GaudiStableDiffusionPipeline
GaudiStableDiffusionPipeline
类支持在 HPU 上执行文本到图像的生成。它继承自 GaudiDiffusionPipeline
类,后者是任何类型的扩散器 pipeline 的父类。
为了充分利用它,它应该与针对 HPU 优化的调度器相关联,例如 GaudiDDIMScheduler
。
GaudiStableDiffusionPipeline
class optimum.habana.diffusers.GaudiStableDiffusionPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True use_habana: bool = False use_hpu_graphs: bool = False gaudi_config: Union = None bf16_full_eval: bool = False )
参数
- vae (
AutoencoderKL
) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示和从潜在表示解码图像。 - text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
- tokenizer (
~transformers.CLIPTokenizer
) — 用于标记文本的CLIPTokenizer
。 - unet (
UNet2DConditionModel
) — 用于去噪编码图像潜在空间的UNet2DConditionModel
。 - scheduler (
SchedulerMixin
) — 调度器,与unet
结合使用以去噪编码图像潜在空间。可以是DDIMScheduler
、LMSDiscreteScheduler
或PNDMScheduler
之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分类模块,用于评估生成的图像是否可能被认为具有攻击性或有害。有关模型潜在危害的更多详细信息,请参阅模型卡。 - feature_extractor (CLIPImageProcessor) —
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。 - use_habana (bool, 默认为
False
) — 是否使用 Gaudi (True
) 或 CPU (False
)。 - use_hpu_graphs (bool, 默认为
False
) — 是否使用 HPU graphs。 - gaudi_config (Union[str, GaudiConfig], 默认为
None
) — 要使用的 Gaudi 配置。可以是用于从 Hub 下载的字符串。或者可以传递先前初始化的配置。 - bf16_full_eval (bool, 默认为
False
) — 是否使用完整的 bfloat16 评估而不是 32 位。与 fp32/混合精度相比,这将更快并节省内存,但可能会损害生成的图像。
- 生成操作以批次方式执行
- 添加了两个
mark_step()
以支持惰性模式 - 添加了对 HPU graphs 的支持
__call__
< source >( prompt: Union = None height: Optional = None width: Optional = None num_inference_steps: int = 50 timesteps: List = None guidance_scale: float = 7.5 negative_prompt: Union = None num_images_per_prompt: Optional = 1 batch_size: int = 1 eta: float = 0.0 generator: Union = None latents: Optional = None prompt_embeds: Optional = None negative_prompt_embeds: Optional = None ip_adapter_image: Union = None output_type: Optional = 'pil' return_dict: bool = True callback: Optional = None callback_steps: int = 1 cross_attention_kwargs: Optional = None guidance_rescale: float = 0.0 clip_skip: Optional = None callback_on_step_end: Optional = None callback_on_step_end_tensor_inputs: List = ['latents'] profiling_warmup_steps: Optional = 0 profiling_steps: Optional = 0 **kwargs ) → GaudiStableDiffusionPipelineOutput
或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的 prompt。如果未定义,则需要传递prompt_embeds
。 - height (
int
, optional, defaults toself.unet.config.sample_size * self.vae_scale_factor
) — 生成图像的高度,单位为像素。 - width (
int
, optional, defaults toself.unet.config.sample_size * self.vae_scale_factor
) — 生成图像的宽度,单位为像素。 - num_inference_steps (
int
, optional, defaults to 50) — 推理步骤数。更多的去噪步骤通常会带来更高质量的图像,但会牺牲推理速度。 - timesteps (
List[int]
, optional) — 时间步长。用于去噪过程的自定义时间步长,适用于调度器在其set_timesteps
方法中支持 `timesteps` 参数的情况。 如果未定义,则当传递 `num_inference_steps` 时将使用默认行为。 必须按降序排列。 - guidance_scale (
float
, optional, defaults to 7.5) — 引导比例。更高的引导比例值会鼓励模型生成与文本prompt
更紧密相关的图像,但会以降低图像质量为代价。 当guidance_scale > 1
时,引导比例生效。 - negative_prompt (
str
orList[str]
, optional) — 负面提示。用于引导图像生成中不应包含的内容的提示。 如果未定义,则需要传递negative_prompt_embeds
。 当不使用引导(guidance_scale < 1
)时忽略。 - num_images_per_prompt (
int
, optional, defaults to 1) — 每提示图像数量。每个提示生成的图像数量。 - batch_size (
int
, optional, defaults to 1) — 批大小。一个批次中的图像数量。 - eta (
float
, optional, defaults to 0.0) — eta。对应于 DDIM 论文中的参数 eta (η)。 仅适用于~schedulers.DDIMScheduler
,在其他调度器中将被忽略。 - generator (
torch.Generator
orList[torch.Generator]
, optional) — 生成器。用于使生成具有确定性的torch.Generator
。 - latents (
torch.FloatTensor
, optional) — 潜在变量。从高斯分布中预生成的噪声潜在变量,用作图像生成的输入。 可用于使用不同的提示调整相同的生成。 如果未提供,则通过使用提供的随机generator
采样来生成潜在张量。 - prompt_embeds (
torch.FloatTensor
, optional) — 提示嵌入。预生成的文本嵌入。 可用于轻松调整文本输入(提示权重)。 如果未提供,则从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.FloatTensor
, optional) — 负面提示嵌入。预生成的负面文本嵌入。 可用于轻松调整文本输入(提示权重)。 如果未提供,则从 `negative_prompt` 输入参数生成 `negative_prompt_embeds`。 ip_adapter_image — (`PipelineImageInput`, *optional*): 与 IP 适配器一起使用的可选图像输入。 - output_type (
str
, optional, defaults to"pil"
) — 输出类型。生成图像的输出格式。 在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, optional, defaults toTrue
) — 返回字典。是否返回GaudiStableDiffusionPipelineOutput
而不是纯元组。 - cross_attention_kwargs (
dict
, optional) — 交叉注意力关键字参数。一个关键字参数字典,如果指定,则作为self.processor
中定义的AttentionProcessor
的参数传递。 - guidance_rescale (
float
, optional, defaults to 0.0) — 引导重缩放。来自 Common Diffusion Noise Schedules and Sample Steps are Flawed 的引导重缩放因子。 引导重缩放因子应修复使用零终端 SNR 时的过度曝光问题。 - clip_skip (
int
, optional) — CLIP 跳过。从 CLIP 中跳过的层数,用于计算提示嵌入。 值 1 表示预最终层的输出将用于计算提示嵌入。 - callback_on_step_end (
Callable
, optional) — 步骤结束时回调。在推理期间每个去噪步骤结束时调用的函数。 该函数使用以下参数调用: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。 `callback_kwargs` 将包含 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List
, optional) — 步骤结束时回调的张量输入。`callback_on_step_end` 函数的张量输入列表。 列表中指定的张量将作为 `callback_kwargs` 参数传递。 您将只能包含管道类的 `._callback_tensor_inputs` 属性中列出的变量。 - profiling_warmup_steps (
int
, optional) — 性能分析预热步骤。性能分析中要忽略的步骤数。 - profiling_steps (
int
, optional) — 性能分析步骤。启用性能分析时要捕获的步骤数。
Returns
GaudiStableDiffusionPipelineOutput
or tuple
如果 return_dict
为 True
,则返回 ~diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
,否则返回一个 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。
调用管道进行生成的调用函数。
GaudiDiffusionPipeline
class optimum.habana.diffusers.GaudiDiffusionPipeline
< source >( use_habana: bool = False use_hpu_graphs: bool = False gaudi_config: Union = None bf16_full_eval: bool = False )
参数
- use_habana (bool, 默认为
False
) — 是否使用 Gaudi (True
) 或 CPU (False
)。 - use_hpu_graphs (bool, 默认为
False
) — 是否使用 HPU graphs。 - gaudi_config (Union[str, GaudiConfig], 默认为
None
) — 要使用的 Gaudi 配置。可以是用于从 Hub 下载的字符串。或者可以传递先前初始化的配置。 - bf16_full_eval (bool, 默认为
False
) — 是否使用完整的 bfloat16 评估而不是 32 位。与 fp32/混合精度相比,这将更快并节省内存,但可能会损害生成的图像质量。
继承自 DiffusionPipeline
类
- 如果
use_habana=True
,则管道在 Gaudi 上初始化。 - 管道的 Gaudi 配置已保存并推送到 hub。
更多信息请参考 这里。
save_pretrained
< source >( save_directory: Union safe_serialization: bool = True variant: Optional = None push_to_hub: bool = False **kwargs )
参数
- save_directory (
str
或os.PathLike
) — 要保存到的目录。如果不存在,将创建该目录。 - safe_serialization (
bool
, 可选, 默认为True
) — 是否使用safetensors
或传统的 PyTorch 方式(使用pickle
)保存模型。 - variant (
str
, 可选) — 如果指定,权重将以 pytorch_model..bin 格式保存。 - push_to_hub (
bool
, 可选, 默认为False
) — 是否在保存模型后将其推送到 Hugging Face 模型 hub。 您可以使用repo_id
指定要推送到的存储库(默认为命名空间中save_directory
的名称)。 - kwargs (
Dict[str, Any]
, 可选) — 传递给~utils.PushToHubMixin.push_to_hub
方法的附加关键字参数。
保存管道和 Gaudi 配置。 更多信息请参考 这里。
GaudiDDIMScheduler
class optimum.habana.diffusers.GaudiDDIMScheduler
< source >( num_train_timesteps: int = 1000 beta_start: float = 0.0001 beta_end: float = 0.02 beta_schedule: str = 'linear' trained_betas: Union = None clip_sample: bool = True set_alpha_to_one: bool = True steps_offset: int = 0 prediction_type: str = 'epsilon' thresholding: bool = False dynamic_thresholding_ratio: float = 0.995 clip_sample_range: float = 1.0 sample_max_value: float = 1.0 timestep_spacing: str = 'leading' rescale_betas_zero_snr: bool = False )
参数
- num_train_timesteps (
int
, 默认为 1000) — 训练模型的扩散步骤数。 - beta_start (
float
, 默认为 0.0001) — 推理的起始beta
值。 - beta_end (
float
, 默认为 0.02) — 最终beta
值。 - beta_schedule (
str
, 默认为"linear"
) — beta 计划,从 beta 范围到用于步进模型的 beta 序列的映射。 从linear
、scaled_linear
或squaredcos_cap_v2
中选择。 - trained_betas (
np.ndarray
, 可选) — 直接将 beta 数组传递给构造函数以绕过beta_start
和beta_end
。 - clip_sample (
bool
, 默认为True
) — 裁剪预测的样本以提高数值稳定性。 - clip_sample_range (
float
, 默认为 1.0) — 样本裁剪的最大幅度。仅当clip_sample=True
时有效。 - set_alpha_to_one (
bool
, 默认为True
) — 每个扩散步骤都使用该步骤和前一步骤的 alphas 乘积值。对于最后一步,没有先前的 alpha。当此选项为True
时,先前的 alpha 乘积固定为1
,否则它使用步骤 0 的 alpha 值。 - steps_offset (
int
, 默认为 0) — 添加到推理步骤的偏移量。 您可以使用offset=1
和set_alpha_to_one=False
的组合,使最后一步像 Stable Diffusion 中一样使用步骤 0 的先前 alpha 乘积。 - prediction_type (
str
, 默认为epsilon
, 可选) — 调度器函数的预测类型;可以是epsilon
(预测扩散过程的噪声)、sample
(直接预测噪声样本)或v_prediction
(请参阅 Imagen Video 论文的第 2.4 节)。 - thresholding (
bool
, defaults toFalse
) — 是否使用“动态阈值”方法。 这不适用于潜在空间扩散模型,例如 Stable Diffusion。 - dynamic_thresholding_ratio (
float
, defaults to 0.995) — 动态阈值方法的比率。 仅当thresholding=True
时有效。 - sample_max_value (
float
, defaults to 1.0) — 动态阈值的阈值。 仅当thresholding=True
时有效。 - timestep_spacing (
str
, defaults to"leading"
) — 时间步长应缩放的方式。 有关更多信息,请参阅常用扩散噪声时间表和采样步骤存在缺陷的表 2。 - rescale_betas_zero_snr (
bool
, defaults toFalse
) — 是否重新缩放 betas 以使其具有零终端 SNR。 这使模型能够生成非常明亮和黑暗的样本,而不是将其限制为具有中等亮度的样本。 与--offset_noise
松散相关。
扩展 Diffusers’ DDIMScheduler 以在 Gaudi 上最佳运行
- 所有时间相关的参数都在开始时生成
- 在每个时间步,张量都会被滚动以更新时间相关参数的值
get_params
< source >( timestep: Optional = None )
初始化时间相关的参数,并在每个时间步检索时间相关的参数。 张量在调度器步骤结束时在单独的函数中滚动,以防参数在一个时间步中被多次检索,例如,当缩放模型输入和在调度器步骤中时。
滚动张量以更新每个时间步中时间相关参数的值。
step
< source >( model_output: FloatTensor timestep: int sample: FloatTensor eta: float = 0.0 use_clipped_model_output: bool = False generator = None variance_noise: Optional = None return_dict: bool = True ) → diffusers.schedulers.scheduling_utils.DDIMSchedulerOutput
或 tuple
参数
- model_output (
torch.FloatTensor
) — 来自学习扩散模型的直接输出。 - sample (
torch.FloatTensor
) — 由扩散过程创建的样本的当前实例。 - eta (
float
) — 扩散步骤中添加噪声的噪声权重。 - use_clipped_model_output (
bool
, defaults toFalse
) — 如果为True
,则从裁剪的预测原始样本计算“校正后的”model_output
。 这是必要的,因为当self.config.clip_sample
为True
时,预测的原始样本会被裁剪到 [-1, 1]。 如果未发生裁剪,“校正后的”model_output
将与作为输入提供的输出一致,并且use_clipped_model_output
无效。 - generator (
torch.Generator
, optional) — 随机数生成器。 - variance_noise (
torch.FloatTensor
) — 通过直接提供方差本身的噪声来替代使用generator
生成噪声。 对于诸如CycleDiffusion
之类的方法很有用。 - return_dict (
bool
, optional, defaults toTrue
) — 是否返回DDIMSchedulerOutput
或tuple
。
Returns
diffusers.schedulers.scheduling_utils.DDIMSchedulerOutput
或 tuple
如果 return_dict 为 True
,则返回 DDIMSchedulerOutput
,否则返回一个元组,其中第一个元素是样本张量。
通过反转 SDE 来预测上一个时间步的样本。 此函数从学习的模型输出(通常是预测的噪声)传播扩散过程。
GaudiStableDiffusionXLPipeline
GaudiStableDiffusionXLPipeline
类允许使用 SDXL 模型在 HPU 上执行文本到图像的生成。 它继承自 GaudiDiffusionPipeline
类,该类是任何类型的扩散管道的父类。
为了充分利用它,它应该与针对 HPU 优化的调度器(如 GaudiDDIMScheduler
)相关联。 推荐的调度器是用于 SDXL 基本模型的 GaudiEulerDiscreteScheduler
和用于 SDXL turbo 的 GaudiEulerAncestralDiscreteScheduler
。
GaudiStableDiffusionXLPipeline
class optimum.habana.diffusers.GaudiStableDiffusionXLPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None force_zeros_for_empty_prompt: bool = True use_habana: bool = False use_hpu_graphs: bool = False gaudi_config: Union = None bf16_full_eval: bool = False )
参数
- vae (
AutoencoderKL
) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示和从潜在表示解码图像。 - text_encoder (
CLIPTextModel
) — 冻结的文本编码器。 Stable Diffusion XL 使用 CLIP 的文本部分,特别是 clip-vit-large-patch14 变体。 - text_encoder_2 (
CLIPTextModelWithProjection
) — 第二个冻结的文本编码器。 Stable Diffusion XL 使用 CLIP 的文本和池化部分,特别是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - tokenizer_2 (
CLIPTokenizer
) — 第二个 CLIPTokenizer 类的分词器。 - unet (
UNet2DConditionModel
) — 条件 U-Net 架构,用于对编码后的图像潜在空间进行去噪。 - scheduler (
SchedulerMixin
) — 调度器,与unet
结合使用,以对编码后的图像潜在空间进行去噪。可以是DDIMScheduler
、LMSDiscreteScheduler
或PNDMScheduler
之一。 - force_zeros_for_empty_prompt (
bool
, 可选, 默认为"True"
) — 负面提示词嵌入是否应始终强制设置为 0。另请参阅stabilityai/stable-diffusion-xl-base-1-0
的配置。 - use_habana (bool, 默认为
False
) — 是否使用 Gaudi (True
) 或 CPU (False
)。 - use_hpu_graphs (bool, 默认为
False
) — 是否使用 HPU 图。 - gaudi_config (Union[str, GaudiConfig], 默认为
None
) — 要使用的 Gaudi 配置。可以是用于从 Hub 下载的字符串。或者可以传递先前初始化的配置。 - bf16_full_eval (bool, 默认为
False
) — 是否使用完整的 bfloat16 评估而不是 32 位。与 fp32/混合精度相比,这将更快并节省内存,但可能会损害生成的图像。
使用 Gaudi 设备上的 Stable Diffusion XL 进行文本到图像生成的 Pipeline。改编自: https://github.com/huggingface/diffusers/blob/v0.23.1/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py#L96
扩展了 StableDiffusionXLPipeline
类
- 生成操作以批次方式执行
- 添加了两个
mark_step()
以支持惰性模式 - 添加了对 HPU graphs 的支持
__call__
< source >( prompt: Union = None prompt_2: Union = None height: Optional = None width: Optional = None num_inference_steps: int = 50 timesteps: List = None denoising_end: Optional = None guidance_scale: float = 5.0 negative_prompt: Union = None negative_prompt_2: Union = None num_images_per_prompt: Optional = 1 batch_size: int = 1 eta: float = 0.0 generator: Union = None latents: Optional = None prompt_embeds: Optional = None negative_prompt_embeds: Optional = None pooled_prompt_embeds: Optional = None negative_pooled_prompt_embeds: Optional = None ip_adapter_image: Union = None output_type: Optional = 'pil' return_dict: bool = True callback: Optional = None callback_steps: int = 1 cross_attention_kwargs: Optional = None guidance_rescale: float = 0.0 original_size: Optional = None crops_coords_top_left: Tuple = (0, 0) target_size: Optional = None negative_original_size: Optional = None negative_crops_coords_top_left: Tuple = (0, 0) negative_target_size: Optional = None clip_skip: Optional = None callback_on_step_end: Optional = None callback_on_step_end_tensor_inputs: List = ['latents', 'prompt_embeds', 'negative_prompt_embeds', 'add_text_embeds', 'add_time_ids', 'negative_pooled_prompt_embeds', 'negative_add_time_ids'] profiling_warmup_steps: Optional = 0 profiling_steps: Optional = 0 **kwargs ) → #~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示词。如果未定义,则必须传递prompt_embeds
。代替。 - prompt_2 (
str
或List[str]
, 可选) — 要发送到tokenizer_2
和text_encoder_2
的提示词。如果未定义,则prompt
将在两个文本编码器中使用 - height (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度像素。默认设置为 1024 以获得最佳效果。对于 stabilityai/stable-diffusion-xl-base-1.0 和未针对低分辨率进行微调的检查点,低于 512 像素的任何值都无法很好地工作。 - width (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度像素。默认设置为 1024 以获得最佳效果。对于 stabilityai/stable-diffusion-xl-base-1.0 和未针对低分辨率进行微调的检查点,低于 512 像素的任何值都无法很好地工作。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步骤的数量。更多去噪步骤通常会以较慢的推理速度为代价,从而获得更高质量的图像。 - timesteps (
List[int]
, 可选) — 用于支持在其set_timesteps
方法中使用timesteps
参数的调度器的去噪过程的自定义时间步长。如果未定义,将使用传递num_inference_steps
时的默认行为。必须按降序排列。 - denoising_end (
float
, 可选) — 如果指定,则确定在有意提前终止之前要完成的总去噪过程的分数(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留大量的噪声,这由调度器选择的离散时间步长决定。当此 pipeline 构成“去噪器混合”多 pipeline 设置的一部分时,应理想地使用 denoising_end 参数,如 优化图像输出 中所述 - guidance_scale (
float
, 可选, 默认为 5.0) — Classifier-Free Diffusion Guidance 中定义的引导缩放。guidance_scale
定义为 Imagen Paper 的公式 2 中的w
。通过设置guidance_scale > 1
启用引导缩放。较高的引导缩放鼓励生成与文本prompt
紧密相关的图像,通常以降低图像质量为代价。 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递negative_prompt_embeds
代替。当不使用引导时忽略(即,如果guidance_scale
小于1
则忽略)。 - negative_prompt_2 (
str
或List[str]
, 可选) — 不用于引导图像生成的提示词,要发送到tokenizer_2
和text_encoder_2
。如果未定义,则negative_prompt
将在两个文本编码器中使用 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示词要生成的图像数量。 - batch_size (
int
, optional, defaults to 1) — 一个批次中的图像数量。 - eta (
float
, optional, defaults to 0.0) — 对应于 DDIM 论文中的参数 eta (η): https://arxiv.org/abs/2010.02502。仅适用于schedulers.DDIMScheduler
,对其他调度器将被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, optional) — 一个或一组 torch 生成器,用于使生成过程确定化。 - latents (
torch.FloatTensor
, optional) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于通过不同的提示调整相同的生成结果。如果未提供,将使用提供的随机generator
采样生成潜变量张量。 - prompt_embeds (
torch.FloatTensor
, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.FloatTensor
, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从negative_prompt
输入参数生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.FloatTensor
, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.FloatTensor
, optional) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从negative_prompt
输入参数生成池化的 negative_prompt_embeds。 ip_adapter_image — (PipelineImageInput
, optional): 与 IP 适配器一起使用的可选图像输入。 - output_type (
str
, optional, defaults to"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, optional, defaults toTrue
) — #是否返回~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
而不是纯元组。是否返回GaudiStableDiffusionXLPipelineOutput
而不是纯元组。 - cross_attention_kwargs (
dict
, optional) — 一个 kwargs 字典,如果指定,则会传递给AttentionProcessor
,定义在 diffusers.models.attention_processor 中的self.processor
下。 - guidance_rescale (
float
, optional, defaults to 0.0) — Common Diffusion Noise Schedules and Sample Steps are Flawed 提出的引导重缩放因子。guidance_scale
在 Common Diffusion Noise Schedules and Sample Steps are Flawed 的公式 16 中定义为φ
。当使用零终端信噪比时,引导重缩放因子应修复过度曝光。 - original_size (
Tuple[int]
, optional, defaults to (1024, 1024)) — 如果original_size
与target_size
不同,图像将显示为降采样或升采样。如果未指定,original_size
默认为(height, width)
。SDXL 微条件控制的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 节所述。 - crops_coords_top_left (
Tuple[int]
, optional, defaults to (0, 0)) —crops_coords_top_left
可用于生成看起来像是从crops_coords_top_left
位置向下“裁剪”的图像。通常通过将crops_coords_top_left
设置为 (0, 0) 来获得良好居中的图像。SDXL 微条件控制的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 节所述。 - target_size (
Tuple[int]
, optional, defaults to (1024, 1024)) — 在大多数情况下,target_size
应设置为生成图像的所需高度和宽度。如果未指定,则默认为(height, width)
。SDXL 微条件控制的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 节所述。 - negative_original_size (
Tuple[int]
, optional, defaults to (1024, 1024)) — 为了基于特定的图像分辨率对生成过程进行负面条件控制。SDXL 微条件控制的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 节所述。有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - negative_crops_coords_top_left (
Tuple[int]
, optional, defaults to (0, 0)) — 为了基于特定的裁剪坐标对生成过程进行负面条件控制。SDXL 微条件控制的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 节所述。有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
Tuple[int]
, optional, defaults to (1024, 1024)) — 为了基于目标图像分辨率对生成过程进行负面条件控制。在大多数情况下,它应与target_size
相同。SDXL 微条件控制的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 节所述。有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - callback_on_step_end (
Callable
, optional) — 一个函数,在推理期间的每个去噪步骤结束时调用。该函数使用以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含由callback_on_step_end_tensor_inputs
指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List
, optional) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您将只能包含在管道类的._callback_tensor_inputs
属性中列出的变量。 - profiling_warmup_steps (
int
, optional) — 进行性能分析时要忽略的步数。 - profiling_steps (
int
, optional) — 启用性能分析时要捕获的步数。
Returns
#~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
或 tuple
#如果 return_dict
为 True,则为 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput
,否则为 GaudiStableDiffusionXLPipelineOutput
或 tuple
:如果 return_dict
为 True,则为 GaudiStableDiffusionXLPipelineOutput
,否则为 tuple
。当返回元组时,第一个元素是包含生成图像的列表。
调用管道进行生成时调用的函数。
示例
GaudiEulerDiscreteScheduler
class optimum.habana.diffusers.GaudiEulerDiscreteScheduler
< source >( num_train_timesteps: int = 1000 beta_start: float = 0.0001 beta_end: float = 0.02 beta_schedule: str = 'linear' trained_betas: Union = None prediction_type: str = 'epsilon' interpolation_type: str = 'linear' use_karras_sigmas: Optional = False sigma_min: Optional = None sigma_max: Optional = None timestep_spacing: str = 'linspace' timestep_type: str = 'discrete' steps_offset: int = 0 rescale_betas_zero_snr: bool = False )
参数
- num_train_timesteps (
int
, 默认为 1000) — 用于训练模型的扩散步数。 - beta_start (
float
, 默认为 0.0001) — 推理的起始beta
值。 - beta_end (
float
, 默认为 0.02) — 最终的beta
值。 - beta_schedule (
str
, 默认为"linear"
) — beta 时间表,从 beta 范围到用于步进模型的 beta 序列的映射。从linear
或scaled_linear
中选择。 - trained_betas (
np.ndarray
, 可选) — 直接将 beta 数组传递给构造函数以绕过beta_start
和beta_end
。 - prediction_type (
str
, 默认为epsilon
, 可选) — 调度器函数的预测类型;可以是epsilon
(预测扩散过程的噪声)、sample
(直接预测噪声样本)或v_prediction
(参见 Imagen Video 论文的 2.4 节)。 - interpolation_type(
str
, 默认为"linear"
, 可选) — 用于计算调度器去噪步骤的中间 sigma 的插值类型。应为"linear"
或"log_linear"
之一。 - use_karras_sigmas (
bool
, 可选, 默认为False
) — 是否在采样过程中对噪声时间表中的步长使用 Karras sigma 值。如果为True
,则 sigma 值根据噪声水平序列 {σi} 确定。 - timestep_spacing (
str
, 默认为"linspace"
) — 应该如何缩放时间步长。有关更多信息,请参阅 通用扩散噪声时间表和样本步长存在缺陷 的表 2。 - steps_offset (
int
, 默认为 0) — 添加到推理步骤的偏移量。您可以结合使用offset=1
和set_alpha_to_one=False
,使最后一步像 Stable Diffusion 中一样使用步骤 0 作为先前的 alpha 乘积。 - rescale_betas_zero_snr (
bool
, 默认为False
) — 是否重新缩放 beta 值以使其具有零终端 SNR。这使模型能够生成非常明亮和黑暗的样本,而不是将其限制为具有中等亮度的样本。与--offset_noise
松散相关。
扩展了 Diffusers 的 EulerDiscreteScheduler,使其在 Gaudi 上以最佳方式运行
- 所有时间相关的参数都在开始时生成
- 在每个时间步,张量都会被滚动以更新时间相关参数的值
滚动张量以更新每个时间步中时间相关参数的值。
确保与需要根据当前时间步缩放去噪模型输入的调度器具有互换性。 将去噪模型输入按 (sigma**2 + 1) ** 0.5
缩放以匹配 Euler 算法。
step
< source >( model_output: FloatTensor timestep: Union sample: FloatTensor s_churn: float = 0.0 s_tmin: float = 0.0 s_tmax: float = inf s_noise: float = 1.0 generator: Optional = None return_dict: bool = True ) → ~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput
或 tuple
参数
- model_output (
torch.FloatTensor
) — 来自学习的扩散模型的直接输出。 - timestep (
float
) — 扩散链中的当前离散时间步。 - sample (
torch.FloatTensor
) — 由扩散过程创建的样本的当前实例。 - s_churn (
float
) — - s_tmin (
float
) — - s_tmax (
float
) — - s_noise (
float
, 默认为 1.0) — 添加到样本的噪声的缩放因子。 - generator (
torch.Generator
, 可选) — 随机数生成器。 - return_dict (
bool
) — 是否返回~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput
或元组。
Returns
~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput
or tuple
如果 return_dict 为 True
,则返回 ~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput
,否则返回一个元组,其中第一个元素是 sample tensor。
通过反转 SDE 来预测上一个时间步的样本。 此函数从学习的模型输出(通常是预测的噪声)传播扩散过程。
GaudiEulerAncestralDiscreteScheduler
class optimum.habana.diffusers.GaudiEulerAncestralDiscreteScheduler
< source >( num_train_timesteps: int = 1000 beta_start: float = 0.0001 beta_end: float = 0.02 beta_schedule: str = 'linear' trained_betas: Union = None prediction_type: str = 'epsilon' timestep_spacing: str = 'linspace' steps_offset: int = 0 rescale_betas_zero_snr: bool = False )
参数
- num_train_timesteps (
int
, 默认为 1000) — 用于训练模型的扩散步骤数量。 - beta_start (
float
, 默认为 0.0001) — 推理的起始beta
值。 - beta_end (
float
, 默认为 0.02) — 最终的beta
值。 - beta_schedule (
str
, 默认为"linear"
) — beta 计划,从 beta 范围到用于模型步进的 beta 序列的映射。从linear
或scaled_linear
中选择。 - trained_betas (
np.ndarray
, *可选*) — 直接将 beta 数组传递给构造函数以绕过beta_start
和beta_end
。 - prediction_type (
str
, 默认为epsilon
, *可选*) — 调度器函数的预测类型;可以是epsilon
(预测扩散过程的噪声),sample
(直接预测带噪样本) 或v_prediction
(参见 Imagen Video 论文的 2.4 节)。 - timestep_spacing (
str
, 默认为"linspace"
) — 步长应缩放的方式。有关更多信息,请参阅 Common Diffusion Noise Schedules and Sample Steps are Flawed 的表 2。 - steps_offset (
int
, 默认为 0) — 添加到推理步骤的偏移量。您可以结合使用offset=1
和set_alpha_to_one=False
,使最后一步像在 Stable Diffusion 中一样,对先前的 alpha 乘积使用步骤 0。 - rescale_betas_zero_snr (
bool
, 默认为False
) — 是否重新缩放 beta 以使其具有零终端 SNR。这使模型能够生成非常明亮和黑暗的样本,而不是将其限制为中等亮度的样本。与--offset_noise
松散相关。
扩展了 Diffusers 的 EulerAncestralDiscreteScheduler,使其在 Gaudi 上最佳运行
- 所有时间相关的参数都在开始时生成
- 在每个时间步,张量都会被滚动以更新时间相关参数的值
get_params
< source >( timestep: Union )
初始化时间相关的参数,并在每个时间步检索时间相关的参数。 张量在调度器步骤结束时在单独的函数中滚动,以防参数在一个时间步中被多次检索,例如,当缩放模型输入和在调度器步骤中时。
滚动张量以更新每个时间步中时间相关参数的值。
scale_model_input
< source >( sample: FloatTensor timestep: Union ) → torch.FloatTensor
确保与需要根据当前时间步缩放去噪模型输入的调度器具有互换性。 将去噪模型输入按 (sigma**2 + 1) ** 0.5
缩放以匹配 Euler 算法。
step
< source >( model_output: FloatTensor timestep: Union sample: FloatTensor generator: Optional = None return_dict: bool = True ) → ~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput
or tuple
参数
- model_output (
torch.FloatTensor
) — 来自学习的扩散模型的直接输出。 - timestep (
float
) — 扩散链中当前的离散步长。 - sample (
torch.FloatTensor
) — 由扩散过程创建的样本的当前实例。 - generator (
torch.Generator
, *可选*) — 随机数生成器。 - return_dict (
bool
) — 是否返回~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput
或元组。
Returns
~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput
or tuple
如果 return_dict 为 True
,则返回 ~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput
,否则返回一个元组,其中第一个元素是 sample tensor。
通过反转 SDE 来预测上一个时间步的样本。 此函数从学习的模型输出(通常是预测的噪声)传播扩散过程。
GaudiStableDiffusionUpscalePipeline
GaudiStableDiffusionUpscalePipeline
用于将输入图像的分辨率在 HPU 上提高 4 倍。 它继承自 GaudiDiffusionPipeline
类,该类是任何类型的扩散器管道的父类。
class optimum.habana.diffusers.GaudiStableDiffusionUpscalePipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel low_res_scheduler: DDPMScheduler scheduler: KarrasDiffusionSchedulers safety_checker: Optional = None feature_extractor: Optional = None watermarker: Optional = None max_noise_level: int = 350 use_habana: bool = False use_hpu_graphs: bool = False gaudi_config: Union = None bf16_full_eval: bool = False )
参数
- vae (
AutoencoderKL
) — 用于将图像编码和解码为潜在表示的变分自动编码器 (VAE) 模型。 - text_encoder (
CLIPTextModel
) — 冻结的文本编码器。 Stable Diffusion 使用 CLIP 的文本部分,特别是 clip-vit-large-patch14 变体。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - unet (
UNet2DConditionModel
) — 条件 U-Net 架构,用于对编码后的图像潜在表示进行去噪。 - low_res_scheduler (
SchedulerMixin
) — 用于向低分辨率条件图像添加初始噪声的调度器。它必须是DDPMScheduler
的实例。 - scheduler (
SchedulerMixin
) — 与unet
结合使用的调度器,用于对编码后的图像潜在表示进行去噪。可以是DDIMScheduler
、LMSDiscreteScheduler
或PNDMScheduler
之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分类模块,用于评估生成的图像是否可能被认为是冒犯性或有害的。请参阅 模型卡 了解详细信息。 - feature_extractor (
CLIPImageProcessor
) — 从生成的图像中提取特征的模型,用作safety_checker
的输入。 - use_habana (bool, 默认为
False
) — 是否使用 Gaudi (True
) 或 CPU (False
)。 - use_hpu_graphs (bool, 默认为
False
) — 是否使用 HPU 图。 - gaudi_config (Union[str, GaudiConfig], 默认为
None
) — 要使用的 Gaudi 配置。可以是用于从 Hub 下载配置的字符串。或者可以传递先前初始化的配置。 - bf16_full_eval (bool, 默认为
False
) — 是否使用完整的 bfloat16 评估而不是 32 位。与 fp32/混合精度相比,这将更快并节省内存,但可能会损害生成的图像。
用于文本引导的图像超分辨率的 Stable Diffusion 2 管线。
- 生成操作以批次方式执行
- 添加了两个
mark_step()
以支持惰性模式 - 添加了对 HPU graphs 的支持
__call__
< source >( prompt: Union = None image: Union = None num_inference_steps: int = 75 guidance_scale: float = 9.0 noise_level: int = 20 negative_prompt: Union = None num_images_per_prompt: Optional = 1 batch_size: int = 1 eta: float = 0.0 generator: Union = None latents: Optional = None prompt_embeds: Optional = None negative_prompt_embeds: Optional = None output_type: Optional = 'pil' return_dict: bool = True callback: Optional = None callback_steps: int = 1 cross_attention_kwargs: Optional = None clip_skip: int = None **kwargs ) → GaudiStableDiffusionPipelineOutput
或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则必须改为传递prompt_embeds
。 - image (
torch.FloatTensor
,PIL.Image.Image
,np.ndarray
,List[torch.FloatTensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) —Image
或张量,表示要放大的图像批次。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步骤的数量。更多去噪步骤通常会带来更高质量的图像,但会牺牲更慢的推理速度。 - guidance_scale (
float
, 可选, 默认为 7.5) — 无分类器扩散引导 中定义的引导比例。guidance_scale
定义为 Imagen Paper 的等式 2 中的w
。通过设置guidance_scale > 1
启用引导比例。较高的引导比例鼓励生成与文本prompt
紧密相关的图像,但通常以降低图像质量为代价。 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示或提示列表。如果未定义,则必须改为传递negative_prompt_embeds
。当不使用引导时忽略(即,如果guidance_scale
小于1
则忽略)。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示要生成的图像数量。 - batch_size (
int
, 可选, 默认为 1) — 批次中的图像数量。 - eta (
float
, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η): https://arxiv.org/abs/2010.02502。仅适用于schedulers.DDIMScheduler
,对于其他调度器将被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成具有确定性的一个或多个 torch 生成器。 - latents (
torch.FloatTensor
, 可选) — 预生成的噪声潜在表示,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,将随机生成潜在张量。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.FloatTensor
, optional) — 预生成的负面文本嵌入。 可以用于轻松调整文本输入,例如 提示词权重。 如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - output_type (
str
, optional, defaults to"pil"
) — 生成图像的输出格式。 在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, optional, defaults toTrue
) — 是否返回GaudiStableDiffusionPipelineOutput
而不是普通的元组。 - callback (
Callable
, optional) — 一个函数,它将在推理期间每callback_steps
步调用一次。 该函数将被以下参数调用:callback(step: int, timestep: int, latents: torch.FloatTensor)
。 - callback_steps (
int
, optional, defaults to 1) —callback
函数将被调用的频率。 如果未指定,则将在每个步骤调用回调。 - cross_attention_kwargs (
dict
, optional) — 一个 kwargs 字典,如果指定,则会传递给AttentionProcessor
,定义在 diffusers.cross_attention 下。 - clip_skip (
int
, optional) — 在计算提示词嵌入时,从 CLIP 跳过的层数。 值为 1 表示预最终层的输出将用于计算提示词嵌入。
Returns
GaudiStableDiffusionPipelineOutput
or tuple
GaudiStableDiffusionPipelineOutput
如果 return_dict
为 True,否则为 tuple
。 当返回元组时,第一个元素是包含生成图像的列表,第二个元素是 bool
列表,表示根据 safety_checker
,相应的生成图像是否可能代表“不适合工作场所观看” (nsfw) 内容。
调用管道进行生成时调用的函数。
示例
>>> import requests #TODO to test?
>>> from PIL import Image
>>> from io import BytesIO
>>> from optimum.habana.diffusers import GaudiStableDiffusionUpscalePipeline
>>> import torch
>>> # load model and scheduler
>>> model_id = "stabilityai/stable-diffusion-x4-upscaler"
>>> pipeline = GaudiStableDiffusionUpscalePipeline.from_pretrained(
... model_id, revision="fp16", torch_dtype=torch.bfloat16
... )
>>> pipeline = pipeline.to("cuda")
>>> # let's download an image
>>> url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
>>> response = requests.get(url)
>>> low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> low_res_img = low_res_img.resize((128, 128))
>>> prompt = "a white cat"
>>> upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
>>> upscaled_image.save("upsampled_cat.png")
GaudiDDPMPipeline
GaudiDDPMPipeline
用于在 HPU 上启用无条件图像生成。 它具有与常规 DiffusionPipeline
类似的 API。 它与其他现有的 Gaudi 管道共享一个共同的父类 GaudiDiffusionPipeline
。 它现在支持 DDPM 和 DDIM 调度器。 建议使用优化的调度器 GaudiDDIMScheduler
,以获得最佳性能和图像输出。