text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
short denoising schedules (`LCMScheduler`) and those with full diffusion schedules (`DDIMScheduler`).
default_processing_resolution (`int`, *optional*):
The recommended value of the `processing_resolution` parameter of the pipeline. This value must be set in
the model config. When the pi... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
model_cpu_offload_seq = "text_encoder->unet->vae"
supported_prediction_types = ("depth", "disparity")
def __init__(
self,
unet: UNet2DConditionModel,
vae: AutoencoderKL,
scheduler: Union[DDIMScheduler, LCMScheduler],
text_encoder: CLIPTextModel,
tokenizer: CLIPTo... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
self.register_modules(
unet=unet,
vae=vae,
scheduler=scheduler,
text_encoder=text_encoder,
tokenizer=tokenizer,
)
self.register_to_config(
prediction_type=prediction_type,
scale_invariant=scale_invariant,
shi... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
def check_inputs(
self,
image: PipelineImageInput,
num_inference_steps: int,
ensemble_size: int,
processing_resolution: int,
resample_method_input: str,
resample_method_output: str,
batch_size: int,
ensembling_kwargs: Optional[Dict[str, Any]],
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
"consider increasing the value to at least 3."
)
if ensemble_size > 1 and (self.scale_invariant or self.shift_invariant) and not is_scipy_available():
raise ImportError("Make sure to install scipy if you want to use ensembling.")
if ensemble_size == 1 and output_uncertainty:
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
raise ValueError(f"`processing_resolution` must be a multiple of {self.vae_scale_factor}.")
if resample_method_input not in ("nearest", "nearest-exact", "bilinear", "bicubic", "area"):
raise ValueError(
"`resample_method_input` takes string values compatible with PIL library: "
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
raise ValueError("`latents` and `generator` cannot be used together.")
if ensembling_kwargs is not None:
if not isinstance(ensembling_kwargs, dict):
raise ValueError("`ensembling_kwargs` must be a dictionary.")
if "reduction" in ensembling_kwargs and ensembling_kwargs["re... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
# image checks
num_images = 0
W, H = None, None
if not isinstance(image, list):
image = [image]
for i, img in enumerate(image):
if isinstance(img, np.ndarray) or torch.is_tensor(img):
if img.ndim not in (2, 3, 4):
raise ValueErr... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
num_images += N_i | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
# latents checks
if latents is not None:
if not torch.is_tensor(latents):
raise ValueError("`latents` must be a torch.Tensor.")
if latents.dim() != 4:
raise ValueError(f"`latents` has unsupported dimensions or shape: {latents.shape}.")
if proc... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
if latents.shape != shape_expected:
raise ValueError(f"`latents` has unexpected shape={latents.shape} expected={shape_expected}.")
# generator checks
if generator is not None:
if isinstance(generator, list):
if len(generator) != num_images * ensemble_size:
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
def progress_bar(self, iterable=None, total=None, desc=None, leave=True):
if not hasattr(self, "_progress_bar_config"):
self._progress_bar_config = {}
elif not isinstance(self._progress_bar_config, dict):
raise ValueError(
f"`self._progress_bar_config` should be o... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
@torch.no_grad()
@replace_example_docstring(EXAMPLE_DOC_STRING)
def __call__(
self,
image: PipelineImageInput,
num_inference_steps: Optional[int] = None,
ensemble_size: int = 1,
processing_resolution: Optional[int] = None,
match_input_resolution: bool = True,
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
Args:
image (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`),
`List[torch.Tensor]`: An input image or images used as an input for the depth estimation task. For
arrays and tensors, the expected value range is between `[0, 1]`. Pas... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
ensemble_size (`int`, defaults to `1`):
Number of ensemble predictions. Recommended values are 5 and higher for better precision, or 1 for
faster inference.
processing_resolution (`int`, *optional*, defaults to `None`):
Effective processing resolution. When se... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
Resampling method used to resize input images to `processing_resolution`. The accepted values are:
`"nearest"`, `"nearest-exact"`, `"bilinear"`, `"bicubic"`, or `"area"`.
resample_method_output (`str`, *optional*, defaults to `"bilinear"`):
Resampling method used to resize ou... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
every pixel location, can be either `"median"` or `"mean"`.
- regularizer_strength (`float`, *optional*, defaults to `0.02`): Strength of the regularizer that
pulls the aligned predictions to the unit range from 0 to 1.
- max_iter (`int`, *optional*, defaults to `2`): M... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
function call's output.
generator (`torch.Generator`, or `List[torch.Generator]`, *optional*, defaults to `None`):
Random number generator object to ensure reproducibility.
output_type (`str`, *optional*, defaults to `"np"`):
Preferred format of the output's `pred... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
within the ensemble. These codes can be saved, modified, and used for subsequent calls with the
`latents` argument.
return_dict (`bool`, *optional*, defaults to `True`):
Whether or not to return a [`~pipelines.marigold.MarigoldDepthOutput`] instead of a plain tuple. | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
Examples:
Returns:
[`~pipelines.marigold.MarigoldDepthOutput`] or `tuple`:
If `return_dict` is `True`, [`~pipelines.marigold.MarigoldDepthOutput`] is returned, otherwise a
`tuple` is returned where the first element is the prediction, the second element is the uncert... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
# 1. Check inputs.
num_images = self.check_inputs(
image,
num_inference_steps,
ensemble_size,
processing_resolution,
resample_method_input,
resample_method_output,
batch_size,
ensembling_kwargs,
latents,
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
# 3. Preprocess input images. This function loads input image or images of compatible dimensions `(H, W)`,
# optionally downsamples them to the `processing_resolution` `(PH, PW)`, where
# `max(PH, PW) == processing_resolution`, and pads the dimensions to `(PPH, PPW)` such that these values are
#... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
# 4. Encode input image into latent space. At this step, each of the `N` input images is represented with `E`
# ensemble members. Each ensemble member is an independent diffused prediction, just initialized independently.
# Latents of each such predictions across all input images and all ensemble member... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
# noise. This behavior can be achieved by setting the `output_latent` argument to `True`. The latent space
# dimensions are `(h, w)`. Encoding into latent space happens in batches of size `batch_size`.
# Model invocation: self.vae.encoder.
image_latent, pred_latent = self.prepare_latents(
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
del image
batch_empty_text_embedding = self.empty_text_embedding.to(device=device, dtype=dtype).repeat(
batch_size, 1, 1
) # [B,1024,2]
# 5. Process the denoising loop. All `N * E` latents are processed sequentially in batches of size `batch_size`.
# The unet model takes c... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
for i in self.progress_bar(
range(0, num_images * ensemble_size, batch_size), leave=True, desc="Marigold predictions..."
):
batch_image_latent = image_latent[i : i + batch_size] # [B,4,h,w]
batch_pred_latent = pred_latent[i : i + batch_size] # [B,4,h,w]
effectiv... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
if XLA_AVAILABLE:
xm.mark_step()
pred_latents.append(batch_pred_latent)
pred_latent = torch.cat(pred_latents, dim=0) # [N*E,4,h,w]
del (
pred_latents,
image_latent,
batch_empty_text_embedding,
batch_image_latent,
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
if not output_latent:
pred_latent = None
# 7. Remove padding. The output shape is (PH, PW).
prediction = self.image_processor.unpad_image(prediction, padding) # [N*E,1,PH,PW] | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
# 8. Ensemble and compute uncertainty (when `output_uncertainty` is set). This code treats each of the `N`
# groups of `E` ensemble predictions independently. For each group it computes an ensembled prediction of shape
# `(PH, PW)` and an optional uncertainty map of the same dimensions. After computing ... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
] # [ [[1,1,PH,PW], [1,1,PH,PW]], ... ]
prediction, uncertainty = zip(*prediction) # [[1,1,PH,PW], ... ], [[1,1,PH,PW], ... ]
prediction = torch.cat(prediction, dim=0) # [N,1,PH,PW]
if output_uncertainty:
uncertainty = torch.cat(uncertainty, dim=0) # [N,1,PH,PW]
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
# 9. If `match_input_resolution` is set, the output prediction and the uncertainty are upsampled to match the
# input resolution `(H, W)`. This step may introduce upsampling artifacts, and therefore can be disabled.
# Depending on the downstream use-case, upsampling can be also chosen based on the toler... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
# 10. Prepare the final outputs.
if output_type == "np":
prediction = self.image_processor.pt_to_numpy(prediction) # [N,H,W,1]
if uncertainty is not None and output_uncertainty:
uncertainty = self.image_processor.pt_to_numpy(uncertainty) # [N,H,W,1]
# 11. Offlo... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
def prepare_latents(
self,
image: torch.Tensor,
latents: Optional[torch.Tensor],
generator: Optional[torch.Generator],
ensemble_size: int,
batch_size: int,
) -> Tuple[torch.Tensor, torch.Tensor]:
def retrieve_latents(encoder_output):
if hasattr(enc... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
image_latent = torch.cat(
[
retrieve_latents(self.vae.encode(image[i : i + batch_size]))
for i in range(0, image.shape[0], batch_size)
],
dim=0,
) # [N,4,h,w]
image_latent = image_latent * self.vae.config.scaling_factor
image_l... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
def decode_prediction(self, pred_latent: torch.Tensor) -> torch.Tensor:
if pred_latent.dim() != 4 or pred_latent.shape[1] != self.vae.config.latent_channels:
raise ValueError(
f"Expecting 4D tensor of shape [B,{self.vae.config.latent_channels},H,W]; got {pred_latent.shape}."
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
@staticmethod
def ensemble_depth(
depth: torch.Tensor,
scale_invariant: bool = True,
shift_invariant: bool = True,
output_uncertainty: bool = False,
reduction: str = "median",
regularizer_strength: float = 0.02,
max_iter: int = 2,
tol: float = 1e-3,
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
`scale_invariant=True`). For absolute predictions (`scale_invariant=False` and `shift_invariant=False`)
alignment is skipped and only ensembling is performed. | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
Args:
depth (`torch.Tensor`):
Input ensemble depth maps.
scale_invariant (`bool`, *optional*, defaults to `True`):
Whether to treat predictions as scale-invariant.
shift_invariant (`bool`, *optional*, defaults to `True`):
Whether to tre... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
Maximum number of the alignment solver steps. Refer to `scipy.optimize.minimize` function, `options`
argument.
tol (`float`, *optional*, defaults to `1e-3`):
Alignment solver tolerance. The solver stops when the tolerance is reached.
max_res (`int`, *optional*, de... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
raise ValueError("Pure shift-invariant ensembling is not supported.") | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
def init_param(depth: torch.Tensor):
init_min = depth.reshape(ensemble_size, -1).min(dim=1).values
init_max = depth.reshape(ensemble_size, -1).max(dim=1).values
if scale_invariant and shift_invariant:
init_s = 1.0 / (init_max - init_min).clamp(min=1e-6)
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
def align(depth: torch.Tensor, param: np.ndarray) -> torch.Tensor:
if scale_invariant and shift_invariant:
s, t = np.split(param, 2)
s = torch.from_numpy(s).to(depth).view(ensemble_size, 1, 1, 1)
t = torch.from_numpy(t).to(depth).view(ensemble_size, 1, 1, 1)
... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
def ensemble(
depth_aligned: torch.Tensor, return_uncertainty: bool = False
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
uncertainty = None
if reduction == "mean":
prediction = torch.mean(depth_aligned, dim=0, keepdim=True)
if return_uncer... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
for i, j in torch.combinations(torch.arange(ensemble_size)):
diff = depth_aligned[i] - depth_aligned[j]
cost += (diff**2).mean().sqrt().item()
if regularizer_strength > 0:
prediction, _ = ensemble(depth_aligned, return_uncertainty=False)
err_n... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
res = scipy.optimize.minimize(
partial(cost_fn, depth=depth_to_align),
param,
method="BFGS",
tol=tol,
options={"maxiter": max_iter, "disp": False},
)
return res.x
requires_aligning = scale_invariant or shif... | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
return depth, uncertainty # [1,1,H,W], [1,1,H,W] | 118 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py |
class MarigoldNormalsOutput(BaseOutput):
"""
Output class for Marigold monocular normals prediction pipeline.
Args:
prediction (`np.ndarray`, `torch.Tensor`):
Predicted normals with values in the range [-1, 1]. The shape is always $numimages \times 3 \times height
\times wid... | 119 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
prediction: Union[np.ndarray, torch.Tensor]
uncertainty: Union[None, np.ndarray, torch.Tensor]
latent: Union[None, torch.Tensor] | 119 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
class MarigoldNormalsPipeline(DiffusionPipeline):
"""
Pipeline for monocular normals estimation using the Marigold method: https://marigoldmonodepth.github.io.
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
library implements for all the p... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
Args:
unet (`UNet2DConditionModel`):
Conditional U-Net to denoise the normals latent, conditioned on image latent.
vae (`AutoencoderKL`):
Variational Auto-Encoder (VAE) Model to encode and decode images and predictions to and from latent
representations.
sched... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
The minimum number of denoising diffusion steps that are required to produce a prediction of reasonable
quality with the given model. This value must be set in the model config. When the pipeline is called
without explicitly setting `num_inference_steps`, the default value is used. This is requi... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
with varying optimal processing resolution values.
""" | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
model_cpu_offload_seq = "text_encoder->unet->vae"
supported_prediction_types = ("normals",)
def __init__(
self,
unet: UNet2DConditionModel,
vae: AutoencoderKL,
scheduler: Union[DDIMScheduler, LCMScheduler],
text_encoder: CLIPTextModel,
tokenizer: CLIPTokenizer,
... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
self.register_modules(
unet=unet,
vae=vae,
scheduler=scheduler,
text_encoder=text_encoder,
tokenizer=tokenizer,
)
self.register_to_config(
use_full_z_range=use_full_z_range,
default_denoising_steps=default_denoising_step... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
def check_inputs(
self,
image: PipelineImageInput,
num_inference_steps: int,
ensemble_size: int,
processing_resolution: int,
resample_method_input: str,
resample_method_output: str,
batch_size: int,
ensembling_kwargs: Optional[Dict[str, Any]],
... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
"consider increasing the value to at least 3."
)
if ensemble_size == 1 and output_uncertainty:
raise ValueError(
"Computing uncertainty by setting `output_uncertainty=True` also requires setting `ensemble_size` "
"greater than 1."
)
if ... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
if resample_method_input not in ("nearest", "nearest-exact", "bilinear", "bicubic", "area"):
raise ValueError(
"`resample_method_input` takes string values compatible with PIL library: "
"nearest, nearest-exact, bilinear, bicubic, area."
)
if resample_meth... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
if not isinstance(ensembling_kwargs, dict):
raise ValueError("`ensembling_kwargs` must be a dictionary.")
if "reduction" in ensembling_kwargs and ensembling_kwargs["reduction"] not in ("closest", "mean"):
raise ValueError("`ensembling_kwargs['reduction']` can be either `'clos... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# image checks
num_images = 0
W, H = None, None
if not isinstance(image, list):
image = [image]
for i, img in enumerate(image):
if isinstance(img, np.ndarray) or torch.is_tensor(img):
if img.ndim not in (2, 3, 4):
raise ValueErr... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
num_images += N_i | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# latents checks
if latents is not None:
if not torch.is_tensor(latents):
raise ValueError("`latents` must be a torch.Tensor.")
if latents.dim() != 4:
raise ValueError(f"`latents` has unsupported dimensions or shape: {latents.shape}.")
if proc... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
if latents.shape != shape_expected:
raise ValueError(f"`latents` has unexpected shape={latents.shape} expected={shape_expected}.")
# generator checks
if generator is not None:
if isinstance(generator, list):
if len(generator) != num_images * ensemble_size:
... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
def progress_bar(self, iterable=None, total=None, desc=None, leave=True):
if not hasattr(self, "_progress_bar_config"):
self._progress_bar_config = {}
elif not isinstance(self._progress_bar_config, dict):
raise ValueError(
f"`self._progress_bar_config` should be o... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
@torch.no_grad()
@replace_example_docstring(EXAMPLE_DOC_STRING)
def __call__(
self,
image: PipelineImageInput,
num_inference_steps: Optional[int] = None,
ensemble_size: int = 1,
processing_resolution: Optional[int] = None,
match_input_resolution: bool = True,
... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
Args:
image (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`),
`List[torch.Tensor]`: An input image or images used as an input for the normals estimation task. For
arrays and tensors, the expected value range is between `[0, 1]`. P... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
ensemble_size (`int`, defaults to `1`):
Number of ensemble predictions. Recommended values are 5 and higher for better precision, or 1 for
faster inference.
processing_resolution (`int`, *optional*, defaults to `None`):
Effective processing resolution. When se... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
Resampling method used to resize input images to `processing_resolution`. The accepted values are:
`"nearest"`, `"nearest-exact"`, `"bilinear"`, `"bicubic"`, or `"area"`.
resample_method_output (`str`, *optional*, defaults to `"bilinear"`):
Resampling method used to resize ou... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
every pixel location, can be either `"closest"` or `"mean"`.
latents (`torch.Tensor`, *optional*, defaults to `None`):
Latent noise tensors to replace the random initialization. These can be taken from the previous
function call's output.
generator (`torch.Generat... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
output_latent (`bool`, *optional*, defaults to `False`):
When enabled, the output's `latent` field contains the latent codes corresponding to the predictions
within the ensemble. These codes can be saved, modified, and used for subsequent calls with the
`latents` argument... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
Examples:
Returns:
[`~pipelines.marigold.MarigoldNormalsOutput`] or `tuple`:
If `return_dict` is `True`, [`~pipelines.marigold.MarigoldNormalsOutput`] is returned, otherwise a
`tuple` is returned where the first element is the prediction, the second element is the un... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# 1. Check inputs.
num_images = self.check_inputs(
image,
num_inference_steps,
ensemble_size,
processing_resolution,
resample_method_input,
resample_method_output,
batch_size,
ensembling_kwargs,
latents,
... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# 3. Preprocess input images. This function loads input image or images of compatible dimensions `(H, W)`,
# optionally downsamples them to the `processing_resolution` `(PH, PW)`, where
# `max(PH, PW) == processing_resolution`, and pads the dimensions to `(PPH, PPW)` such that these values are
#... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# 4. Encode input image into latent space. At this step, each of the `N` input images is represented with `E`
# ensemble members. Each ensemble member is an independent diffused prediction, just initialized independently.
# Latents of each such predictions across all input images and all ensemble member... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# noise. This behavior can be achieved by setting the `output_latent` argument to `True`. The latent space
# dimensions are `(h, w)`. Encoding into latent space happens in batches of size `batch_size`.
# Model invocation: self.vae.encoder.
image_latent, pred_latent = self.prepare_latents(
... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
del image
batch_empty_text_embedding = self.empty_text_embedding.to(device=device, dtype=dtype).repeat(
batch_size, 1, 1
) # [B,1024,2]
# 5. Process the denoising loop. All `N * E` latents are processed sequentially in batches of size `batch_size`.
# The unet model takes c... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
for i in self.progress_bar(
range(0, num_images * ensemble_size, batch_size), leave=True, desc="Marigold predictions..."
):
batch_image_latent = image_latent[i : i + batch_size] # [B,4,h,w]
batch_pred_latent = pred_latent[i : i + batch_size] # [B,4,h,w]
effectiv... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
if XLA_AVAILABLE:
xm.mark_step()
pred_latents.append(batch_pred_latent)
pred_latent = torch.cat(pred_latents, dim=0) # [N*E,4,h,w]
del (
pred_latents,
image_latent,
batch_empty_text_embedding,
batch_image_latent,
... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
if not output_latent:
pred_latent = None
# 7. Remove padding. The output shape is (PH, PW).
prediction = self.image_processor.unpad_image(prediction, padding) # [N*E,3,PH,PW] | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# 8. Ensemble and compute uncertainty (when `output_uncertainty` is set). This code treats each of the `N`
# groups of `E` ensemble predictions independently. For each group it computes an ensembled prediction of shape
# `(PH, PW)` and an optional uncertainty map of the same dimensions. After computing ... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
prediction = torch.cat(prediction, dim=0) # [N,3,PH,PW]
if output_uncertainty:
uncertainty = torch.cat(uncertainty, dim=0) # [N,1,PH,PW]
else:
uncertainty = None | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# 9. If `match_input_resolution` is set, the output prediction and the uncertainty are upsampled to match the
# input resolution `(H, W)`. This step may introduce upsampling artifacts, and therefore can be disabled.
# After upsampling, the native resolution normal maps are renormalized to unit length to... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
uncertainty, original_resolution, resample_method_output, is_aa=False
) # [N,1,H,W] | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# 10. Prepare the final outputs.
if output_type == "np":
prediction = self.image_processor.pt_to_numpy(prediction) # [N,H,W,3]
if uncertainty is not None and output_uncertainty:
uncertainty = self.image_processor.pt_to_numpy(uncertainty) # [N,H,W,1]
# 11. Offlo... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
# Copied from diffusers.pipelines.marigold.pipeline_marigold_depth.MarigoldDepthPipeline.prepare_latents
def prepare_latents(
self,
image: torch.Tensor,
latents: Optional[torch.Tensor],
generator: Optional[torch.Generator],
ensemble_size: int,
batch_size: int,
) -... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
image_latent = torch.cat(
[
retrieve_latents(self.vae.encode(image[i : i + batch_size]))
for i in range(0, image.shape[0], batch_size)
],
dim=0,
) # [N,4,h,w]
image_latent = image_latent * self.vae.config.scaling_factor
image_l... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
def decode_prediction(self, pred_latent: torch.Tensor) -> torch.Tensor:
if pred_latent.dim() != 4 or pred_latent.shape[1] != self.vae.config.latent_channels:
raise ValueError(
f"Expecting 4D tensor of shape [B,{self.vae.config.latent_channels},H,W]; got {pred_latent.shape}."
... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
norm = torch.norm(normals, dim=1, keepdim=True)
normals /= norm.clamp(min=eps)
return normals
@staticmethod
def ensemble_normals(
normals: torch.Tensor, output_uncertainty: bool, reduction: str = "closest"
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
"""
Ensemb... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
Returns:
A tensor of aligned and ensembled normals maps with shape `(1, 3, H, W)` and optionally a tensor of
uncertainties of shape `(1, 1, H, W)`.
"""
if normals.dim() != 4 or normals.shape[1] != 3:
raise ValueError(f"Expecting 4D tensor of shape [B,3,H,W]; got {norm... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
if reduction == "mean":
return mean_normals, uncertainty # [1,3,H,W], [1,1,H,W]
closest_indices = sim_cos.argmax(dim=0, keepdim=True) # [1,1,H,W]
closest_indices = closest_indices.repeat(1, 3, 1, 1) # [1,3,H,W]
closest_normals = torch.gather(normals, 0, closest_indices) # [1,3,H... | 120 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py |
class UniDiffuserTextDecoder(ModelMixin, ConfigMixin, ModuleUtilsMixin):
"""
Text decoder model for a image-text [UniDiffuser](https://arxiv.org/pdf/2303.06555.pdf) model. This is used to
generate text from the UniDiffuser image-text embedding. | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
Parameters:
prefix_length (`int`):
Max number of prefix tokens that will be supplied to the model.
prefix_inner_dim (`int`):
The hidden size of the incoming prefix embeddings. For UniDiffuser, this would be the hidden dim of the
CLIP text encoder.
prefix_hidde... | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
n_layer (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
n_head (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
n_inner (`int`, *optional*, defaults to None):
D... | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
The epsilon to use in the layer normalization layers.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
scale_attn... | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
dot-product/softmax to float() when training with mixed precision.
""" | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
_keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
@register_to_config
def __init__(
self,
prefix_length: int,
prefix_inner_dim: int,
prefix_hidden_dim: Optional[int] = None,
vocab_size: int = 50257, # Start of GPT2 config args
... | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
if prefix_inner_dim != n_embd and prefix_hidden_dim is None:
raise ValueError(
f"`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and"
f" `n_embd`: {n_embd} are not equal."
)
self.prefix_inner_dim = prefix_inner_dim
... | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
gpt_config = GPT2Config(
vocab_size=vocab_size,
n_positions=n_positions,
n_embd=n_embd,
n_layer=n_layer,
n_head=n_head,
n_inner=n_inner,
activation_function=activation_function,
resid_pdrop=resid_pdrop,
embd_pdro... | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
def forward(
self,
input_ids: torch.Tensor,
prefix_embeds: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
):
"""
Args:
input_ids (`torch.Tensor` of shape `(N, max_seq_len)`):
Text... | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
embedding_cat = torch.cat((prefix_embeds, embedding_text), dim=1) | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
if labels is not None:
dummy_token = self.get_dummy_token(input_ids.shape[0], input_ids.device)
labels = torch.cat((dummy_token, input_ids), dim=1)
out = self.transformer(inputs_embeds=embedding_cat, labels=labels, attention_mask=attention_mask)
if self.prefix_hidden_dim is not N... | 121 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.