Diffusers 文档
用于计算机视觉任务的万寿菊管线
并获得增强的文档体验
开始使用
用于计算机视觉任务的万寿菊管线
万寿菊在 Repurposing Diffusion-Based Image Generators for Monocular Depth Estimation 中被提出,这是一篇 CVPR 2024 口头报告论文,作者包括 Bingxin Ke、Anton Obukhov、Shengyu Huang、Nando Metzger、Rodrigo Caye Daudt 和 Konrad Schindler。其想法是重新利用文本到图像潜在扩散模型 (LDM) 丰富的生成先验知识,用于传统的计算机视觉任务。最初,这个想法被探索用于微调 Stable Diffusion 以进行单目深度估计,如上面的预告片所示。 之后,
- Tianfu Wang 训练了第一个万寿菊的潜在一致性模型 (LCM),解锁了快速单步推理;
- Kevin Qu 将该方法扩展到表面法线估计;
- Anton Obukhov 将管线和文档贡献到 diffusers 中(由 YiYi Xu 和 Sayak Paul 启用和支持)。
论文的摘要是
单目深度估计是一项基础的计算机视觉任务。从单张图像中恢复 3D 深度在几何上是病态问题,并且需要场景理解,因此深度学习的兴起带来了突破,这并不令人意外。单目深度估计器的显著进步与模型容量的增长同步,从相对适中的 CNN 到大型 Transformer 架构。然而,当呈现具有不熟悉内容和布局的图像时,单目深度估计器往往会遇到困难,因为它们对视觉世界的知识受到训练期间所见数据的限制,并且受到对新领域零样本泛化的挑战。这促使我们探索最近的生成扩散模型中捕获的广泛先验知识是否能够实现更好、更具泛化性的深度估计。我们推出了 Marigold,这是一种从 Stable Diffusion 衍生而来,并保留了其丰富先验知识的仿射不变单目深度估计方法。该估计器仅使用合成训练数据,即可在单个 GPU 上于几天内完成微调。它在各种数据集上都实现了最先进的性能,在特定情况下性能提升超过 20%。项目页面:https://marigoldmonodepth.github.io。
可用的 Pipeline
每个 pipeline 支持一项计算机视觉任务,该任务以 RGB 图像作为输入,并生成感兴趣模态的预测,例如输入图像的深度图。目前,已实现以下任务
Pipeline | 预测的模态 | 演示 |
---|---|---|
MarigoldDepthPipeline | 深度, 视差 | 快速演示 (LCM), 慢速原始演示 (DDIM) |
MarigoldNormalsPipeline | 表面法线 | 快速演示 (LCM) |
可用的 Checkpoint
原始 checkpoint 可以在 PRS-ETH Hugging Face 组织下找到。
请务必查看调度器 指南,了解如何探索调度器速度和质量之间的权衡,并查看 跨 pipeline 重用组件 部分,了解如何有效地将相同组件加载到多个 pipeline 中。此外,要了解更多关于减少此 pipeline 内存使用量的信息,请参阅此处的[“减少内存使用量”]部分。
Marigold pipeline 仅使用 DDIMScheduler
和 LCMScheduler
进行设计和测试。根据调度器的不同,获得可靠预测所需的推理步骤数也会有所不同,并且没有适用于所有调度器的通用最佳值。因此,pipeline 的 __call__
方法中 num_inference_steps
的默认值设置为 None
(请参阅 API 参考)。除非显式设置,否则其值将从 checkpoint 配置 model_index.json
中获取。这样做是为了确保仅使用 image
参数调用 pipeline 时也能获得高质量的预测结果。
另请参阅 Marigold 使用示例。
MarigoldDepthPipeline
class diffusers.MarigoldDepthPipeline
< source >( unet: UNet2DConditionModel vae: AutoencoderKL scheduler: typing.Union[diffusers.schedulers.scheduling_ddim.DDIMScheduler, diffusers.schedulers.scheduling_lcm.LCMScheduler] text_encoder: CLIPTextModel tokenizer: CLIPTokenizer prediction_type: typing.Optional[str] = None scale_invariant: typing.Optional[bool] = True shift_invariant: typing.Optional[bool] = True default_denoising_steps: typing.Optional[int] = None default_processing_resolution: typing.Optional[int] = None )
参数
- unet (
UNet2DConditionModel
) — 条件 U-Net,用于对深度潜在变量进行去噪,并以图像潜在变量为条件。 - vae (
AutoencoderKL
) — 变分自编码器 (VAE) 模型,用于将图像和预测编码和解码为潜在表示形式和从潜在表示形式解码。 - scheduler (
DDIMScheduler
或LCMScheduler
) — 调度器,与unet
结合使用,用于对编码后的图像潜在变量进行去噪。 - text_encoder (
CLIPTextModel
) — 文本编码器,用于空文本嵌入。 - tokenizer (
CLIPTokenizer
) — CLIP 分词器。 - prediction_type (
str
, 可选) — 模型进行的预测类型。 - scale_invariant (
bool
, 可选) — 模型属性,指定预测的深度图是否具有尺度不变性。此值必须在模型配置中设置。当与shift_invariant=True
标志一起使用时,该模型也称为“仿射不变”。注意:不支持覆盖此值。 - shift_invariant (
bool
, 可选) — 模型属性,指定预测的深度图是否具有平移不变性。此值必须在模型配置中设置。当与scale_invariant=True
标志一起使用时,该模型也称为“仿射不变”。注意:不支持覆盖此值。 - default_denoising_steps (
int
, 可选) — 生成具有给定模型的合理质量预测所需的最小去噪扩散步骤数。此值必须在模型配置中设置。当在未显式设置num_inference_steps
的情况下调用 pipeline 时,将使用默认值。这是确保使用与 pipeline 兼容的各种模型风格(例如,依赖于非常短的去噪计划 (LCMScheduler
) 和具有完整扩散计划 (DDIMScheduler
) 的模型)获得合理结果所必需的。 - default_processing_resolution (
int
, 可选) — pipeline 的processing_resolution
参数的建议值。此值必须在模型配置中设置。当在未显式设置processing_resolution
的情况下调用 pipeline 时,将使用默认值。这是确保使用以不同的最佳处理分辨率值训练的各种模型风格获得合理结果所必需的。
使用 Marigold 方法进行单目深度估计的 Pipeline:https://marigoldmonodepth.github.io。
此模型继承自 DiffusionPipeline。查看超类文档,了解库为所有 pipeline 实现的通用方法(例如,下载或保存、在特定设备上运行等)。
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] num_inference_steps: typing.Optional[int] = None ensemble_size: int = 1 processing_resolution: typing.Optional[int] = None match_input_resolution: bool = True resample_method_input: str = 'bilinear' resample_method_output: str = 'bilinear' batch_size: int = 1 ensembling_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None latents: typing.Union[torch.Tensor, typing.List[torch.Tensor], NoneType] = None generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None output_type: str = 'np' output_uncertainty: bool = False output_latent: bool = False return_dict: bool = True ) → MarigoldDepthOutput 或 tuple
参数
- image (
PIL.Image.Image
,np.ndarray
,torch.Tensor
,List[PIL.Image.Image]
,List[np.ndarray]
), —List[torch.Tensor]
: 用作深度估计任务输入的输入图像或图像列表。对于数组和张量,预期值范围在[0, 1]
之间。可以通过提供四维数组或张量来传递一批图像。此外,还可以传递二维或三维数组或张量的图像列表。在后一种情况下,所有列表元素必须具有相同的宽度和高度。 - num_inference_steps (
int
, 可选, 默认为None
) — 推理期间的去噪扩散步骤数。默认值None
会导致自动选择。对于完整的 Marigold 模型,步骤数应至少为 10,对于 Marigold-LCM 模型,步骤数应介于 1 到 4 之间。 - ensemble_size (
int
, 默认为1
) — 集成预测的数量。建议值为 5 或更高以获得更好的精度,或 1 以获得更快的推理速度。 - processing_resolution (
int
, 可选, 默认为None
) — 有效处理分辨率。设置为0
时,与较大的输入图像尺寸匹配。这将产生更清晰的预测,但也可能导致全局上下文的整体丢失。默认值None
解析为模型配置中的最佳值。 - match_input_resolution (
bool
, 可选, 默认为True
) — 启用后,输出预测将调整大小以匹配输入尺寸。禁用后,输出的较长边将等于processing_resolution
。 - resample_method_input (
str
, 可选, 默认为"bilinear"
) — 用于调整输入图像大小至processing_resolution
的重采样方法。可接受的值为:"nearest"
、"nearest-exact"
、"bilinear"
、"bicubic"
或"area"
。 - resample_method_output (
str
, 可选, 默认为"bilinear"
) — 用于调整输出预测大小以匹配输入分辨率的重采样方法。可接受的值为:"nearest"
、"nearest-exact"
、"bilinear"
、"bicubic"
或"area"
。 - batch_size (
int
, 可选, 默认为1
) — 批大小;仅在设置ensemble_size
或传递图像张量时有效。 - ensembling_kwargs (
dict
, 可选, 默认为None
) — 用于精确控制集成 (ensembling) 的额外字典参数。以下选项可用:- reduction (
str
, 可选, 默认为"median"
): 定义在每个像素位置应用的集成函数,可以是"median"
或"mean"
。 - regularizer_strength (
float
, 可选, 默认为0.02
): 正则化强度的值,用于将对齐的预测结果拉向 0 到 1 的单位范围。 - max_iter (
int
, 可选, 默认为2
): 对齐求解器步骤的最大数量。请参考scipy.optimize.minimize
函数的options
参数。 - tol (
float
, 可选, 默认为1e-3
): 对齐求解器的容差。当达到容差时,求解器停止。 - max_res (
int
, 可选, 默认为None
): 执行对齐的分辨率;None
表示与processing_resolution
匹配。
- reduction (
- latents (
torch.Tensor
, 或List[torch.Tensor]
, 可选, 默认为None
) — 用于替换随机初始化的潜在噪声张量。这些可以从先前函数调用的输出中获取。 - generator (
torch.Generator
, 或List[torch.Generator]
, 可选, 默认为None
) — 随机数生成器对象,用于确保可重复性。 - output_type (
str
, 可选, 默认为"np"
) — 输出的prediction
和可选的uncertainty
字段的首选格式。可接受的值为:"np"
(numpy 数组) 或"pt"
(torch 张量)。 - output_uncertainty (
bool
, 可选, 默认为False
) — 启用后,如果将ensemble_size
参数设置为大于 2 的值,则输出的uncertainty
字段将包含预测不确定性图。 - output_latent (
bool
, 可选, 默认为False
) — 启用后,输出的latent
字段将包含与集成内的预测相对应的潜在代码。这些代码可以被保存、修改,并用于后续使用latents
参数的调用。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 MarigoldDepthOutput 而不是纯元组。
返回值
MarigoldDepthOutput 或 tuple
如果 return_dict
为 True
,则返回 MarigoldDepthOutput,否则返回一个 tuple
,其中第一个元素是预测结果,第二个元素是不确定性(或 None
),第三个元素是潜在变量(或 None
)。
调用管道时调用的函数。
示例
>>> import diffusers
>>> import torch
>>> pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
... "prs-eth/marigold-depth-lcm-v1-0", variant="fp16", torch_dtype=torch.float16
... ).to("cuda")
>>> image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
>>> depth = pipe(image)
>>> vis = pipe.image_processor.visualize_depth(depth.prediction)
>>> vis[0].save("einstein_depth.png")
>>> depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
>>> depth_16bit[0].save("einstein_depth_16bit.png")
集成深度
< source >( depth: 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 = 0.001 max_res: int = 1024 ) → 对齐和集成的深度图张量,以及可选的相同形状的不确定性张量
参数
- depth (
torch.Tensor
) — 输入的集成深度图。 - scale_invariant (
bool
, 可选, 默认为True
) — 是否将预测视为尺度不变的。 - shift_invariant (
bool
, 可选, 默认为True
) — 是否将预测视为平移不变的。 - output_uncertainty (
bool
, 可选, 默认为False
) — 是否输出不确定性图。 - reduction (
str
, 可选, 默认为"median"
) — 用于集成对齐预测的缩减方法。可接受的值为:"mean"
和"median"
。 - regularizer_strength (
float
, 可选, 默认为0.02
) — 正则化强度的值,用于将对齐的预测结果拉向 0 到 1 的单位范围。 - max_iter (
int
, 可选, 默认为2
) — 对齐求解器步骤的最大数量。请参考scipy.optimize.minimize
函数的options
参数。 - tol (
float
, 可选, 默认为1e-3
) — 对齐求解器的容差。当达到容差时,求解器停止。 - max_res (
int
, 可选, 默认为1024
) — 执行对齐的分辨率;None
表示与processing_resolution
匹配。
返回值
对齐和集成的深度图张量,以及可选的相同形状的不确定性张量
(1, 1, H, W)
.
集成由 depth
张量表示的深度图,预期形状为 (B, 1, H, W)
,其中 B 是给定尺寸为 (H x W)
的预测的集成成员数量。 尽管此函数是为深度图设计的,但它也可以用于视差图,只要输入张量值为非负数即可。 当预测具有一个或多个自由度时,即当它们是仿射不变 (scale_invariant=True
和 shift_invariant=True
) 或仅尺度不变 (仅 scale_invariant=True
) 时,就会发生对齐。 对于绝对预测 (scale_invariant=False
和 shift_invariant=False
),将跳过对齐,仅执行集成。
MarigoldNormalsPipeline
class diffusers.MarigoldNormalsPipeline
< source >( unet: UNet2DConditionModel vae: AutoencoderKL scheduler: typing.Union[diffusers.schedulers.scheduling_ddim.DDIMScheduler, diffusers.schedulers.scheduling_lcm.LCMScheduler] text_encoder: CLIPTextModel tokenizer: CLIPTokenizer prediction_type: typing.Optional[str] = None use_full_z_range: typing.Optional[bool] = True default_denoising_steps: typing.Optional[int] = None default_processing_resolution: typing.Optional[int] = None )
参数
- unet (
UNet2DConditionModel
) — 用于去噪法线潜在空间的条件 U-Net,以图像潜在空间为条件。 - vae (
AutoencoderKL
) — 变分自动编码器 (VAE) 模型,用于将图像和预测编码和解码为潜在表示以及从潜在表示解码。 - scheduler (
DDIMScheduler
orLCMScheduler
) — 调度器,与unet
结合使用,以去噪编码后的图像潜在空间。 - text_encoder (
CLIPTextModel
) — 文本编码器,用于空文本嵌入。 - tokenizer (
CLIPTokenizer
) — CLIP 分词器。 - prediction_type (
str
, optional) — 模型进行的预测类型。 - use_full_z_range (
bool
, optional) — 此模型预测的法线是否使用 Z 维度的完整范围,还是仅使用其正半部分。 - default_denoising_steps (
int
, optional) — 产生具有给定模型的合理质量预测所需的最小去噪扩散步骤数。此值必须在模型配置中设置。当在没有显式设置num_inference_steps
的情况下调用管道时,将使用默认值。这是确保与管道兼容的各种模型风格(例如,依赖于非常短的去噪计划 (LCMScheduler
) 和具有完整扩散计划 (DDIMScheduler
) 的模型)获得合理结果所必需的。 - default_processing_resolution (
int
, optional) — 管道的processing_resolution
参数的建议值。此值必须在模型配置中设置。当在没有显式设置processing_resolution
的情况下调用管道时,将使用默认值。这是确保使用以不同的最佳处理分辨率值训练的各种模型风格获得合理结果所必需的。
使用 Marigold 方法进行单目法线估计的管道: https://marigoldmonodepth.github.io。
此模型继承自 DiffusionPipeline。查看超类文档,了解库为所有 pipeline 实现的通用方法(例如,下载或保存、在特定设备上运行等)。
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] num_inference_steps: typing.Optional[int] = None ensemble_size: int = 1 processing_resolution: typing.Optional[int] = None match_input_resolution: bool = True resample_method_input: str = 'bilinear' resample_method_output: str = 'bilinear' batch_size: int = 1 ensembling_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None latents: typing.Union[torch.Tensor, typing.List[torch.Tensor], NoneType] = None generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None output_type: str = 'np' output_uncertainty: bool = False output_latent: bool = False return_dict: bool = True ) → MarigoldNormalsOutput 或 tuple
参数
- image (
PIL.Image.Image
,np.ndarray
,torch.Tensor
,List[PIL.Image.Image]
,List[np.ndarray]
), —List[torch.Tensor]
: 用作法线估计任务输入的输入图像或图像列表。对于数组和张量,期望值范围在[0, 1]
之间。可以通过提供四维数组或张量来传递一批图像。此外,还可以传递二维或三维数组或张量图像的列表。在后一种情况下,所有列表元素必须具有相同的宽度和高度。 - num_inference_steps (
int
, optional, defaults toNone
) — 推理期间的去噪扩散步骤数。默认值None
会导致自动选择。对于完整的 Marigold 模型,步骤数应至少为 10,对于 Marigold-LCM 模型,步骤数应在 1 到 4 之间。 - ensemble_size (
int
, defaults to1
) — 集成预测的数量。建议值为 5 或更高以获得更高的精度,或 1 以获得更快的推理速度。 - processing_resolution (
int
, optional, defaults toNone
) — 有效处理分辨率。设置为0
时,与较大的输入图像尺寸匹配。这会产生更清晰的预测,但也可能导致全局上下文的整体丢失。默认值None
解析为模型配置中的最佳值。 - match_input_resolution (
bool
, optional, defaults toTrue
) — 启用后,输出预测将调整大小以匹配输入尺寸。禁用后,输出的较长边将等于processing_resolution
。 - resample_method_input (
str
, optional, defaults to"bilinear"
) — 用于将输入图像大小调整为processing_resolution
的重采样方法。接受的值为:"nearest"
、"nearest-exact"
、"bilinear"
、"bicubic"
或"area"
。 - resample_method_output (
str
, optional, defaults to"bilinear"
) — 用于调整输出预测大小以匹配输入分辨率的重采样方法。接受的值为"nearest"
、"nearest-exact"
、"bilinear"
、"bicubic"
或"area"
。 - batch_size (
int
, optional, defaults to1
) — 批量大小;仅在设置ensemble_size
或传递图像张量时才有意义。 - ensembling_kwargs (
dict
, optional, defaults toNone
) — 用于精确集成控制的参数的额外字典。以下选项可用:- reduction (
str
, optional, defaults to"closest"
): 定义在每个像素位置应用的集成函数,可以是"closest"
或"mean"
。
- reduction (
- latents (
torch.Tensor
, optional, defaults toNone
) — 用于替换随机初始化的潜在噪声张量。这些可以从先前函数调用的输出中获取。 - generator (
torch.Generator
, orList[torch.Generator]
, optional, defaults toNone
) — 随机数生成器对象,用于确保可重复性。 - output_type (
str
, optional, defaults to"np"
) — 输出的prediction
和可选的uncertainty
字段的首选格式。接受的值为:"np"
(numpy 数组) 或"pt"
(torch 张量)。 - output_uncertainty (
bool
, optional, defaults toFalse
) — 启用后,如果ensemble_size
参数设置为大于 2 的值,则输出的uncertainty
字段包含预测不确定性图。 - output_latent (
bool
, optional, defaults toFalse
) — 启用后,输出的latent
字段包含与集成中的预测相对应的潜在代码。这些代码可以保存、修改,并用于后续使用latents
参数的调用。 - return_dict (
bool
, optional, defaults toTrue
) — 是否返回 MarigoldNormalsOutput 而不是普通元组。
返回值
MarigoldNormalsOutput 或 tuple
如果 return_dict
为 True
,则返回 MarigoldNormalsOutput,否则返回一个 tuple
,其中第一个元素是预测,第二个元素是不确定性(或 None
),第三个元素是潜在空间(或 None
)。
调用管道时调用的函数。
示例
>>> import diffusers
>>> import torch
>>> pipe = diffusers.MarigoldNormalsPipeline.from_pretrained(
... "prs-eth/marigold-normals-lcm-v0-1", variant="fp16", torch_dtype=torch.float16
... ).to("cuda")
>>> image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
>>> normals = pipe(image)
>>> vis = pipe.image_processor.visualize_normals(normals.prediction)
>>> vis[0].save("einstein_normals.png")
ensemble_normals
< source >( normals: Tensor output_uncertainty: bool reduction: str = 'closest' )
集成由 normals
张量表示的法线贴图,期望形状为 (B, 3, H, W)
,其中 B 是给定尺寸为 (H x W)
的预测的集成成员数量。
MarigoldDepthOutput
class diffusers.pipelines.marigold.MarigoldDepthOutput
< source >( prediction: typing.Union[numpy.ndarray, torch.Tensor] uncertainty: typing.Union[NoneType, numpy.ndarray, torch.Tensor] latent: typing.Optional[torch.Tensor] )
参数
- prediction (
np.ndarray
,torch.Tensor
) — 预测的深度图,取值范围为 [0, 1]。形状始终为 $numimages imes 1 imes height imes width$,无论图像是以 4D 数组还是列表形式传递。 - uncertainty (
None
,np.ndarray
,torch.Tensor
) — 从集成计算的不确定性图,取值范围为 [0, 1]。形状为 $numimages imes 1 imes height imes width$。 - latent (
None
,torch.Tensor
) — 与预测相对应的潜在特征,与管道的latents
参数兼容。形状为 $numimages * numensemble imes 4 imes latentheight imes latentwidth$。
Marigold 单目深度预测管道的输出类。
MarigoldNormalsOutput
class diffusers.pipelines.marigold.MarigoldNormalsOutput
< source >( prediction: typing.Union[numpy.ndarray, torch.Tensor] uncertainty: typing.Union[NoneType, numpy.ndarray, torch.Tensor] latent: typing.Optional[torch.Tensor] )
参数
- prediction (
np.ndarray
,torch.Tensor
) — 预测的法线,取值范围为 [-1, 1]。形状始终为 $numimages imes 3 imes height imes width$,无论图像是以 4D 数组还是列表形式传递。 - uncertainty (
None
,np.ndarray
,torch.Tensor
) — 从集成计算的不确定性图,取值范围为 [0, 1]。形状为 $numimages imes 1 imes height imes width$。 - latent (
None
,torch.Tensor
) — 与预测相对应的潜在特征,与管道的latents
参数兼容。形状为 $numimages * numensemble imes 4 imes latentheight imes latentwidth$。
Marigold 单目法线预测管道的输出类。