# Hướng dẫn Perturbed-Attention

  

[Perturbed-Attention Guidance (PAG)](https://ku-cvlab.github.io/Perturbed-Attention-Guidance/) là một phương pháp hướng dẫn lấy mẫu diffusion mới, cải thiện chất lượng mẫu trong cả các thiết lập không điều kiện và có điều kiện, mà không cần huấn luyện thêm hay tích hợp các module bên ngoài.

PAG được giới thiệu trong [Self-Rectifying Diffusion Sampling with Perturbed-Attention Guidance](https://huggingface.co/papers/2403.17377) bởi Donghoon Ahn, Hyoungwon Cho, Jaewon Min, Wooseok Jang, Jungwoo Kim, SeonHwa Kim, Hyun Hee Park, Kyong Hwan Jin và Seungryong Kim.

Tóm tắt từ bài báo là:

*Các nghiên cứu gần đây đã chứng minh rằng các mô hình khuếch tán có khả năng tạo ra các mẫu chất lượng cao, nhưng chất lượng của chúng phụ thuộc rất nhiều vào các kỹ thuật dẫn hướng lấy mẫu, chẳng hạn như dẫn hướng phân loại (CG) và dẫn hướng không phân loại (CFG). Những kỹ thuật này thường không áp dụng được trong tạo mẫu không điều kiện hoặc trong các tác vụ hạ nguồn khác nhau như khôi phục ảnh. Trong bài báo này, chúng tôi đề xuất một kỹ thuật dẫn hướng lấy mẫu mới, gọi là Dẫn hướng Chú ý Bị Nhiễu (PAG), giúp cải thiện chất lượng mẫu khuếch tán trong cả cài đặt không điều kiện và có điều kiện, đạt được điều này mà không cần huấn luyện bổ sung hay tích hợp các module bên ngoài. PAG được thiết kế để tăng cường dần cấu trúc của các mẫu trong suốt quá trình khử nhiễu. Nó bao gồm việc tạo ra các mẫu trung gian có cấu trúc bị suy giảm bằng cách thay thế các bản đồ tự chú ý được chọn trong U-Net khuếch tán bằng ma trận đồng nhất, dựa trên khả năng nắm bắt thông tin cấu trúc của các cơ chế tự chú ý, và dẫn hướng quá trình khử nhiễu tránh xa các mẫu bị suy giảm này. Trong cả ADM và Stable Diffusion, PAG bất ngờ cải thiện chất lượng mẫu trong các kịch bản có điều kiện và thậm chí không điều kiện. Hơn nữa, PAG cải thiện đáng kể hiệu năng cơ sở trong các tác vụ hạ nguồn khác nhau mà các kỹ thuật dẫn hướng hiện có như CG hoặc CFG không thể được khai thác đầy đủ, bao gồm ControlNet với các prompt rỗng và khôi phục ảnh như inpainting và khử mờ.*

PAG có thể được sử dụng bằng cách chỉ định `pag_applied_layers` dưới dạng một tham số khi khởi tạo một pipeline PAG. Tham số này có thể là một chuỗi duy nhất hoặc một danh sách các chuỗi. Mỗi chuỗi có thể là một định danh lớp duy nhất hoặc một biểu thức chính quy để xác định một hoặc nhiều lớp.

- Định danh đầy đủ dưới dạng chuỗi thông thường: `down_blocks.2.attentions.0.transformer_blocks.0.attn1.processor`
- Định danh đầy đủ dưới dạng RegEx: `down_blocks.2.(attentions|motion_modules).0.transformer_blocks.0.attn1.processor`
- Định danh một phần dưới dạng RegEx: `down_blocks.2`, hoặc `attn1`
- Danh sách các định danh (có thể là tổ hợp của chuỗi và ReGex): `["blocks.1", "blocks.(14|20)", r"down_blocks\.(2,3)"]`

> [!WARNING]
> Vì RegEx được hỗ trợ như một cách để khớp các định danh lớp, việc sử dụng nó đúng cách là rất quan trọng, nếu không có thể dẫn đến hành vi không mong muốn. Cách sử dụng PAG được khuyến nghị là chỉ định các lớp dưới dạng `blocks.{layer_index}` và `blocks.({layer_index_1|layer_index_2|...})`. Việc sử dụng theo bất kỳ cách nào khác, dù có thể thực hiện được, có thể bỏ qua các kiểm tra xác thực cơ bản của chúng tôi và cho ra kết quả không như mong đợi.

## Các tác vụ chung

Bạn có thể áp dụng PAG cho [StableDiffusionXLPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLPipeline) cho các tác vụ như text-to-image, image-to-image và inpainting. Để bật PAG cho một tác vụ cụ thể, hãy tải pipeline bằng API [AutoPipeline](./auto_pipeline) với cờ `enable_pag=True` và đối số `pag_applied_layers`.

> [!TIP]
> 🤗 Diffusers hiện chỉ hỗ trợ sử dụng PAG với các pipeline SDXL được chọn và [PixArtSigmaPAGPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/pag#diffusers.PixArtSigmaPAGPipeline). Tuy nhiên, bạn hoàn toàn có thể mở một [feature request](https://github.com/huggingface/diffusers/issues/new/choose) nếu muốn thêm hỗ trợ PAG cho một pipeline mới!

```py
from diffusers import AutoPipelineForText2Image
from diffusers.utils import load_image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    enable_pag=True,
    pag_applied_layers=["mid"],
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
```

> [!TIP]
> Tham số `pag_applied_layers` cho phép bạn chỉ định các lớp mà PAG được áp dụng. Ngoài ra, bạn có thể sử dụng phương thức `set_pag_applied_layers` để cập nhật các lớp này sau khi pipeline đã được tạo. Xem phần [pag_applied_layers](#pagappliedlayers) để tìm hiểu thêm về việc áp dụng PAG cho các lớp khác.

Nếu bạn đã có một pipeline được tạo và tải sẵn, bạn có thể kích hoạt PAG trên nó bằng cách sử dụng API `from_pipe` với cờ `enable_pag`. Bên trong, một pipeline PAG sẽ được tạo dựa trên pipeline và tác vụ mà bạn đã chỉ định. Trong ví dụ dưới đây, vì chúng ta đã sử dụng `AutoPipelineForText2Image` và truyền vào một `StableDiffusionXLPipeline`, một `StableDiffusionXLPAGPipeline` sẽ được tạo tương ứng. Lưu ý rằng điều này không yêu cầu bộ nhớ bổ sung, và bạn sẽ có cả `StableDiffusionXLPipeline` và `StableDiffusionXLPAGPipeline` được tải và sẵn sàng sử dụng. Bạn có thể đọc thêm về API `from_pipe` và cách tái sử dụng pipeline trong diffuser [tại đây](https://huggingface.co/docs/diffusers/using-diffusers/loading#reusing-models-in-multiple-pipelines).

```py
pipeline_sdxl = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForText2Image.from_pipe(pipeline_sdxl, enable_pag=True)
```

Để tạo một hình ảnh, bạn cũng cần truyền vào `pag_scale`. Khi `pag_scale` tăng lên, hình ảnh sẽ có cấu trúc nhất quán về mặt ngữ nghĩa hơn và xuất hiện ít lỗi hơn. Tuy nhiên, giá trị guidance scale quá lớn có thể dẫn đến kết cấu mịn hơn và độ bão hòa nhẹ trong hình ảnh, tương tự như CFG. `pag_scale=3.0` được sử dụng trong demo chính thức và hoạt động tốt trong hầu hết các trường hợp sử dụng, nhưng bạn có thể tự do thử nghiệm và chọn giá trị phù hợp theo nhu cầu của mình! PAG sẽ bị tắt khi `pag_scale=0`.

```py
prompt = "an insect robot preparing a delicious meal, anime style"

for pag_scale in [0.0, 3.0]:
    generator = torch.Generator(device="cpu").manual_seed(0)
    images = pipeline(
        prompt=prompt,
        num_inference_steps=25,
        guidance_scale=7.0,
        generator=generator,
        pag_scale=pag_scale,
    ).images
```

  
    
    hình ảnh được tạo mà không có PAG
  
  
    
    hình ảnh được tạo bằng PAG
  

Bạn có thể sử dụng PAG với các pipeline image-to-image.

```py
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import load_image
import torch

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    enable_pag=True,
    pag_applied_layers=["mid"],
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
```

Nếu bạn đã có một pipeline image-to-image và muốn bật PAG trên nó, bạn có thể chạy

```py
pipeline_t2i = AutoPipelineForImage2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForImage2Image.from_pipe(pipeline_t2i, enable_pag=True)
```

Việc chuyển đổi trực tiếp từ pipeline text-to-image sang pipeline image-to-image có hỗ trợ PAG cũng rất dễ dàng

```py
pipeline_pag = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForImage2Image.from_pipe(pipeline_t2i, enable_pag=True)
```

Nếu bạn có một pipeline text-to-image được bật PAG, bạn có thể chuyển trực tiếp sang pipeline image-to-image với PAG vẫn được bật

```py
pipeline_pag = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", enable_pag=True, dtype=torch.float16)
pipeline = AutoPipelineForImage2Image.from_pipe(pipeline_t2i)
```

Bây giờ hãy tạo một hình ảnh!

```py
pag_scales =  4.0
guidance_scales = 7.0

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png"
init_image = load_image(url)
prompt = "a dog catching a frisbee in the jungle"

generator = torch.Generator(device="cpu").manual_seed(0)
image = pipeline(
    prompt,
    image=init_image,
    strength=0.8,
    guidance_scale=guidance_scale,
    pag_scale=pag_scale,
    generator=generator).images[0]
```

```py
from diffusers import AutoPipelineForInpainting
from diffusers.utils import load_image
import torch

pipeline = AutoPipelineForInpainting.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    enable_pag=True,
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
```

Bạn có thể bật PAG trên một pipeline inpainting hiện có như sau

```py
pipeline_inpaint = AutoPipelineForInpainting.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForInpainting.from_pipe(pipeline_inpaint, enable_pag=True)
```

Điều này vẫn hoạt động khi pipeline của bạn có một tác vụ khác:

```py
pipeline_t2i = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForInpaiting.from_pipe(pipeline_t2i, enable_pag=True)
```

Hãy tạo một hình ảnh!

```py
img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
init_image = load_image(img_url).convert("RGB")
mask_image = load_image(mask_url).convert("RGB")

prompt = "A majestic tiger sitting on a bench"

pag_scales =  3.0
guidance_scales = 7.5

generator = torch.Generator(device="cpu").manual_seed(1)
images = pipeline(
    prompt=prompt,
    image=init_image,
    mask_image=mask_image,
    strength=0.8,
    num_inference_steps=50,
    guidance_scale=guidance_scale,
    generator=generator,
    pag_scale=pag_scale,
).images
images[0]
```

## PAG với ControlNet

Để sử dụng PAG với ControlNet, trước tiên hãy tạo một `controlnet`. Sau đó, truyền `controlnet` và các đối số PAG khác vào phương thức `from_pretrained` của AutoPipeline cho tác vụ được chỉ định.

```py
from diffusers import AutoPipelineForText2Image, ControlNetModel
import torch

controlnet = ControlNetModel.from_pretrained(
    "diffusers/controlnet-canny-sdxl-1.0", dtype=torch.float16
)

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    controlnet=controlnet,
    enable_pag=True,
    pag_applied_layers="mid",
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
```

> [!TIP]
> Nếu bạn đã có một pipeline controlnet và muốn bật PAG, bạn có thể sử dụng API `from_pipe`: `AutoPipelineForText2Image.from_pipe(pipeline_controlnet, enable_pag=True)`

Bạn có thể sử dụng pipeline theo cách tương tự như khi sử dụng các pipeline ControlNet thông thường, với tùy chọn bổ sung để chỉ định tham số `pag_scale`. Lưu ý rằng PAG hoạt động tốt cho việc tạo nội dung không điều kiện. Trong ví dụ này, chúng ta sẽ tạo một hình ảnh mà không có prompt.

```py
from diffusers.utils import load_image
canny_image = load_image(
    "https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/pag_control_input.png"
)

for pag_scale in [0.0, 3.0]:
    generator = torch.Generator(device="cpu").manual_seed(1)
    images = pipeline(
        prompt="",
        controlnet_conditioning_scale=controlnet_conditioning_scale,
        image=canny_image,
        num_inference_steps=50,
        guidance_scale=0,
        generator=generator,
        pag_scale=pag_scale,
    ).images
    images[0]
```

  
    
    hình ảnh được tạo mà không có PAG
  
  
    
    hình ảnh được tạo bằng PAG
  

## PAG với IP-Adapter

[IP-Adapter](https://hf.co/papers/2308.06721) là một mô hình phổ biến có thể được tích hợp vào các mô hình khuếch tán để cho phép nhập liệu bằng hình ảnh mà không cần thay đổi mô hình nền tảng. Bạn có thể bật PAG trên một pipeline đã nạp IP-Adapter.

```py
from diffusers import AutoPipelineForText2Image
from diffusers.utils import load_image
from transformers import CLIPVisionModelWithProjection
import torch

image_encoder = CLIPVisionModelWithProjection.from_pretrained(
    "h94/IP-Adapter",
    subfolder="models/image_encoder",
    dtype=torch.float16
)

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    image_encoder=image_encoder,
    enable_pag=True,
    dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

pipeline.load_ip_adapter("h94/IP-Adapter", subfolder="sdxl_models", weight_name="ip-adapter-plus_sdxl_vit-h.bin")

pag_scales = 5.0
ip_adapter_scales = 0.8

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_diner.png")

pipeline.set_ip_adapter_scale(ip_adapter_scale)
generator = torch.Generator(device="cpu").manual_seed(0)
images = pipeline(
    prompt="a polar bear sitting in a chair drinking a milkshake",
    ip_adapter_image=image,
    negative_prompt="deformed, ugly, wrong proportion, low res, bad anatomy, worst quality, low quality",
    num_inference_steps=25,
    guidance_scale=3.0,
    generator=generator,
    pag_scale=pag_scale,
).images
images[0]

```

PAG giảm thiểu các lỗi hình ảnh và cải thiện tổng thể bố cục.

  
    
    hình ảnh được tạo mà không có PAG
  
  
    
    hình ảnh được tạo bằng PAG
  

## Cấu hình các tham số

### pag_applied_layers

Tham số `pag_applied_layers` cho phép bạn chỉ định các lớp mà PAG được áp dụng. Mặc định, nó chỉ được áp dụng cho các khối giữa (mid blocks). Việc thay đổi cài đặt này sẽ ảnh hưởng đáng kể đến kết quả đầu ra. Bạn có thể sử dụng phương thức `set_pag_applied_layers` để điều chỉnh các lớp PAG sau khi pipeline được tạo, giúp bạn tìm ra các lớp tối ưu cho mô hình của mình.

Ví dụ, dưới đây là các hình ảnh được tạo với `pag_layers = ["down.block_2"]` và `pag_layers = ["down.block_2", "up.block_1.attentions_0"]`

```py
prompt = "an insect robot preparing a delicious meal, anime style"
pipeline.set_pag_applied_layers(pag_layers)
generator = torch.Generator(device="cpu").manual_seed(0)
images = pipeline(
    prompt=prompt,
    num_inference_steps=25,
    guidance_scale=guidance_scale,
    generator=generator,
    pag_scale=pag_scale,
).images
images[0]
```

  
    
    down.block_2 + up.block1.attentions_0
  
  
    
    down.block_2
  

## AnimateDiffPAGPipeline[[diffusers.AnimateDiffPAGPipeline]]

#### diffusers.AnimateDiffPAGPipeline[[diffusers.AnimateDiffPAGPipeline]]

```python
diffusers.AnimateDiffPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel | diffusers.models.unets.unet_motion_model.UNetMotionModel, motion_adapter: MotionAdapter, scheduler: KarrasDiffusionSchedulers, feature_extractor: CLIPImageProcessorPil = None, image_encoder: CLIPVisionModelWithProjection = None, pag_applied_layers: str | list[str] = 'mid_block.*attn1')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py#L89)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder (`CLIPTextModel`) : Bộ mã hóa văn bản đóng băng ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer (`CLIPTokenizer`) : Một [CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer) để tách token cho văn bản.

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Một [UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel) được sử dụng để tạo ra một UNetMotionModel nhằm khử nhiễu các latents video đã được mã hóa.

motion_adapter (`MotionAdapter`) : Một `MotionAdapter` được sử dụng kết hợp với `unet` để khử nhiễu các latents video đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

Pipeline để tạo video từ văn bản sử dụng [AnimateDiff](https://huggingface.co/docs/diffusers/en/api/pipelines/animatediff) và [Perturbed Attention Guidance](https://huggingface.co/docs/diffusers/en/using-diffusers/pag).

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.AnimateDiffPAGPipeline.__call__]]

```python
__call__(prompt: str | list[str] | None = None, num_frames: int | None = 16, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_videos_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], decode_chunk_size: int = 16, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py#L575)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `prompt_embeds`.

height (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Chiều cao tính bằng pixel của video được tạo ra.

width (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Độ rộng tính bằng pixel của video được tạo ra.

num_frames (`int`, *optional*, mặc định là 16) : Số lượng khung hình video được tạo ra. Mặc định là 16 khung hình, tương đương với 2 giây video ở tốc độ 8 khung hình mỗi giây.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến video có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

guidance_scale (`float`, *optional*, mặc định là 7.5) : Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi `guidance_scale > 1`.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng video cần tạo cho mỗi prompt.

eta (`float`, *tuỳ chọn*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo [DDIM](https://huggingface.co/papers/2010.02502). Chỉ áp dụng cho [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler) và bị bỏ qua ở các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo video. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp. Latents phải có hình dạng `(batch_size, num_channel, num_frames, height, width)`.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, `negative_prompt_embeds` sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của video được tạo. Chọn giữa `torch.Tensor`, `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput` thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa trong [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

decode_chunk_size (`int`, *tuỳ chọn*, mặc định là 16) : Số khung hình cần giải mã mỗi lần khi gọi phương thức `decode_latents`.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** [AnimateDiffPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/animatediff#diffusers.pipelines.animatediff.AnimateDiffPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [AnimateDiffPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/animatediff#diffusers.pipelines.animatediff.AnimateDiffPipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các khung hình đã tạo.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AnimateDiffPAGPipeline, MotionAdapter, DDIMScheduler
>>> from diffusers.utils import export_to_gif

>>> model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
>>> motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-2"
>>> motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id)
>>> scheduler = DDIMScheduler.from_pretrained(
...     model_id, subfolder="scheduler", beta_schedule="linear", steps_offset=1, clip_sample=False
... )
>>> pipe = AnimateDiffPAGPipeline.from_pretrained(
...     model_id,
...     motion_adapter=motion_adapter,
...     scheduler=scheduler,
...     pag_applied_layers=["mid"],
...     torch_dtype=torch.float16,
... ).to("cuda")

>>> video = pipe(
...     prompt="car, futuristic cityscape with neon lights, street, no human",
...     negative_prompt="low quality, bad quality",
...     num_inference_steps=25,
...     guidance_scale=6.0,
...     pag_scale=3.0,
...     generator=torch.Generator().manual_seed(42),
... ).frames[0]

>>> export_to_gif(video, "animatediff_pag.gif")
```

#### encode_prompt[[diffusers.AnimateDiffPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py#L165)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

## HunyuanDiTPAGPipeline[[diffusers.HunyuanDiTPAGPipeline]]

#### diffusers.HunyuanDiTPAGPipeline[[diffusers.HunyuanDiTPAGPipeline]]

```python
diffusers.HunyuanDiTPAGPipeline(vae: AutoencoderKL, text_encoder: BertModel, tokenizer: BertTokenizer, transformer: HunyuanDiT2DModel, scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.stable_diffusion.safety_checker.StableDiffusionSafetyChecker | None = None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = None, requires_safety_checker: bool = True, text_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = None, tokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = None, pag_applied_layers: str | list[str] = 'blocks.1')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_hunyuandit.py#L152)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn. Chúng tôi sử dụng `sdxl-vae-fp16-fix`.

text_encoder (`~transformers.BertModel`, `~transformers.CLIPTextModel` | None) : Bộ mã hóa văn bản đóng băng ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). HunyuanDiT sử dụng [CLIP song ngữ] đã tinh chỉnh.

tokenizer (`~transformers.BertTokenizer`, `~transformers.CLIPTokenizer` | None) : Một `BertTokenizer` hoặc `CLIPTokenizer` để phân tách văn bản.

transformer ([HunyuanDiT2DModel](/docs/diffusers/v0.43.0/vi/api/models/hunyuan_transformer2d#diffusers.HunyuanDiT2DModel)) : Mô hình HunyuanDiT do Tencent Hunyuan thiết kế.

text_encoder_2 (`T5EncoderModel`) : Bộ nhúng mT5. Cụ thể, nó là 't5-v1_1-xxl'.

tokenizer_2 (`T5Tokenizer`) : Bộ phân từ cho bộ nhúng mT5.

scheduler ([DDPMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddpm#diffusers.DDPMScheduler)) : Một trình lập lịch được sử dụng kết hợp với HunyuanDiT để khử nhiễu các ẩn hình ảnh đã mã hóa.

Pipeline để tạo ảnh từ tiếng Anh/Tiếng Trung sử dụng HunyuanDiT và [Perturbed Attention Guidance](https://huggingface.co/docs/diffusers/en/using-diffusers/pag).

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các pipeline (chẳng hạn như tải xuống hoặc lưu, chạy trên một thiết bị cụ thể, v.v.)

HunyuanDiT sử dụng hai bộ mã hóa văn bản: [mT5](https://huggingface.co/google/mt5-base) và [bilingual CLIP](được chúng tôi tinh chỉnh)

#### __call__[[diffusers.HunyuanDiTPAGPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_2: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_2: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, output_type: str = 'pil', return_dict: bool = True, callback_on_step_end: typing.Union[typing.Callable[[int, int, dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], guidance_rescale: float = 0.0, original_size: tuple[int, int] = (1024, 1024), target_size: tuple[int, int] = None, crops_coords_top_left: tuple[int, int] = (0, 0), use_resolution_binning: bool = True, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_hunyuandit.py#L579)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `prompt_embeds`.

height (`int`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel.

width (`int`) : Độ rộng của hình ảnh được tạo ra, tính bằng pixel.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, đổi lại là suy luận chậm hơn. Tham số này được điều chỉnh bởi `strength`.

guidance_scale (`float`, *optional*, mặc định là 7.5) : Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi `guidance_scale > 1`.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *tuỳ chọn*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo [DDIM](https://huggingface.co/papers/2010.02502). Chỉ áp dụng cho [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler) và bị bỏ qua ở các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

prompt_embeds_2 (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, `negative_prompt_embeds` sẽ được tạo từ đối số đầu vào `negative_prompt`.

negative_prompt_embeds_2 (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, `negative_prompt_embeds` sẽ được tạo từ đối số đầu vào `negative_prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho prompt. Bắt buộc khi `prompt_embeds` được truyền trực tiếp.

prompt_attention_mask_2 (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho prompt. Bắt buộc khi `prompt_embeds_2` được truyền trực tiếp.

negative_prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho prompt âm. Bắt buộc khi `negative_prompt_embeds` được truyền trực tiếp.

negative_prompt_attention_mask_2 (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho prompt âm. Bắt buộc khi `negative_prompt_embeds_2` được truyền trực tiếp.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

callback_on_step_end (`Callable[[int, int], None]`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm callback hoặc danh sách các hàm callback sẽ được gọi vào cuối mỗi bước khử nhiễu.

callback_on_step_end_tensor_inputs (`list[str]`, *tùy chọn*) : Một danh sách các đầu vào tensor cần được truyền đến hàm callback. Nếu không được định nghĩa, tất cả các đầu vào tensor sẽ được truyền.

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Thang lại noise_cfg theo `guidance_rescale`. Dựa trên các phát hiện của [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Xem Mục 3.4

original_size (`tuple[int, int]`, *tùy chọn*, mặc định là `(1024, 1024)`) : Kích thước gốc của hình ảnh. Được sử dụng để tính toán các id thời gian.

target_size (`tuple[int, int]`, *tùy chọn*) : Kích thước đích của hình ảnh. Được sử dụng để tính toán các id thời gian.

crops_coords_top_left (`tuple[int, int]`, *tùy chọn*, mặc định là `(0, 0)`) : Tọa độ góc trên bên trái của vùng cắt. Được sử dụng để tính toán các id thời gian.

use_resolution_binning (`bool`, *tùy chọn*, mặc định là `True`) : Có sử dụng phân loại độ phân giải hay không. Nếu `True`, độ phân giải đầu vào sẽ được ánh xạ đến độ phân giải chuẩn gần nhất. Các độ phân giải được hỗ trợ là 1024x1024, 1280x1280, 1024x768, 1152x864, 1280x960, 768x1024, 864x1152, 960x1280, 1280x768 và 768x1280. Khuyến nghị đặt giá trị này thành `True`.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo và phần tử thứ hai là một danh sách các `bool` cho biết hình ảnh tương ứng có chứa nội dung "không an toàn" (nsfw) hay không.

Hàm gọi pipeline để tạo nội dung với HunyuanDiT.

Ví dụ:
```python
>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Tencent-Hunyuan/HunyuanDiT-v1.2-Diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=[14],
... ).to("cuda")

>>> # prompt = "an astronaut riding a horse"
>>> prompt = "一个宇航员在骑马"
>>> image = pipe(prompt, guidance_scale=4, pag_scale=3).images[0]
```

#### encode_prompt[[diffusers.HunyuanDiTPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, device: device = None, dtype: dtype = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int | None = None, text_encoder_index: int = 0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_hunyuandit.py#L258)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

dtype (`torch.dtype`) : kiểu dữ liệu torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho prompt. Bắt buộc khi `prompt_embeds` được truyền trực tiếp.

negative_prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho prompt âm. Bắt buộc khi `negative_prompt_embeds` được truyền trực tiếp.

max_sequence_length (`int`, *tuỳ chọn*) : độ dài tối đa của chuỗi để sử dụng cho prompt.

text_encoder_index (`int`, *optional*) : Chỉ số của text encoder cần sử dụng. `0` cho clip và `1` cho T5.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

## KolorsPAGPipeline[[diffusers.KolorsPAGPipeline]]

#### diffusers.KolorsPAGPipeline[[diffusers.KolorsPAGPipeline]]

```python
diffusers.KolorsPAGPipeline(vae: AutoencoderKL, text_encoder: ChatGLMModel, tokenizer: ChatGLMTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, force_zeros_for_empty_prompt: bool = False, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_kolors.py#L128)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder (`ChatGLMModel`) : Bộ mã hóa văn bản đóng băng. Kolors sử dụng [ChatGLM3-6B](https://huggingface.co/THUDM/chatglm3-6b).

tokenizer (`ChatGLMTokenizer`) : Tokenizer của lớp [ChatGLMTokenizer](https://huggingface.co/THUDM/chatglm3-6b/blob/main/tokenization_chatglm.py).

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Kiến trúc U-Net có điều kiện để khử nhiễu các ẩn (latents) của ảnh đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

force_zeros_for_empty_prompt (`bool`, *tùy chọn*, mặc định là `"False"`) : Xác định xem có nên ép buộc các embedding của prompt âm luôn được đặt thành 0 hay không. Xem thêm cấu hình của `Kwai-Kolors/Kolors-diffusers`.

pag_applied_layers (`str` or `list[str]``, *optional*, defaults to `"mid"`) : Set the transformer attention layers where to apply the perturbed attention guidance. Can be a string or a list of strings with "down", "mid", "up", a whole transformer block or specific transformer block attention layers, e.g.: ["mid"] ["down", "mid"] ["down", "mid", "up.block_1"] ["down", "mid", "up.block_1.attentions_0", "up.block_1.attentions_1"]

Pipeline để tạo ảnh từ văn bản sử dụng Kolors.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các pipeline (chẳng hạn như tải xuống hoặc lưu, chạy trên một thiết bị cụ thể, v.v.)

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.KolorsPAGPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, original_size: tuple[int, int] | None = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] | None = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0, max_sequence_length: int = 256)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_kolors.py#L665)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

height (`int`, *tuỳ chọn*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Chiều cao tính bằng pixel của hình ảnh được tạo ra. Giá trị mặc định là 1024 để đạt kết quả tốt nhất. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers) và các checkpoint không được tinh chỉnh đặc biệt cho độ phân giải thấp.

width (`int`, *tuỳ chọn*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Độ rộng tính bằng pixel của hình ảnh được tạo ra. Mặc định được đặt là 1024 để đạt kết quả tốt nhất. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers) và các checkpoint không được tinh chỉnh đặc biệt cho độ phân giải thấp.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

denoising_end (`float`, *optional*) : Khi được chỉ định, xác định tỷ lệ (từ 0.0 đến 1.0) của toàn bộ quá trình khử nhiễu cần hoàn thành trước khi bị kết thúc sớm một cách có chủ đích. Kết quả là, mẫu được trả về vẫn sẽ giữ lại một lượng nhiễu đáng kể, được xác định bởi các bước thời gian rời rạc do trình lập lịch chọn. Tham số denoising_end lý tưởng nhất nên được sử dụng khi pipeline này là một phần của cấu hình đa pipeline "Mixture of Denoisers", như đã mô tả chi tiết trong [**Refining the Image Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)

guidance_scale (`float`, *optional*, mặc định là 5.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *optional*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho [schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể được sử dụng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.kolors.KolorsPipelineOutput` thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Nếu `original_size` không giống với `target_size`, hình ảnh sẽ có vẻ được giảm hoặc tăng mẫu. `original_size` mặc định là `(height, width)` nếu không được chỉ định. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : `crops_coords_top_left` có thể được dùng để tạo ra một hình ảnh trông như đã được "cắt" từ vị trí `crops_coords_top_left` trở xuống. Các hình ảnh đẹp, được căn giữa tốt thường đạt được bằng cách đặt `crops_coords_top_left` thành (0, 0). Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Trong hầu hết các trường hợp, `target_size` nên được đặt thành chiều cao và chiều rộng mong muốn của hình ảnh được tạo. Nếu không được chỉ định, giá trị mặc định sẽ là `(height, width)`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

negative_original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải hình ảnh cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : Để điều kiện âm quá trình tạo dựa trên tọa độ cắt cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải ảnh mục tiêu. Trong hầu hết các trường hợp, nó nên giống với `target_size`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng issue này: https://github.com/huggingface/diffusers/issues/4208.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

max_sequence_length (`int` mặc định là 256) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

**Trả về:** `~pipelines.kolors.KolorsPipelineOutput` hoặc `tuple`

`~pipelines.kolors.KolorsPipelineOutput` nếu `return_dict` là True, ngược lại là một `tuple`. Khi trả về tuple, phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Kwai-Kolors/Kolors-diffusers",
...     variant="fp16",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["down.block_2.attentions_1", "up.block_0.attentions_1"],
... )
>>> pipe = pipe.to("cuda")

>>> prompt = (
...     "A photo of a ladybug, macro, zoom, high quality, film, holding a wooden sign with the text 'KOLORS'"
... )
>>> image = pipe(prompt, guidance_scale=5.5, pag_scale=1.5).images[0]
```

#### encode_prompt[[diffusers.KolorsPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 256)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_kolors.py#L216)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số của prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

max_sequence_length (`int` mặc định là 256) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.KolorsPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_kolors.py#L608)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionPAGInpaintPipeline[[diffusers.StableDiffusionPAGInpaintPipeline]]

#### diffusers.StableDiffusionPAGInpaintPipeline[[diffusers.StableDiffusionPAGInpaintPipeline]]

```python
diffusers.StableDiffusionPAGInpaintPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py#L184)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)) : Bộ mã hóa văn bản đóng băng ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer)) : Một `CLIPTokenizer` để phân tách văn bản.

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Một `UNet2DConditionModel` để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

safety_checker (`StableDiffusionSafetyChecker`) : Module phân loại ước tính xem hình ảnh được tạo ra có thể bị coi là khiêu khích hoặc gây hại hay không. Vui lòng tham khảo [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) để biết thêm chi tiết về các tác hại tiềm ẩn của model.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor)) : Một `CLIPImageProcessor` để trích xuất đặc trưng từ các hình ảnh được tạo ra; được dùng làm đầu vào cho `safety_checker`.

Pipeline để tạo ảnh từ văn bản sử dụng Stable Diffusion.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.StableDiffusionPAGInpaintPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: Tensor = None, height: int | None = None, width: int | None = None, padding_mask_crop: int | None = None, strength: float = 0.9999, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py#L910)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `prompt_embeds`.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`) : `Image`, mảng numpy hoặc tensor đại diện cho một lô ảnh cần được inpaint (các phần của ảnh sẽ bị che bằng `mask_image` và được vẽ lại theo `prompt`).

mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`) : `Image`, mảng numpy hoặc tensor đại diện cho một lô ảnh cần che `image`. Các pixel trắng trong mask sẽ được tô lại trong khi các pixel đen được giữ nguyên. Nếu `mask_image` là ảnh PIL, nó sẽ được chuyển đổi thành một kênh duy nhất (độ sáng) trước khi sử dụng. Nếu là mảng numpy hoặc tensor pytorch, nó phải chứa một kênh màu (L) thay vì 3, do đó hình dạng mong đợi cho tensor pytorch sẽ là `(B, 1, H, W)`, `(B, H, W)`, `(1, H, W)`, `(H, W)`. Và cho mảng numpy sẽ là `(B, H, W, 1)`, `(B, H, W)`, `(H, W, 1)`, hoặc `(H, W)`.

masked_image_latents (`torch.Tensor`, *tùy chọn*) : Latent đã mã hóa trước của hình ảnh bị che (cho inpainting).

height (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel.

width (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Độ rộng tính bằng pixel của hình ảnh được tạo ra.

padding_mask_crop (`int`, *optional*, mặc định là `None`) : Kích thước của phần lề (margin) trong vùng cắt (crop) sẽ được áp dụng cho ảnh và mặt nạ. Nếu là `None`, sẽ không áp dụng cắt cho image và mask_image. Nếu `padding_mask_crop` không phải `None`, hệ thống sẽ trước tiên tìm một vùng hình chữ nhật có cùng tỷ lệ khung hình với ảnh và chứa toàn bộ vùng bị che, sau đó mở rộng vùng đó dựa trên `padding_mask_crop`. Ảnh và mask_image sẽ được cắt dựa trên vùng đã mở rộng trước khi được điều chỉnh kích thước về kích thước ảnh gốc để phục vụ inpainting. Điều này hữu ích khi vùng bị che nhỏ trong khi ảnh lớn và chứa thông tin không liên quan đến inpainting, chẳng hạn như nền.

strength (`float`, *optional*, mặc định là 0.9999) : Chỉ định mức độ biến đổi ảnh tham chiếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` được dùng làm điểm khởi đầu và càng thêm nhiều nhiễu khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khi `strength` bằng 1, nhiễu được thêm vào là tối đa và quá trình khử nhiễu chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Giá trị 1 về cơ bản sẽ bỏ qua `image`.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

guidance_scale (`float`, *optional*, mặc định là 7.5) : Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi `guidance_scale > 1`.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *tuỳ chọn*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo [DDIM](https://huggingface.co/papers/2010.02502). Chỉ áp dụng cho [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler) và bị bỏ qua ở các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, `negative_prompt_embeds` sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa trong [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Hệ số rescale guidance từ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Hệ số rescale guidance nên khắc phục hiện tượng phơi sáng quá mức khi sử dụng zero terminal SNR.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo và phần tử thứ hai là một danh sách các `bool` cho biết hình ảnh tương ứng có chứa nội dung "không an toàn" (nsfw) hay không.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AutoPipelineForInpainting

>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> init_image = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")
>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     strength=0.8,
...     num_inference_steps=50,
...     guidance_scale=guidance_scale,
...     generator=generator,
...     pag_scale=pag_scale,
... ).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionPAGInpaintPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py#L334)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionPAGInpaintPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py#L849)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionPAGPipeline[[diffusers.StableDiffusionPAGPipeline]]

#### diffusers.StableDiffusionPAGPipeline[[diffusers.StableDiffusionPAGPipeline]]

```python
diffusers.StableDiffusionPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd.py#L157)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)) : Bộ mã hóa văn bản đóng băng ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer)) : Một `CLIPTokenizer` để phân tách văn bản.

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Một `UNet2DConditionModel` để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

safety_checker (`StableDiffusionSafetyChecker`) : Module phân loại ước tính xem hình ảnh được tạo ra có thể bị coi là khiêu khích hoặc gây hại hay không. Vui lòng tham khảo [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) để biết thêm chi tiết về các tác hại tiềm ẩn của model.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor)) : Một `CLIPImageProcessor` để trích xuất đặc trưng từ các hình ảnh được tạo ra; được dùng làm đầu vào cho `safety_checker`.

Pipeline để tạo ảnh từ văn bản sử dụng Stable Diffusion.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.StableDiffusionPAGPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd.py#L745)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `prompt_embeds`.

height (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel.

width (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Độ rộng tính bằng pixel của hình ảnh được tạo ra.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

guidance_scale (`float`, *optional*, mặc định là 7.5) : Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi `guidance_scale > 1`.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *tuỳ chọn*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo [DDIM](https://huggingface.co/papers/2010.02502). Chỉ áp dụng cho [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler) và bị bỏ qua ở các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, `negative_prompt_embeds` sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa trong [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Hệ số rescale guidance từ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Hệ số rescale guidance nên khắc phục hiện tượng phơi sáng quá mức khi sử dụng zero terminal SNR.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo và phần tử thứ hai là một danh sách các `bool` cho biết hình ảnh tương ứng có chứa nội dung "không an toàn" (nsfw) hay không.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd.py#L304)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd.py#L684)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionPAGImg2ImgPipeline[[diffusers.StableDiffusionPAGImg2ImgPipeline]]

#### diffusers.StableDiffusionPAGImg2ImgPipeline[[diffusers.StableDiffusionPAGImg2ImgPipeline]]

```python
diffusers.StableDiffusionPAGImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_img2img.py#L152)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)) : Bộ mã hóa văn bản đóng băng ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer)) : Một `CLIPTokenizer` để phân tách văn bản.

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Một `UNet2DConditionModel` để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

safety_checker (`StableDiffusionSafetyChecker`) : Module phân loại ước tính xem hình ảnh được tạo ra có thể bị coi là khiêu khích hoặc gây hại hay không. Vui lòng tham khảo [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) để biết thêm chi tiết về các tác hại tiềm ẩn của model.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor)) : Một `CLIPImageProcessor` để trích xuất đặc trưng từ các hình ảnh được tạo ra; được dùng làm đầu vào cho `safety_checker`.

Pipeline cho việc tạo ảnh từ ảnh có hướng dẫn bằng văn bản sử dụng Stable Diffusion.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.StableDiffusionPAGImg2ImgPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, strength: float = 0.8, num_inference_steps: int | None = 50, timesteps: list[int] = None, sigmas: list[float] = None, guidance_scale: float | None = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float | None = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_img2img.py#L782)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `prompt_embeds`.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`) : `Image`, mảng numpy hoặc tensor đại diện cho một lô ảnh (image batch) được sử dụng làm điểm khởi đầu. Đối với cả mảng numpy và tensor pytorch, khoảng giá trị mong đợi nằm trong `[0, 1]` Nếu là tensor hoặc danh sách các tensor, hình dạng mong đợi nên là `(B, C, H, W)` hoặc `(C, H, W)`. Nếu là mảng numpy hoặc danh sách các mảng, hình dạng mong đợi nên là `(B, H, W, C)` hoặc `(H, W, C)` Nó cũng có thể nhận các image latents dưới dạng `image`, nhưng nếu truyền trực tiếp latents thì chúng sẽ không được mã hóa lại.

strength (`float`, *optional*, mặc định là 0.8) : Chỉ định mức độ biến đổi ảnh tham chiếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` được dùng làm điểm khởi đầu và càng thêm nhiều nhiễu khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khi `strength` là 1, nhiễu được thêm vào là tối đa và quá trình khử nhiễu chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Giá trị 1 về cơ bản sẽ bỏ qua `image`.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, đổi lại là suy luận chậm hơn. Tham số này được điều chỉnh bởi `strength`.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

guidance_scale (`float`, *optional*, mặc định là 7.5) : Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi `guidance_scale > 1`.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *tuỳ chọn*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo [DDIM](https://huggingface.co/papers/2010.02502). Chỉ áp dụng cho [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler) và bị bỏ qua ở các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, `negative_prompt_embeds` sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa trong [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo và phần tử thứ hai là một danh sách các `bool` cho biết hình ảnh tương ứng có chứa nội dung "không an toàn" (nsfw) hay không.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionPAGImg2ImgPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_img2img.py#L299)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionPAGImg2ImgPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_img2img.py#L725)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionControlNetPAGPipeline[[diffusers.StableDiffusionControlNetPAGPipeline]]

#### diffusers.StableDiffusionControlNetPAGPipeline[[diffusers.StableDiffusionControlNetPAGPipeline]]

```python
diffusers.StableDiffusionControlNetPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py#L168)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)) : Bộ mã hóa văn bản đóng băng ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer)) : Một `CLIPTokenizer` để phân tách văn bản.

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Một `UNet2DConditionModel` để khử nhiễu các latents ảnh đã mã hóa.

controlnet ([ControlNetModel](/docs/diffusers/v0.43.0/vi/api/models/controlnet#diffusers.ControlNetModel) hoặc `list[ControlNetModel]`) : Cung cấp điều kiện bổ sung cho `unet` trong quá trình khử nhiễu. Nếu bạn đặt nhiều ControlNet dưới dạng danh sách, đầu ra từ mỗi ControlNet sẽ được cộng lại với nhau để tạo thành một điều kiện bổ sung kết hợp.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

safety_checker (`StableDiffusionSafetyChecker`) : Module phân loại ước tính xem hình ảnh được tạo ra có thể bị coi là khiêu khích hoặc gây hại hay không. Vui lòng tham khảo [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) để biết thêm chi tiết về các tác hại tiềm ẩn của model.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor)) : Một `CLIPImageProcessor` để trích xuất đặc trưng từ các hình ảnh được tạo ra; được dùng làm đầu vào cho `safety_checker`.

Pipeline để tạo ảnh từ văn bản sử dụng Stable Diffusion với sự dẫn dắt của ControlNet.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### encode_prompt[[diffusers.StableDiffusionControlNetPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py#L275)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionControlNetPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py#L810)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionControlNetPAGInpaintPipeline[[diffusers.StableDiffusionControlNetPAGInpaintPipeline]]

#### diffusers.StableDiffusionControlNetPAGInpaintPipeline[[diffusers.StableDiffusionControlNetPAGInpaintPipeline]]

```python
diffusers.StableDiffusionControlNetPAGInpaintPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py#L134)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)) : Bộ mã hóa văn bản đóng băng ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer)) : Một `CLIPTokenizer` để phân tách văn bản.

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Một `UNet2DConditionModel` để khử nhiễu các latents ảnh đã mã hóa.

controlnet ([ControlNetModel](/docs/diffusers/v0.43.0/vi/api/models/controlnet#diffusers.ControlNetModel) hoặc `list[ControlNetModel]`) : Cung cấp điều kiện bổ sung cho `unet` trong quá trình khử nhiễu. Nếu bạn đặt nhiều ControlNet dưới dạng danh sách, đầu ra từ mỗi ControlNet sẽ được cộng lại với nhau để tạo thành một điều kiện bổ sung kết hợp.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

safety_checker (`StableDiffusionSafetyChecker`) : Module phân loại ước tính xem hình ảnh được tạo ra có thể bị coi là khiêu khích hoặc gây hại hay không. Vui lòng tham khảo [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) để biết thêm chi tiết về các tác hại tiềm ẩn của model.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor)) : Một `CLIPImageProcessor` để trích xuất đặc trưng từ các hình ảnh được tạo ra; được dùng làm đầu vào cho `safety_checker`.

Pipeline cho việc inpainting hình ảnh sử dụng Stable Diffusion với sự dẫn dắt của ControlNet.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

> [!TIP] > Pipeline này có thể được sử dụng với các checkpoint đã được fine-tune riêng cho inpainting >
([stable-diffusion-v1-5/stable-diffusion-inpainting](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-inpainting)) cũng như các checkpoint Stable Diffusion mặc định từ văn bản sang ảnh > ([stable-diffusion-v1-5/stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)). Các checkpoint Stable Diffusion từ văn bản sang ảnh mặc định có thể được ưu tiên hơn cho các ControlNet đã được tinh chỉnh trên chúng, chẳng hạn như > [lllyasviel/control_v11p_sd15_inpaint](https://huggingface.co/lllyasviel/control_v11p_sd15_inpaint).

#### __call__[[diffusers.StableDiffusionControlNetPAGInpaintPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, padding_mask_crop: int | None = None, strength: float = 1.0, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, controlnet_conditioning_scale: float | list[float] = 0.5, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py#L972)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `prompt_embeds`.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, : `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`): `Image`, mảng NumPy hoặc tensor đại diện cho một lô ảnh (image batch) được sử dụng làm điểm khởi đầu. Đối với cả mảng NumPy và tensor PyTorch, khoảng giá trị mong đợi nằm trong `[0, 1]`. Nếu là tensor hoặc danh sách các tensor, hình dạng mong đợi phải là `(B, C, H, W)` hoặc `(C, H, W)`. Nếu là mảng NumPy hoặc danh sách các mảng, hình dạng mong đợi phải là `(B, H, W, C)` hoặc `(H, W, C)`. Nó cũng có thể nhận các image latents dưới dạng `image`, nhưng nếu truyền trực tiếp latents thì chúng sẽ không được mã hóa lại.

mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, : `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`): `Image`, mảng NumPy hoặc tensor đại diện cho một lô ảnh cần che `image`. Các pixel trắng trong mask sẽ được tô lại trong khi các pixel đen được giữ nguyên. Nếu `mask_image` là ảnh PIL, nó sẽ được chuyển đổi thành một kênh duy nhất (độ sáng) trước khi sử dụng. Nếu là mảng NumPy hoặc tensor PyTorch, nó phải chứa một kênh màu (L) thay vì 3, do đó hình dạng mong đợi cho tensor PyTorch sẽ là `(B, 1, H, W)`, `(B, H, W)`, `(1, H, W)`, `(H, W)`. Và cho mảng NumPy, nó sẽ là `(B, H, W, 1)`, `(B, H, W)`, `(H, W, 1)`, hoặc `(H, W)`.

control_image (`torch.Tensor`, `PIL.Image.Image`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, : `list[list[torch.Tensor]]`, hoặc `list[list[PIL.Image.Image]]`): Điều kiện đầu vào của ControlNet để cung cấp hướng dẫn cho `unet` trong quá trình tạo ảnh. Nếu kiểu được chỉ định là `torch.Tensor`, nó sẽ được truyền vào ControlNet nguyên vẹn. `PIL.Image.Image` cũng có thể được chấp nhận dưới dạng ảnh. Kích thước của ảnh đầu ra mặc định là kích thước của `image`. Nếu chiều cao và/hoặc chiều rộng được truyền vào, `image` sẽ được thay đổi kích thước cho phù hợp. Nếu nhiều ControlNet được chỉ định trong `init`, các ảnh phải được truyền dưới dạng danh sách sao cho mỗi phần tử của danh sách có thể được batch đúng cách để làm đầu vào cho một ControlNet duy nhất.

height (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel.

width (`int`, *tùy chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Độ rộng tính bằng pixel của hình ảnh được tạo ra.

padding_mask_crop (`int`, *optional*, mặc định là `None`) : Kích thước của phần lề (margin) trong vùng cắt (crop) sẽ được áp dụng cho ảnh và mặt nạ. Nếu là `None`, sẽ không áp dụng cắt cho image và mask_image. Nếu `padding_mask_crop` không phải `None`, hệ thống sẽ trước tiên tìm một vùng hình chữ nhật có cùng tỷ lệ khung hình với ảnh và chứa toàn bộ vùng bị che, sau đó mở rộng vùng đó dựa trên `padding_mask_crop`. Ảnh và mask_image sẽ được cắt dựa trên vùng đã mở rộng trước khi được điều chỉnh kích thước về kích thước ảnh gốc để phục vụ inpainting. Điều này hữu ích khi vùng bị che nhỏ trong khi ảnh lớn và chứa thông tin không liên quan đến inpainting, chẳng hạn như nền.

strength (`float`, *optional*, mặc định là 1.0) : Chỉ định mức độ biến đổi ảnh tham chiếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` được dùng làm điểm khởi đầu và càng thêm nhiều nhiễu khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu được thêm vào ban đầu. Khi `strength` là 1, nhiễu được thêm vào là tối đa và quá trình khử nhiễu chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Giá trị 1 về cơ bản sẽ bỏ qua `image`.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

guidance_scale (`float`, *optional*, mặc định là 7.5) : Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi `guidance_scale > 1`.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *tuỳ chọn*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo [DDIM](https://huggingface.co/papers/2010.02502). Chỉ áp dụng cho [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler) và bị bỏ qua ở các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, `negative_prompt_embeds` sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa trong [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

controlnet_conditioning_scale (`float` hoặc `list[float]`, *không bắt buộc*, mặc định là 0.5) : Đầu ra của ControlNet được nhân với `controlnet_conditioning_scale` trước khi được cộng vào phần dư trong `unet` gốc. Nếu nhiều ControlNet được chỉ định trong `init`, bạn có thể đặt thang đo tương ứng dưới dạng một danh sách.

control_guidance_start (`float` hoặc `list[float]`, *tuỳ chọn*, mặc định là 0.0) : Tỷ lệ phần trăm của tổng số bước mà tại đó ControlNet bắt đầu áp dụng.

control_guidance_end (`float` hoặc `list[float]`, *tuỳ chọn*, mặc định là 1.0) : Tỷ lệ phần trăm tổng số bước mà tại đó ControlNet ngừng áp dụng.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo và phần tử thứ hai là một danh sách các `bool` cho biết hình ảnh tương ứng có chứa nội dung "không an toàn" (nsfw) hay không.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```py
>>> # !pip install transformers accelerate
>>> import cv2
>>> from diffusers import AutoPipelineForInpainting, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> from PIL import Image
>>> import torch

>>> init_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((512, 512))

>>> generator = torch.Generator(device="cpu").manual_seed(1)

>>> mask_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((512, 512))

>>> def make_canny_condition(image):
...     image = np.array(image)
...     image = cv2.Canny(image, 100, 200)
...     image = image[:, :, None]
...     image = np.concatenate([image, image, image], axis=2)
...     image = Image.fromarray(image)
...     return image

>>> control_image = make_canny_condition(init_image)

>>> controlnet = ControlNetModel.from_pretrained(
...     "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16
... )
>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     controlnet=controlnet,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )

>>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> image = pipe(
...     "a handsome man with ray-ban sunglasses",
...     num_inference_steps=20,
...     generator=generator,
...     eta=1.0,
...     image=init_image,
...     mask_image=mask_image,
...     control_image=control_image,
...     pag_scale=0.3,
... ).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionControlNetPAGInpaintPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py#L251)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionControlNetPAGInpaintPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py#L919)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionXLPAGPipeline[[diffusers.StableDiffusionXLPAGPipeline]]

#### diffusers.StableDiffusionXLPAGPipeline[[diffusers.StableDiffusionXLPAGPipeline]]

```python
diffusers.StableDiffusionXLPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl.py#L172)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder (`CLIPTextModel`) : Bộ mã hóa văn bản đóng băng. Stable Diffusion XL sử dụng phần văn bản của [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14).

text_encoder_2 (` CLIPTextModelWithProjection`) : Bộ mã hóa văn bản đóng băng thứ hai. Stable Diffusion XL sử dụng phần văn bản và pool của [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), cụ thể là biến thể [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k).

tokenizer (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_2 (`CLIPTokenizer`) : Tokenizer thứ hai thuộc lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Kiến trúc U-Net có điều kiện để khử nhiễu các ẩn (latents) của ảnh đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

force_zeros_for_empty_prompt (`bool`, *tùy chọn*, mặc định là `"True"`) : Xác định xem các embedding của prompt tiêu cực có nên được ép buộc luôn đặt về 0 hay không. Xem thêm cấu hình của `stabilityai/stable-diffusion-xl-base-1-0`.

add_watermarker (`bool`, *tuỳ chọn*) : Có sử dụng [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) để thêm watermark cho các hình ảnh đầu ra hay không. Nếu không được định nghĩa, giá trị mặc định sẽ là True nếu gói đã được cài đặt, ngược lại sẽ không sử dụng công cụ watermark.

Pipeline để tạo ảnh từ văn bản sử dụng Stable Diffusion XL.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các pipeline (chẳng hạn như tải xuống hoặc lưu, chạy trên một thiết bị cụ thể, v.v.)

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.StableDiffusionXLPAGPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, original_size: tuple[int, int] | None = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] | None = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl.py#L836)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder

height (`int`, *tuỳ chọn*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Chiều cao tính bằng pixel của hình ảnh được tạo ra. Mặc định được đặt là 1024 để đạt kết quả tốt nhất. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) và các checkpoint không được tinh chỉnh đặc biệt cho độ phân giải thấp.

width (`int`, *tuỳ chọn*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Độ rộng tính bằng pixel của hình ảnh được tạo ra. Mặc định được đặt là 1024 để đạt kết quả tốt nhất. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) và các checkpoint không được tinh chỉnh đặc biệt cho độ phân giải thấp.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

denoising_end (`float`, *optional*) : Khi được chỉ định, xác định tỷ lệ (từ 0.0 đến 1.0) của toàn bộ quá trình khử nhiễu cần hoàn thành trước khi bị kết thúc sớm một cách có chủ đích. Kết quả là, mẫu được trả về vẫn sẽ giữ lại một lượng nhiễu đáng kể, được xác định bởi các bước thời gian rời rạc do trình lập lịch chọn. Tham số denoising_end lý tưởng nhất nên được sử dụng khi pipeline này là một phần của cấu hình đa pipeline "Mixture of Denoisers", như đã mô tả chi tiết trong [**Refining the Image Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)

guidance_scale (`float`, *optional*, mặc định là 5.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *optional*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho [schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể được sử dụng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Hệ số rescale guidance được đề xuất bởi [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` được định nghĩa là `φ` trong phương trình 16. của [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Hệ số rescale guidance nên khắc phục hiện tượng phơi sáng quá mức khi sử dụng zero terminal SNR.

original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Nếu `original_size` không giống với `target_size`, hình ảnh sẽ có vẻ được giảm hoặc tăng mẫu. `original_size` mặc định là `(height, width)` nếu không được chỉ định. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : `crops_coords_top_left` có thể được dùng để tạo ra một hình ảnh trông như đã được "cắt" từ vị trí `crops_coords_top_left` trở xuống. Các hình ảnh đẹp, được căn giữa tốt thường đạt được bằng cách đặt `crops_coords_top_left` thành (0, 0). Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Trong hầu hết các trường hợp, `target_size` nên được đặt thành chiều cao và chiều rộng mong muốn của hình ảnh được tạo. Nếu không được chỉ định, giá trị mặc định sẽ là `(height, width)`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

negative_original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải hình ảnh cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : Để điều kiện âm quá trình tạo dựa trên tọa độ cắt cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải ảnh mục tiêu. Trong hầu hết các trường hợp, nó nên giống với `target_size`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng issue này: https://github.com/huggingface/diffusers/issues/4208.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` hoặc `tuple`

`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` nếu `return_dict` là True, ngược lại là một `tuple`. Khi trả về tuple, phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, prompt_2: str | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, negative_prompt_2: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl.py#L293)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Một hệ số lora sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl.py#L771)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionXLPAGImg2ImgPipeline[[diffusers.StableDiffusionXLPAGImg2ImgPipeline]]

#### diffusers.StableDiffusionXLPAGImg2ImgPipeline[[diffusers.StableDiffusionXLPAGImg2ImgPipeline]]

```python
diffusers.StableDiffusionXLPAGImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py#L191)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder (`CLIPTextModel`) : Bộ mã hóa văn bản đóng băng. Stable Diffusion XL sử dụng phần văn bản của [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14).

text_encoder_2 (` CLIPTextModelWithProjection`) : Bộ mã hóa văn bản đóng băng thứ hai. Stable Diffusion XL sử dụng phần văn bản và pool của [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), cụ thể là biến thể [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k).

tokenizer (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_2 (`CLIPTokenizer`) : Tokenizer thứ hai thuộc lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Kiến trúc U-Net có điều kiện để khử nhiễu các ẩn (latents) của ảnh đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

requires_aesthetics_score (`bool`, *tùy chọn*, mặc định là `"False"`) : Xác định xem `unet` có yêu cầu điều kiện `aesthetic_score` được truyền vào trong quá trình suy luận hay không. Xem thêm cấu hình của `stabilityai/stable-diffusion-xl-refiner-1-0`.

force_zeros_for_empty_prompt (`bool`, *tùy chọn*, mặc định là `"True"`) : Xác định xem các embedding của prompt tiêu cực có nên được ép buộc luôn đặt về 0 hay không. Xem thêm cấu hình của `stabilityai/stable-diffusion-xl-base-1-0`.

add_watermarker (`bool`, *tuỳ chọn*) : Có sử dụng [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) để thêm watermark cho các hình ảnh đầu ra hay không. Nếu không được định nghĩa, giá trị mặc định sẽ là True nếu gói đã được cài đặt, ngược lại sẽ không sử dụng công cụ watermark.

Pipeline để tạo ảnh từ văn bản sử dụng Stable Diffusion XL.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các pipeline (chẳng hạn như tải xuống hoặc lưu, chạy trên một thiết bị cụ thể, v.v.)

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.StableDiffusionXLPAGImg2ImgPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, strength: float = 0.3, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, denoising_start: float | None = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, original_size: tuple[int, int] = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, aesthetic_score: float = 6.0, negative_aesthetic_score: float = 2.5, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py#L989)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder

image (`torch.Tensor` hoặc `PIL.Image.Image` hoặc `np.ndarray` hoặc `list[torch.Tensor]` hoặc `list[PIL.Image.Image]` hoặc `list[np.ndarray]`) : Ảnh cần chỉnh sửa bằng pipeline.

strength (`float`, *optional*, mặc định là 0.3) : Về mặt khái niệm, chỉ ra mức độ biến đổi hình ảnh tham chiếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` sẽ được dùng làm điểm khởi đầu, với lượng nhiễu được thêm vào càng lớn khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu được thêm vào ban đầu. Khi `strength` bằng 1, lượng nhiễu thêm vào sẽ đạt mức tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Do đó, giá trị 1 về cơ bản sẽ bỏ qua `image`. Lưu ý rằng trong trường hợp `denoising_start` được khai báo là số nguyên, giá trị của `strength` sẽ bị bỏ qua.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

denoising_start (`float`, *optional*) : Khi được chỉ định, tham số này cho biết tỷ lệ (từ 0.0 đến 1.0) của toàn bộ quá trình khử nhiễu sẽ bị bỏ qua trước khi quá trình bắt đầu. Do đó, phần đầu của quá trình khử nhiễu sẽ bị bỏ qua và hình ảnh `image` được truyền vào được giả định là một hình ảnh đã được khử nhiễu một phần. Lưu ý rằng khi tham số này được chỉ định, strength sẽ bị bỏ qua. Tham số `denoising_start` đặc biệt hữu ích khi pipeline này được tích hợp vào cấu hình đa pipeline "Mixture of Denoisers", như được mô tả chi tiết trong [**Nâng cao chất lượng hình ảnh**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).

denoising_end (`float`, *optional*) : Khi được chỉ định, xác định tỷ lệ (từ 0.0 đến 1.0) của toàn bộ quá trình khử nhiễu cần hoàn thành trước khi bị kết thúc sớm một cách có chủ đích. Kết quả là, mẫu được trả về vẫn sẽ giữ lại một lượng nhiễu đáng kể (khoảng 20% các bước thời gian cuối cùng vẫn cần thiết) và nên được khử nhiễu bởi một pipeline kế tiếp có `denoising_start` được đặt thành 0.8 để chỉ khử nhiễu 20% cuối cùng của trình lập lịch. Tham số denoising_end lý tưởng nhất nên được sử dụng khi pipeline này là một phần của cấu hình đa pipeline "Mixture of Denoisers", như đã mô tả chi tiết trong [**Nâng cao chất lượng hình ảnh**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).

guidance_scale (`float`, *optional*, mặc định là 7.5) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *optional*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho [schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể được sử dụng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Hệ số rescale guidance được đề xuất bởi [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` được định nghĩa là `φ` trong phương trình 16. của [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Hệ số rescale guidance nên khắc phục hiện tượng phơi sáng quá mức khi sử dụng zero terminal SNR.

original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Nếu `original_size` không giống với `target_size`, hình ảnh sẽ có vẻ được giảm hoặc tăng mẫu. `original_size` mặc định là `(height, width)` nếu không được chỉ định. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : `crops_coords_top_left` có thể được dùng để tạo ra một hình ảnh trông như đã được "cắt" từ vị trí `crops_coords_top_left` trở xuống. Các hình ảnh đẹp, được căn giữa tốt thường đạt được bằng cách đặt `crops_coords_top_left` thành (0, 0). Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Trong hầu hết các trường hợp, `target_size` nên được đặt thành chiều cao và chiều rộng mong muốn của hình ảnh được tạo. Nếu không được chỉ định, giá trị mặc định sẽ là `(height, width)`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

negative_original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải hình ảnh cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : Để điều kiện âm quá trình tạo dựa trên tọa độ cắt cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải ảnh mục tiêu. Trong hầu hết các trường hợp, nó nên giống với `target_size`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng issue này: https://github.com/huggingface/diffusers/issues/4208.

aesthetic_score (`float`, *tuỳ chọn*, mặc định là 6.0) : Được dùng để mô phỏng điểm thẩm mỹ của hình ảnh được tạo ra bằng cách ảnh hưởng đến điều kiện văn bản tích cực. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

negative_aesthetic_score (`float`, *tuỳ chọn*, mặc định là 2.5) : Một phần của micro-conditioning trong SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Có thể được sử dụng để mô phỏng điểm thẩm mỹ của hình ảnh được tạo ra bằng cách ảnh hưởng đến điều kiện văn bản âm.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` hoặc `tuple`

`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` nếu `return_dict` là True, ngược lại là một `tuple. Khi trả về tuple, phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-refiner-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLPAGImg2ImgPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, prompt_2: str | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, negative_prompt_2: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py#L311)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Một hệ số lora sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLPAGImg2ImgPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py#L920)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionXLPAGInpaintPipeline[[diffusers.StableDiffusionXLPAGInpaintPipeline]]

#### diffusers.StableDiffusionXLPAGInpaintPipeline[[diffusers.StableDiffusionXLPAGInpaintPipeline]]

```python
diffusers.StableDiffusionXLPAGInpaintPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py#L204)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder (`CLIPTextModel`) : Bộ mã hóa văn bản đóng băng. Stable Diffusion XL sử dụng phần văn bản của [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14).

text_encoder_2 (` CLIPTextModelWithProjection`) : Bộ mã hóa văn bản đóng băng thứ hai. Stable Diffusion XL sử dụng phần văn bản và pool của [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), cụ thể là biến thể [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k).

tokenizer (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_2 (`CLIPTokenizer`) : Tokenizer thứ hai thuộc lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Kiến trúc U-Net có điều kiện để khử nhiễu các ẩn (latents) của ảnh đã mã hóa.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

requires_aesthetics_score (`bool`, *tùy chọn*, mặc định là `"False"`) : Xác định xem `unet` có yêu cầu điều kiện aesthetic_score được truyền vào trong quá trình suy luận hay không. Xem thêm cấu hình của `stabilityai/stable-diffusion-xl-refiner-1-0`.

force_zeros_for_empty_prompt (`bool`, *tùy chọn*, mặc định là `"True"`) : Xác định xem các embedding của prompt tiêu cực có nên được ép buộc luôn đặt về 0 hay không. Xem thêm cấu hình của `stabilityai/stable-diffusion-xl-base-1-0`.

add_watermarker (`bool`, *tuỳ chọn*) : Có sử dụng [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) để thêm watermark cho các hình ảnh đầu ra hay không. Nếu không được định nghĩa, giá trị mặc định sẽ là True nếu gói đã được cài đặt, ngược lại sẽ không sử dụng công cụ watermark.

Pipeline để tạo ảnh từ văn bản sử dụng Stable Diffusion XL.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các pipeline (chẳng hạn như tải xuống hoặc lưu, chạy trên một thiết bị cụ thể, v.v.)

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.StableDiffusionXLPAGInpaintPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: Tensor = None, height: int | None = None, width: int | None = None, padding_mask_crop: int | None = None, strength: float = 0.9999, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, denoising_start: float | None = None, denoising_end: float | None = None, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, original_size: tuple[int, int] = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, aesthetic_score: float = 6.0, negative_aesthetic_score: float = 2.5, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py#L1080)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder

image (`PIL.Image.Image`) : `Image`, hoặc tensor đại diện cho một lô ảnh sẽ được inpaint, *tức là* một phần của ảnh sẽ bị che đi bằng `mask_image` và được vẽ lại theo `prompt`.

mask_image (`PIL.Image.Image`) : `Image`, hoặc tensor đại diện cho một lô ảnh, dùng để tạo mặt nạ cho `image`. Các pixel trắng trong mặt nạ sẽ được tô lại, trong khi các pixel đen sẽ được giữ nguyên. Nếu `mask_image` là ảnh PIL, nó sẽ được chuyển đổi thành một kênh duy nhất (độ sáng) trước khi sử dụng. Nếu là tensor, nó phải chứa một kênh màu (L) thay vì 3, do đó hình dạng mong đợi sẽ là `(B, H, W, 1)`.

masked_image_latents (`torch.Tensor`, *tùy chọn*) : Latent đã mã hóa trước của hình ảnh bị che (cho inpainting).

height (`int`, *tuỳ chọn*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Chiều cao tính bằng pixel của hình ảnh được tạo ra. Mặc định được đặt là 1024 để đạt kết quả tốt nhất. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) và các checkpoint không được tinh chỉnh đặc biệt cho độ phân giải thấp.

width (`int`, *tuỳ chọn*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Độ rộng tính bằng pixel của hình ảnh được tạo ra. Mặc định được đặt là 1024 để đạt kết quả tốt nhất. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) và các checkpoint không được tinh chỉnh đặc biệt cho độ phân giải thấp.

padding_mask_crop (`int`, *optional*, mặc định là `None`) : Kích thước của phần lề (margin) trong vùng cắt (crop) sẽ được áp dụng cho ảnh và mặt nạ. Nếu là `None`, sẽ không áp dụng cắt cho image và mask_image. Nếu `padding_mask_crop` không phải `None`, hệ thống sẽ trước tiên tìm một vùng hình chữ nhật có cùng tỷ lệ khung hình với ảnh và chứa toàn bộ vùng bị che, sau đó mở rộng vùng đó dựa trên `padding_mask_crop`. Ảnh và mask_image sẽ được cắt dựa trên vùng đã mở rộng trước khi được điều chỉnh kích thước về kích thước ảnh gốc để phục vụ inpainting. Điều này hữu ích khi vùng bị che nhỏ trong khi ảnh lớn và chứa thông tin không liên quan đến inpainting, chẳng hạn như nền.

strength (`float`, *optional*, mặc định là 0.9999) : Về mặt khái niệm, chỉ ra mức độ biến đổi phần bị che khuất của `image` tham chiếu. Phải nằm trong khoảng từ 0 đến 1. `image` sẽ được dùng làm điểm khởi đầu, thêm nhiều nhiễu hơn khi `strength` càng lớn. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khi `strength` là 1, nhiễu được thêm vào sẽ ở mức tối đa và quá trình khử nhiễu sẽ chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Do đó, giá trị 1 về cơ bản sẽ bỏ qua phần bị che khuất của `image` tham chiếu. Lưu ý rằng trong trường hợp `denoising_start` được khai báo là số nguyên, giá trị của `strength` sẽ bị bỏ qua.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

denoising_start (`float`, *optional*) : Khi được chỉ định, cho biết tỷ lệ (từ 0.0 đến 1.0) của toàn bộ quá trình khử nhiễu sẽ bị bỏ qua trước khi bắt đầu. Do đó, phần đầu của quá trình khử nhiễu sẽ bị bỏ qua và `image` được truyền vào được giả định là một hình ảnh đã được khử nhiễu một phần. Lưu ý rằng khi tham số này được chỉ định, strength sẽ bị bỏ qua. Tham số `denoising_start` đặc biệt hữu ích khi pipeline này được tích hợp vào cấu hình đa pipeline "Mixture of Denoisers", như được mô tả chi tiết trong [**Refining the Image Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).

denoising_end (`float`, *optional*) : Khi được chỉ định, xác định tỷ lệ (từ 0.0 đến 1.0) của toàn bộ quá trình khử nhiễu cần hoàn thành trước khi bị kết thúc sớm một cách có chủ đích. Kết quả là, mẫu được trả về vẫn sẽ giữ lại một lượng nhiễu đáng kể (khoảng 20% các bước thời gian cuối cùng vẫn cần thiết) và nên được khử nhiễu bởi một pipeline kế tiếp có `denoising_start` được đặt thành 0.8 để chỉ khử nhiễu 20% cuối cùng của trình lập lịch. Tham số denoising_end lý tưởng nhất nên được sử dụng khi pipeline này là một phần của cấu hình đa pipeline "Mixture of Denoisers", như đã mô tả chi tiết trong [**Refining the Image Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).

guidance_scale (`float`, *optional*, mặc định là 7.5) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *optional*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho [schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác.

generator (`torch.Generator`, *tùy chọn*) : Một hoặc một danh sách [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) để làm cho quá trình sinh trở nên tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể được sử dụng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Nếu `original_size` không giống với `target_size`, hình ảnh sẽ có vẻ được giảm hoặc tăng mẫu. `original_size` mặc định là `(height, width)` nếu không được chỉ định. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : `crops_coords_top_left` có thể được dùng để tạo ra một hình ảnh trông như đã được "cắt" từ vị trí `crops_coords_top_left` trở xuống. Các hình ảnh đẹp, được căn giữa tốt thường đạt được bằng cách đặt `crops_coords_top_left` thành (0, 0). Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Trong hầu hết các trường hợp, `target_size` nên được đặt thành chiều cao và chiều rộng mong muốn của hình ảnh được tạo. Nếu không được chỉ định, giá trị mặc định sẽ là `(height, width)`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

negative_original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải hình ảnh cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : Để điều kiện âm quá trình tạo dựa trên tọa độ cắt cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải ảnh mục tiêu. Trong hầu hết các trường hợp, nó nên giống với `target_size`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng issue này: https://github.com/huggingface/diffusers/issues/4208.

aesthetic_score (`float`, *tuỳ chọn*, mặc định là 6.0) : Được dùng để mô phỏng điểm thẩm mỹ của hình ảnh được tạo ra bằng cách ảnh hưởng đến điều kiện văn bản tích cực. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

negative_aesthetic_score (`float`, *tuỳ chọn*, mặc định là 2.5) : Một phần của micro-conditioning trong SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Có thể được sử dụng để mô phỏng điểm thẩm mỹ của hình ảnh được tạo ra bằng cách ảnh hưởng đến điều kiện văn bản âm.

guidance_rescale (`float`, *tuỳ chọn*, mặc định là 0.0) : Hệ số rescale guidance từ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` hoặc `tuple`

`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` nếu `return_dict` là True, ngược lại là một `tuple. `tuple. Khi trả về một tuple, phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AutoPipelineForInpainting
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     variant="fp16",
...     enable_pag=True,
... )
>>> pipe.to("cuda")

>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

>>> init_image = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")

>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     num_inference_steps=50,
...     strength=0.80,
...     pag_scale=0.3,
... ).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLPAGInpaintPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, prompt_2: str | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, negative_prompt_2: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py#L401)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Một hệ số lora sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLPAGInpaintPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py#L1011)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionXLControlNetPAGPipeline[[diffusers.StableDiffusionXLControlNetPAGPipeline]]

#### diffusers.StableDiffusionXLControlNetPAGPipeline[[diffusers.StableDiffusionXLControlNetPAGPipeline]]

```python
diffusers.StableDiffusionXLControlNetPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, feature_extractor: CLIPImageProcessorPil = None, image_encoder: CLIPVisionModelWithProjection = None, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py#L185)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)) : Bộ mã hóa văn bản đóng băng ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

text_encoder_2 ([CLIPTextModelWithProjection](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModelWithProjection)) : Bộ mã hóa văn bản đóng băng thứ hai ([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer)) : Một `CLIPTokenizer` để phân tách văn bản.

tokenizer_2 ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer)) : Một `CLIPTokenizer` để phân tách văn bản.

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Một `UNet2DConditionModel` để khử nhiễu các latents ảnh đã mã hóa.

controlnet ([ControlNetModel](/docs/diffusers/v0.43.0/vi/api/models/controlnet#diffusers.ControlNetModel) hoặc `list[ControlNetModel]`) : Cung cấp điều kiện bổ sung cho `unet` trong quá trình khử nhiễu. Nếu bạn đặt nhiều ControlNet dưới dạng danh sách, đầu ra từ mỗi ControlNet sẽ được cộng lại với nhau để tạo thành một điều kiện bổ sung kết hợp.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

force_zeros_for_empty_prompt (`bool`, *tùy chọn*, mặc định là `"True"`) : Xác định xem các embedding của prompt tiêu cực có luôn được đặt thành 0 hay không. Xem thêm cấu hình của `stabilityai/stable-diffusion-xl-base-1-0`.

add_watermarker (`bool`, *optional*) : Có sử dụng thư viện [invisible_watermark](https://github.com/ShieldMnt/invisible-watermark/) để thêm watermark cho các hình ảnh đầu ra hay không. Nếu không được định nghĩa, giá trị mặc định là `True` nếu gói đã được cài đặt; nếu không, sẽ không sử dụng công cụ watermark.

Pipeline để tạo ảnh từ văn bản sử dụng Stable Diffusion XL với sự dẫn dắt của ControlNet.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [from_single_file()](/docs/diffusers/v0.43.0/vi/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) để tải các tệp `.ckpt`
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.StableDiffusionXLControlNetPAGPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, controlnet_conditioning_scale: float | list[float] = 1.0, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, original_size: tuple[int, int] = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py#L1003)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `prompt_embeds`.

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, `list[np.ndarray]`, : `list[list[torch.Tensor]]`, `list[list[np.ndarray]]` hoặc `list[list[PIL.Image.Image]]`): Điều kiện đầu vào của ControlNet để cung cấp hướng dẫn cho `unet` trong quá trình tạo ảnh. Nếu kiểu được chỉ định là `torch.Tensor`, nó sẽ được truyền vào ControlNet nguyên vẹn. `PIL.Image.Image` cũng có thể được chấp nhận dưới dạng ảnh. Kích thước của ảnh đầu ra mặc định là kích thước của `image`. Nếu chiều cao và/hoặc chiều rộng được truyền vào, `image` sẽ được thay đổi kích thước cho phù hợp. Nếu nhiều ControlNet được chỉ định trong `init`, các ảnh phải được truyền dưới dạng danh sách sao cho mỗi phần tử của danh sách có thể được nhóm (batch) chính xác để làm đầu vào cho một ControlNet duy nhất.

height (`int`, *tuỳ chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) và các checkpoint không được tinh chỉnh cụ thể cho độ phân giải thấp.

width (`int`, *tuỳ chọn*, mặc định là `self.unet.config.sample_size * self.vae_scale_factor`) : Độ rộng tính bằng pixel của hình ảnh được tạo ra. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) và các checkpoint không được tinh chỉnh cụ thể cho độ phân giải thấp.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

denoising_end (`float`, *optional*) : Khi được chỉ định, xác định tỷ lệ (từ 0.0 đến 1.0) của toàn bộ quá trình khử nhiễu cần hoàn thành trước khi bị kết thúc sớm một cách có chủ đích. Kết quả là, mẫu được trả về vẫn sẽ giữ lại một lượng nhiễu đáng kể, được xác định bởi các bước thời gian rời rạc do trình lập lịch chọn. Tham số denoising_end lý tưởng nhất nên được sử dụng khi pipeline này là một phần của cấu hình đa pipeline "Mixture of Denoisers", như đã mô tả chi tiết trong [**Refining the Image Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)

guidance_scale (`float`, *optional*, mặc định là 5.0) : Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi `guidance_scale > 1`.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (`guidance_scale < 1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nội dung này được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder.

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *tuỳ chọn*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo [DDIM](https://huggingface.co/papers/2010.02502). Chỉ áp dụng cho [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler) và bị bỏ qua ở các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, `negative_prompt_embeds` sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các `negative_prompt_embeds` pooled sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa trong [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

controlnet_conditioning_scale (`float` hoặc `list[float]`, *tuỳ chọn*, mặc định là 1.0) : Đầu ra của ControlNet được nhân với `controlnet_conditioning_scale` trước khi được cộng vào phần dư trong `unet` gốc. Nếu nhiều ControlNet được chỉ định trong `init`, bạn có thể đặt thang đo tương ứng dưới dạng danh sách.

control_guidance_start (`float` hoặc `list[float]`, *tuỳ chọn*, mặc định là 0.0) : Tỷ lệ phần trăm của tổng số bước mà tại đó ControlNet bắt đầu áp dụng.

control_guidance_end (`float` hoặc `list[float]`, *tuỳ chọn*, mặc định là 1.0) : Tỷ lệ phần trăm tổng số bước mà tại đó ControlNet ngừng áp dụng.

original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Nếu `original_size` không giống với `target_size`, hình ảnh sẽ có vẻ được giảm hoặc tăng mẫu. `original_size` mặc định là `(height, width)` nếu không được chỉ định. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : `crops_coords_top_left` có thể được dùng để tạo ra một hình ảnh trông như đã được "cắt" từ vị trí `crops_coords_top_left` trở xuống. Các hình ảnh đẹp, được căn giữa tốt thường đạt được bằng cách đặt `crops_coords_top_left` thành (0, 0). Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Trong hầu hết các trường hợp, `target_size` nên được đặt thành chiều cao và chiều rộng mong muốn của hình ảnh được tạo. Nếu không được chỉ định, giá trị mặc định sẽ là `(height, width)`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

negative_original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải hình ảnh cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : Để điều kiện âm quá trình tạo dựa trên tọa độ cắt cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải ảnh mục tiêu. Trong hầu hết các trường hợp, nó nên giống với `target_size`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng issue này: https://github.com/huggingface/diffusers/issues/4208.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) sẽ được trả về, ngược lại một `tuple` chứa các hình ảnh đầu ra sẽ được trả về.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```py
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import AutoPipelineForText2Image, ControlNetModel, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch

>>> import cv2
>>> from PIL import Image

>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
>>> negative_prompt = "low quality, bad quality, sketches"

>>> # download an image
>>> image = load_image(
...     "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )

>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()

>>> # get canny image
>>> image = np.array(image)
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)

>>> # generate image
>>> image = pipe(
...     prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image, pag_scale=0.3
... ).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLControlNetPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, prompt_2: str | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, negative_prompt_2: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py#L306)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Một hệ số lora sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLControlNetPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py#L946)

**Tham số:**

w (`torch.Tensor`) : Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.

embedding_dim (`int`, *tuỳ chọn*, mặc định là 512) : Kích thước của các embedding cần tạo.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : Kiểu dữ liệu của các embedding được tạo ra.

**Trả về:** `torch.Tensor`

Các vector nhúng có hình dạng `(len(w), embedding_dim)`.

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionXLControlNetPAGImg2ImgPipeline[[diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline]]

#### diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline[[diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline]]

```python
diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, feature_extractor: CLIPImageProcessorPil = None, image_encoder: CLIPVisionModelWithProjection = None, pag_applied_layers: str | list[str] = 'mid')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py#L163)

**Tham số:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder (`CLIPTextModel`) : Bộ mã hóa văn bản đóng băng. Stable Diffusion sử dụng phần văn bản của [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14).

text_encoder_2 (` CLIPTextModelWithProjection`) : Bộ mã hóa văn bản đóng băng thứ hai. Stable Diffusion XL sử dụng phần văn bản và pool của [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), cụ thể là biến thể [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k).

tokenizer (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_2 (`CLIPTokenizer`) : Tokenizer thứ hai thuộc lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/vi/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : Kiến trúc U-Net có điều kiện để khử nhiễu các ẩn (latents) của ảnh đã mã hóa.

controlnet ([ControlNetModel](/docs/diffusers/v0.43.0/vi/api/models/controlnet#diffusers.ControlNetModel) hoặc `list[ControlNetModel]`) : Cung cấp điều kiện bổ sung cho unet trong quá trình khử nhiễu. Nếu bạn đặt nhiều ControlNet dưới dạng danh sách, các đầu ra từ mỗi ControlNet sẽ được cộng lại với nhau để tạo thành một điều kiện bổ sung kết hợp.

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong [DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), hoặc [PNDMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/pndm#diffusers.PNDMScheduler).

requires_aesthetics_score (`bool`, *tùy chọn*, mặc định là `"False"`) : Xác định xem `unet` có yêu cầu điều kiện `aesthetic_score` được truyền vào trong quá trình suy luận hay không. Xem thêm cấu hình của `stabilityai/stable-diffusion-xl-refiner-1-0`.

force_zeros_for_empty_prompt (`bool`, *tùy chọn*, mặc định là `"True"`) : Xác định xem các embedding của prompt tiêu cực có nên được ép buộc luôn đặt về 0 hay không. Xem thêm cấu hình của `stabilityai/stable-diffusion-xl-base-1-0`.

add_watermarker (`bool`, *tuỳ chọn*) : Có sử dụng [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) để thêm watermark cho các hình ảnh đầu ra hay không. Nếu không được định nghĩa, giá trị mặc định sẽ là True nếu gói đã được cài đặt, ngược lại sẽ không sử dụng công cụ watermark.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor)) : Một `CLIPImageProcessor` để trích xuất đặc trưng từ các hình ảnh được tạo ra; được dùng làm đầu vào cho `safety_checker`.

Pipeline để tạo ảnh từ ảnh sử dụng Stable Diffusion XL với sự dẫn dắt của ControlNet.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các pipeline (chẳng hạn như tải xuống hoặc lưu, chạy trên một thiết bị cụ thể, v.v.)

Pipeline cũng kế thừa các phương thức nạp sau:
- [load_textual_inversion()](/docs/diffusers/v0.43.0/vi/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion) để nạp các embedding textual inversion
- [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights) để nạp trọng số LoRA
- [save_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights) để lưu trọng số LoRA
- [load_ip_adapter()](/docs/diffusers/v0.43.0/vi/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter) để nạp IP Adapters

#### __call__[[diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, strength: float = 0.8, num_inference_steps: int = 50, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, controlnet_conditioning_scale: float | list[float] = 0.8, guess_mode: bool = False, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, original_size: tuple[int, int] = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, aesthetic_score: float = 6.0, negative_aesthetic_score: float = 2.5, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py#L1079)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, `list[np.ndarray]`, : `list[list[torch.Tensor]]`, `list[list[np.ndarray]]` hoặc `list[list[PIL.Image.Image]]`): Ảnh ban đầu sẽ được sử dụng làm điểm khởi đầu cho quá trình tạo ảnh. Cũng có thể nhận các latent của ảnh dưới dạng `image`; nếu truyền trực tiếp các latent, chúng sẽ không được mã hóa lại.

control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, `list[np.ndarray]`, : `list[list[torch.Tensor]]`, `list[list[np.ndarray]]` hoặc `list[list[PIL.Image.Image]]`): Điều kiện đầu vào của ControlNet. ControlNet sử dụng điều kiện đầu vào này để tạo ra sự dẫn hướng cho Unet. Nếu kiểu được chỉ định là `torch.Tensor`, nó sẽ được truyền vào ControlNet nguyên vẹn. `PIL.Image.Image` cũng có thể được chấp nhận như một hình ảnh. Kích thước của hình ảnh đầu ra mặc định là kích thước của `image`. Nếu chiều cao và/hoặc chiều rộng được truyền vào, `image` sẽ được thay đổi kích thước theo chúng. Nếu nhiều ControlNet được chỉ định trong init, các hình ảnh phải được truyền dưới dạng một danh sách sao cho mỗi phần tử của danh sách có thể được batch đúng cách để làm đầu vào cho một controlnet đơn lẻ.

height (`int`, *tuỳ chọn*, mặc định là kích thước của control_image) : Chiều cao tính bằng pixel của hình ảnh được tạo ra. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) và các checkpoint không được tinh chỉnh đặc biệt cho độ phân giải thấp.

width (`int`, *tuỳ chọn*, mặc định là kích thước của control_image) : Độ rộng tính bằng pixel của hình ảnh được tạo ra. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) và các checkpoint không được tinh chỉnh đặc biệt cho độ phân giải thấp.

strength (`float`, *optional*, mặc định là 0.8) : Chỉ định mức độ biến đổi ảnh tham chiếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` được dùng làm điểm khởi đầu và càng thêm nhiều nhiễu khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khi `strength` là 1, nhiễu được thêm vào là tối đa và quá trình khử nhiễu chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Giá trị 1 về cơ bản sẽ bỏ qua `image`.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

guidance_scale (`float`, *optional*, mặc định là 7.5) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

eta (`float`, *optional*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho [schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể được sử dụng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

ip_adapter_image : (`PipelineImageInput`, *tùy chọn*): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.

ip_adapter_image_embeds (`list[torch.Tensor]`, *tùy chọn*) : Các embedding ảnh đã tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng `(batch_size, num_images, emb_dim)`. Nó phải chứa embedding ảnh âm nếu `do_classifier_free_guidance` được đặt thành `True`. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào `ip_adapter_image`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) thay vì một tuple thông thường hay không.

cross_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

controlnet_conditioning_scale (`float` hoặc `list[float]`, *không bắt buộc*, mặc định là 1.0) : Đầu ra của controlnet được nhân với `controlnet_conditioning_scale` trước khi được cộng vào phần dư trong unet gốc. Nếu nhiều ControlNet được chỉ định trong init, bạn có thể đặt scale tương ứng dưới dạng một danh sách.

guess_mode (`bool`, *tùy chọn*, mặc định là `False`) : Ở chế độ này, bộ mã hóa ControlNet sẽ cố gắng hết sức để nhận diện nội dung của hình ảnh đầu vào ngay cả khi bạn xóa tất cả các prompt. Khuyến nghị sử dụng `guidance_scale` trong khoảng từ 3.0 đến 5.0.

control_guidance_start (`float` hoặc `list[float]`, *tuỳ chọn*, mặc định là 0.0) : Tỷ lệ phần trăm tổng số bước mà tại đó controlnet bắt đầu áp dụng.

control_guidance_end (`float` hoặc `list[float]`, *tuỳ chọn*, mặc định là 1.0) : Tỷ lệ phần trăm tổng số bước mà tại đó controlnet ngừng áp dụng.

original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Nếu `original_size` không giống với `target_size`, hình ảnh sẽ có vẻ được giảm hoặc tăng mẫu. `original_size` mặc định là `(height, width)` nếu không được chỉ định. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : `crops_coords_top_left` có thể được dùng để tạo ra một hình ảnh trông như đã được "cắt" từ vị trí `crops_coords_top_left` trở xuống. Các hình ảnh đẹp, được căn giữa tốt thường đạt được bằng cách đặt `crops_coords_top_left` thành (0, 0). Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Trong hầu hết các trường hợp, `target_size` nên được đặt thành chiều cao và chiều rộng mong muốn của hình ảnh được tạo. Nếu không được chỉ định, giá trị mặc định sẽ là `(height, width)`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

negative_original_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải hình ảnh cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *optional*, mặc định là (0, 0)) : Để điều kiện âm quá trình tạo dựa trên tọa độ cắt cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *optional*, mặc định là (1024, 1024)) : Để điều kiện âm quá trình tạo dựa trên độ phân giải ảnh mục tiêu. Trong hầu hết các trường hợp, nó nên giống với `target_size`. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Để biết thêm thông tin, hãy tham khảo luồng issue này: https://github.com/huggingface/diffusers/issues/4208.

aesthetic_score (`float`, *tuỳ chọn*, mặc định là 6.0) : Được dùng để mô phỏng điểm thẩm mỹ của hình ảnh được tạo ra bằng cách ảnh hưởng đến điều kiện văn bản tích cực. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).

negative_aesthetic_score (`float`, *tuỳ chọn*, mặc định là 2.5) : Một phần của micro-conditioning trong SDXL như được giải thích trong mục 2.2 của [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Có thể được sử dụng để mô phỏng điểm thẩm mỹ của hình ảnh được tạo ra bằng cách ảnh hưởng đến điều kiện văn bản âm.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` hoặc `tuple`

`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` nếu `return_dict` là True, ngược lại là một `tuple` chứa các hình ảnh đầu ra.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> # pip install accelerate transformers safetensors diffusers

>>> import torch
>>> import numpy as np
>>> from PIL import Image

>>> from transformers import DPTFeatureExtractor, DPTForDepthEstimation
>>> from diffusers import ControlNetModel, StableDiffusionXLControlNetPAGImg2ImgPipeline, AutoencoderKL
>>> from diffusers.utils import load_image

>>> depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda")
>>> feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-hybrid-midas")
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-depth-sdxl-1.0-small",
...     variant="fp16",
...     use_safetensors="True",
...     torch_dtype=torch.float16,
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetPAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     variant="fp16",
...     use_safetensors=True,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()

>>> def get_depth_map(image):
...     image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
...     with torch.no_grad(), torch.autocast("cuda"):
...         depth_map = depth_estimator(image).predicted_depth

...     depth_map = torch.nn.functional.interpolate(
...         depth_map.unsqueeze(1),
...         size=(1024, 1024),
...         mode="bicubic",
...         align_corners=False,
...     )
...     depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_map = (depth_map - depth_min) / (depth_max - depth_min)
...     image = torch.cat([depth_map] * 3, dim=1)
...     image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
...     image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
...     return image

>>> prompt = "A robot, 4k photo"
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> depth_image = get_depth_map(image)

>>> images = pipe(
...     prompt,
...     image=image,
...     control_image=depth_image,
...     strength=0.99,
...     num_inference_steps=50,
...     controlnet_conditioning_scale=controlnet_conditioning_scale,
... ).images
>>> images[0].save(f"robot_cat.png")
```

#### encode_prompt[[diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, prompt_2: str | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, negative_prompt_2: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py#L296)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng cho cả hai text-encoder

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng cho cả hai text-encoder

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

lora_scale (`float`, *tuỳ chọn*) : Một hệ số lora sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

## StableDiffusion3PAGPipeline[[diffusers.StableDiffusion3PAGPipeline]]

#### diffusers.StableDiffusion3PAGPipeline[[diffusers.StableDiffusion3PAGPipeline]]

```python
diffusers.StableDiffusion3PAGPipeline(transformer: SD3Transformer2DModel, scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, text_encoder_2: CLIPTextModelWithProjection, tokenizer_2: CLIPTokenizer, text_encoder_3: T5EncoderModel, tokenizer_3: T5Tokenizer, pag_applied_layers: str | list[str] = 'blocks.1')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_3.py#L136)

**Tham số:**

transformer ([SD3Transformer2DModel](/docs/diffusers/v0.43.0/vi/api/models/sd3_transformer2d#diffusers.SD3Transformer2DModel)) : Kiến trúc Transformer điều kiện (MMDiT) để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một trình lập lịch được sử dụng kết hợp với `transformer` để khử nhiễu các latent ảnh đã mã hóa.

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder (`CLIPTextModelWithProjection`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14), với một lớp chiếu bổ sung được khởi tạo bằng một ma trận chéo có kích thước là `hidden_size`.

text_encoder_2 (`CLIPTextModelWithProjection`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), cụ thể là biến thể [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k).

text_encoder_3 (`T5EncoderModel`) : Bộ mã hóa văn bản đóng băng. Stable Diffusion 3 sử dụng [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), cụ thể là biến thể [t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl).

tokenizer (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_2 (`CLIPTokenizer`) : Tokenizer thứ hai thuộc lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_3 (`T5TokenizerFast`) : Tokenizer của lớp [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).

[Pipeline PAG](https://huggingface.co/docs/diffusers/main/en/using-diffusers/pag) cho việc tạo ảnh từ văn bản sử dụng Stable Diffusion 3.

#### __call__[[diffusers.StableDiffusion3PAGPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, prompt_3: str | list[str] | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, negative_prompt_3: str | list[str] | None = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 256, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_3.py#L684)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng thay thế

prompt_3 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_3` và `text_encoder_3`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng thay thế

height (`int`, *optional*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Giá trị mặc định là 1024 để đạt kết quả tốt nhất.

width (`int`, *optional*, mặc định là self.unet.config.sample_size * self.vae_scale_factor) : Độ rộng tính bằng pixel của hình ảnh được tạo ra. Mặc định được đặt là 1024 để đạt kết quả tốt nhất.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

guidance_scale (`float`, *optional*, mặc định là 7.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng thay thế

negative_prompt_3 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_3` và `text_encoder_3`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng thay thế

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.FloatTensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số của prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo ra từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` thay vì một tuple thông thường hay không.

joint_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

max_sequence_length (`int` mặc định là 256) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** `~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput` hoặc `tuple`

`~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput` nếu `return_dict` là True, ngược lại là một `tuple`. Khi trả về tuple, phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> image = pipe(prompt, guidance_scale=5.0, pag_scale=0.7).images[0]
>>> image.save("sd3_pag.png")
```

#### encode_prompt[[diffusers.StableDiffusion3PAGPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], prompt_2: str | list[str], prompt_3: str | list[str], device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, negative_prompt_3: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, clip_skip: int | None = None, max_sequence_length: int = 256, lora_scale: float | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_3.py#L335)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng trong tất cả các text-encoder

prompt_3 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_3` và `text_encoder_3`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng trong tất cả các text-encoder

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng trong tất cả các text-encoder.

negative_prompt_3 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_3` và `text_encoder_3`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng trong tất cả các text-encoder.

prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số của prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo ra từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

lora_scale (`float`, *tuỳ chọn*) : Một hệ số lora sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

## StableDiffusion3PAGImg2ImgPipeline[[diffusers.StableDiffusion3PAGImg2ImgPipeline]]

#### diffusers.StableDiffusion3PAGImg2ImgPipeline[[diffusers.StableDiffusion3PAGImg2ImgPipeline]]

```python
diffusers.StableDiffusion3PAGImg2ImgPipeline(transformer: SD3Transformer2DModel, scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, text_encoder_2: CLIPTextModelWithProjection, tokenizer_2: CLIPTokenizer, text_encoder_3: T5EncoderModel, tokenizer_3: T5Tokenizer, pag_applied_layers: str | list[str] = 'blocks.1')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py#L152)

**Tham số:**

transformer ([SD3Transformer2DModel](/docs/diffusers/v0.43.0/vi/api/models/sd3_transformer2d#diffusers.SD3Transformer2DModel)) : Kiến trúc Transformer điều kiện (MMDiT) để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một trình lập lịch được sử dụng kết hợp với `transformer` để khử nhiễu các latent ảnh đã mã hóa.

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/vi/api/models/autoencoderkl#diffusers.AutoencoderKL)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh sang và từ các biểu diễn ẩn.

text_encoder (`CLIPTextModelWithProjection`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14), với một lớp chiếu bổ sung được khởi tạo bằng một ma trận chéo có kích thước là `hidden_size`.

text_encoder_2 (`CLIPTextModelWithProjection`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), cụ thể là biến thể [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k).

text_encoder_3 (`T5EncoderModel`) : Bộ mã hóa văn bản đóng băng. Stable Diffusion 3 sử dụng [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), cụ thể là biến thể [t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl).

tokenizer (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_2 (`CLIPTokenizer`) : Tokenizer thứ hai thuộc lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).

tokenizer_3 (`T5TokenizerFast`) : Tokenizer của lớp [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).

[Pipeline PAG](https://huggingface.co/docs/diffusers/main/en/using-diffusers/pag) cho việc tạo ảnh từ ảnh sử dụng Stable Diffusion 3.

#### __call__[[diffusers.StableDiffusion3PAGImg2ImgPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, prompt_3: str | list[str] | None = None, height: int | None = None, width: int | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, strength: float = 0.6, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 7.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, negative_prompt_3: str | list[str] | None = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 256, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py#L735)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng thay thế

prompt_3 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_3` và `text_encoder_3`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng thay thế

height (`int`, *tuỳ chọn*, mặc định là `self.default_sample_size * self.vae_scale_factor`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Mặc định được đặt là 1024 để đạt kết quả tốt nhất.

width (`int`, *tuỳ chọn*, mặc định là `self.default_sample_size * self.vae_scale_factor`) : Độ rộng tính bằng pixel của hình ảnh được tạo ra. Mặc định được đặt là 1024 để đạt kết quả tốt nhất.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`) : `Image`, mảng numpy hoặc tensor đại diện cho một lô ảnh (image batch) được sử dụng làm điểm khởi đầu. Đối với cả mảng numpy và tensor pytorch, khoảng giá trị mong đợi nằm trong `[0, 1]` Nếu là tensor hoặc danh sách các tensor, hình dạng mong đợi nên là `(B, C, H, W)` hoặc `(C, H, W)`. Nếu là mảng numpy hoặc danh sách các mảng, hình dạng mong đợi nên là `(B, H, W, C)` hoặc `(H, W, C)` Nó cũng có thể nhận các image latents dưới dạng `image`, nhưng nếu truyền trực tiếp latents thì chúng sẽ không được mã hóa lại.

strength (`float`, *optional*, mặc định là 0.8) : Chỉ định mức độ biến đổi ảnh tham chiếu `image`. Giá trị phải nằm trong khoảng từ 0 đến 1. `image` được dùng làm điểm khởi đầu và càng thêm nhiều nhiễu khi `strength` càng cao. Số bước khử nhiễu phụ thuộc vào lượng nhiễu ban đầu được thêm vào. Khi `strength` là 1, nhiễu được thêm vào là tối đa và quá trình khử nhiễu chạy đủ số lần lặp được chỉ định trong `num_inference_steps`. Giá trị 1 về cơ bản sẽ bỏ qua `image`.

num_inference_steps (`int`, *optional*, mặc định là 50) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

guidance_scale (`float`, *optional*, mặc định là 7.0) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng thay thế

negative_prompt_3 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_3` và `text_encoder_3`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng thay thế

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.FloatTensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số của prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo ra từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` thay vì một tuple thông thường hay không.

joint_attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

callback_on_step_end (`Callable`, *tùy chọn*) : Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

max_sequence_length (`int` mặc định là 256) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** `~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput` hoặc `tuple`

`~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput` nếu `return_dict` là True, ngược lại là một `tuple`. Khi trả về tuple, phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import StableDiffusion3PAGImg2ImgPipeline
>>> from diffusers.utils import load_image

>>> pipe = StableDiffusion3PAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
>>> init_image = load_image(url).convert("RGB")
>>> image = pipe(prompt, image=init_image, guidance_scale=5.0, pag_scale=0.7).images[0]
```

#### encode_prompt[[diffusers.StableDiffusion3PAGImg2ImgPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], prompt_2: str | list[str], prompt_3: str | list[str], device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, negative_prompt_3: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, clip_skip: int | None = None, max_sequence_length: int = 256, lora_scale: float | None = None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py#L351)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng trong tất cả các text-encoder

prompt_3 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_3` và `text_encoder_3`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng trong tất cả các text-encoder

device : (`torch.device`): thiết bị torch

num_images_per_prompt (`int`) : số lượng hình ảnh cần được tạo cho mỗi prompt

do_classifier_free_guidance (`bool`) : có sử dụng classifier free guidance hay không

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng trong tất cả các text-encoder.

negative_prompt_3 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_3` và `text_encoder_3`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng trong tất cả các text-encoder.

prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số của prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo ra từ đối số đầu vào `prompt`.

negative_pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

clip_skip (`int`, *optional*) : Số lượng lớp cần bỏ qua từ CLIP khi tính toán các prompt embeddings. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối cùng sẽ được sử dụng để tính toán các prompt embeddings.

lora_scale (`float`, *tuỳ chọn*) : Một hệ số lora sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.

## PixArtSigmaPAGPipeline[[diffusers.PixArtSigmaPAGPipeline]]

#### diffusers.PixArtSigmaPAGPipeline[[diffusers.PixArtSigmaPAGPipeline]]

```python
diffusers.PixArtSigmaPAGPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, vae: AutoencoderKL, transformer: PixArtTransformer2DModel, scheduler: KarrasDiffusionSchedulers, pag_applied_layers: str | list[str] = 'blocks.1')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py#L144)

[Pipeline PAG](https://huggingface.co/docs/diffusers/main/en/using-diffusers/pag) cho việc tạo ảnh từ văn bản sử dụng PixArt-Sigma.

#### __call__[[diffusers.PixArtSigmaPAGPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 20, timesteps: list[int] = None, sigmas: list[float] = None, guidance_scale: float = 4.5, num_images_per_prompt: int | None = 1, height: int | None = None, width: int | None = None, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, clean_caption: bool = True, use_resolution_binning: bool = True, max_sequence_length: int = 300, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py#L574)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `guidance_scale` nhỏ hơn `1`).

num_inference_steps (`int`, *optional*, mặc định là 100) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, với cái giá là suy luận chậm hơn.

timesteps (`list[int]`, *optional*) : Các bước thời gian (timesteps) tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch (scheduler) hỗ trợ tham số `timesteps` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

guidance_scale (`float`, *optional*, mặc định là 4.5) : Thang độ dẫn hướng như được định nghĩa trong [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` được định nghĩa là `w` của phương trình 2. trong [Imagen Paper](https://huggingface.co/papers/2205.11487). Thang độ dẫn hướng được kích hoạt bằng cách đặt `guidance_scale > 1`. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với `prompt` văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn.

num_images_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

height (`int`, *tuỳ chọn*, mặc định là self.unet.config.sample_size) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel.

width (`int`, *tuỳ chọn*, mặc định là self.unet.config.sample_size) : Độ rộng tính bằng pixel của hình ảnh được tạo ra.

eta (`float`, *optional*, mặc định là 0.0) : Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho [schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddim#diffusers.DDIMScheduler), sẽ bị bỏ qua với các trình lập lịch khác.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một hoặc một danh sách [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu đã được tạo trước, được lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể được sử dụng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo ra bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản.

negative_prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

negative_prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản âm.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo. Chọn giữa [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `~pipelines.stable_diffusion.IFPipelineOutput` thay vì một tuple thông thường hay không.

callback (`Callable`, *tùy chọn*) : Một hàm sẽ được gọi mỗi `callback_steps` bước trong quá trình suy luận. Hàm sẽ được gọi với các đối số sau: `callback(step: int, timestep: int, latents: torch.Tensor)`.

callback_steps (`int`, *optional*, mặc định là 1) : Tần suất mà hàm `callback` sẽ được gọi. Nếu không được chỉ định, callback sẽ được gọi ở mỗi bước.

clean_caption (`bool`, *tùy chọn*, mặc định là `True`) : Có dọn dẹp chú thích trước khi tạo embeddings hay không. Yêu cầu `beautifulsoup4` và `ftfy` phải được cài đặt. Nếu các phụ thuộc này không được cài đặt, embeddings sẽ được tạo từ prompt thô.

use_resolution_binning (`bool` mặc định là `True`) : Nếu được đặt thành `True`, chiều cao và chiều rộng yêu cầu sẽ được ánh xạ trước tiên đến các độ phân giải gần nhất bằng cách sử dụng `ASPECT_RATIO_1024_BIN`. Sau khi các latents được tạo ra được giải mã thành hình ảnh, chúng sẽ được thay đổi kích thước trở lại độ phân giải yêu cầu. Hữu ích cho việc tạo ra các hình ảnh không vuông.

max_sequence_length (`int` mặc định là 300) : Độ dài tối đa của chuỗi để sử dụng với `prompt`.

pag_scale (`float`, *optional*, mặc định là 3.0) : Hệ số tỷ lệ cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, hướng dẫn chú ý bị nhiễu sẽ không được sử dụng.

pag_adaptive_scale (`float`, *optional*, mặc định là 0.0) : Hệ số tỷ lệ thích ứng cho hướng dẫn chú ý bị nhiễu. Nếu được đặt thành 0.0, `pag_scale` sẽ được sử dụng.

**Trả về:** [ImagePipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) hoặc `tuple`

Nếu `return_dict` là `True`, [ImagePipelineOutput](/docs/diffusers/v0.43.0/vi/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã được tạo

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:
```py
>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.14"],
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "A small cactus with a happy face in the Sahara desert"
>>> image = pipe(prompt, pag_scale=4.0, guidance_scale=1.0).images[0]
```

#### encode_prompt[[diffusers.PixArtSigmaPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, clean_caption: bool = False, max_sequence_length: int = 300, **kwargs)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py#L190)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : prompt cần được mã hóa

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt không dùng để hướng dẫn tạo ảnh. Nếu không được định nghĩa, cần truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bỏ qua nếu `guidance_scale` nhỏ hơn `1`). Đối với PixArt-Alpha, giá trị này nên là "".

do_classifier_free_guidance (`bool`, *tùy chọn*, mặc định là `True`) : có sử dụng classifier free guidance hay không

num_images_per_prompt (`int`, *tùy chọn*, mặc định là 1) : số lượng hình ảnh cần được tạo cho mỗi prompt

device : (`torch.device`, *tùy chọn*): thiết bị torch để đặt các embedding kết quả lên

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.Tensor`, *tuỳ chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Đối với PixArt-Alpha, đây nên là các vector nhúng của chuỗi "".

clean_caption (`bool`, mặc định là `False`) : Nếu `True`, hàm sẽ tiền xử lý và làm sạch chú thích được cung cấp trước khi mã hóa.

max_sequence_length (`int`, mặc định là 300) : Độ dài tối đa của chuỗi được sử dụng cho prompt.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

