# Bộ tăng độ phân giải tiềm ẩn

Mô hình latent upscaler của Stable Diffusion được tạo ra bởi [Katherine Crowson](https://github.com/crowsonkb/k-diffusion) hợp tác với [Stability AI](https://stability.ai/). Nó được sử dụng để tăng độ phân giải của ảnh đầu ra lên gấp 2 (xem [notebook](https://colab.research.google.com/drive/1o1qYJcFeywzCIdkfKJy7cTpgZTCM2EI4) demo này để xem minh họa về cài đặt gốc).

> [!TIP]
> Hãy chắc chắn xem qua phần [Mẹo](overview#tips) của Stable Diffusion để tìm hiểu cách khám phá sự đánh đổi giữa tốc độ và chất lượng của scheduler, cũng như cách tái sử dụng các thành phần pipeline một cách hiệu quả!
>
> Nếu bạn quan tâm đến việc sử dụng một trong các checkpoint chính thức cho một tác vụ, hãy khám phá các tổ chức [CompVis](https://huggingface.co/CompVis) và [Stability AI](https://huggingface.co/stabilityai) trên Hub!

## StableDiffusionLatentUpscalePipeline[[diffusers.StableDiffusionLatentUpscalePipeline]]

#### diffusers.StableDiffusionLatentUpscalePipeline[[diffusers.StableDiffusionLatentUpscalePipeline]]

```python
diffusers.StableDiffusionLatentUpscalePipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: EulerDiscreteScheduler)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py#L84)

**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 [EulerDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/euler#diffusers.EulerDiscreteScheduler) được sử dụng kết hợp với `unet` để khử nhiễu các latents của ảnh đã mã hóa.

Pipeline để tăng độ phân giải của ảnh đầu ra từ Stable Diffusion lên gấp 2 lần.

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:
- [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`

#### __call__[[diffusers.StableDiffusionLatentUpscalePipeline.__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, num_inference_steps: int = 75, guidance_scale: float = 9.0, negative_prompt: str | list[str] | None = None, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py#L396)

**Tham số:**

prompt (`str` hoặc `list[str]`) : Prompt hoặc các prompt để hướng dẫn việc tăng độ phân giải ảnh.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, hoặc `list[np.ndarray]`) : `Image` hoặc tensor đại diện cho một lô ảnh cần được tăng kích thước. Nếu là tensor, nó có thể là đầu ra latent từ một mô hình Stable Diffusion hoặc một tensor ảnh trong khoảng `[-1, 1]`. Nó được coi là `latent` nếu `image.shape[1]` là `4`; ngược lại, nó được coi là biểu diễn ảnh và được mã hóa bằng bộ mã hóa `vae` của pipeline nà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 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`).

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`.

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 (`Callable`, *tùy chọn*) : Một hàm được gọi mỗi `callback_steps` bước trong quá trình suy luận. Hàm này đượ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 gọi hàm `callback`. Nếu không được chỉ định, callback sẽ được gọi ở mỗi bước.

**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 đã được tạo.

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

Ví dụ:
```py
>>> from diffusers import StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline
>>> import torch

>>> pipeline = StableDiffusionPipeline.from_pretrained(
...     "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16
... )
>>> pipeline.to("cuda")

>>> model_id = "stabilityai/sd-x2-latent-upscaler"
>>> upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
>>> upscaler.to("cuda")

>>> prompt = "a photo of an astronaut high resolution, unreal engine, ultra realistic"
>>> generator = torch.manual_seed(33)

>>> low_res_latents = pipeline(prompt, generator=generator, output_type="latent").images

>>> with torch.no_grad():
...     image = pipeline.decode_latents(low_res_latents)
>>> image = pipeline.numpy_to_pil(image)[0]

>>> image.save("../images/a1.png")

>>> upscaled_image = upscaler(
...     prompt=prompt,
...     image=low_res_latents,
...     num_inference_steps=20,
...     guidance_scale=0,
...     generator=generator,
... ).images[0]

>>> upscaled_image.save("../images/a2.png")
```

#### enable_sequential_cpu_offload[[diffusers.StableDiffusionLatentUpscalePipeline.enable_sequential_cpu_offload]]

```python
enable_sequential_cpu_offload(gpu_id: int | None = None, device: typing.Union[torch.device, str] = None)
```

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

**Tham số:**

gpu_id (`int`, *optional*) : ID của bộ tăng tốc sẽ được sử dụng trong suy luận. Nếu không được chỉ định, giá trị mặc định sẽ là 0.

device (`torch.Device` hoặc `str`, *tuỳ chọn*, mặc định là None) : Loại thiết bị PyTorch của bộ tăng tốc sẽ được sử dụng trong suy luận. Nếu không được chỉ định, hệ thống sẽ tự động phát hiện và sử dụng bộ tăng tốc khả dụng.

Tải xuống tất cả các mô hình xuống CPU bằng 🤗 Accelerate, giảm đáng kể lượng bộ nhớ sử dụng. Khi được gọi, các state dict của tất cả các thành phần `torch.nn.Module` (ngoại trừ những thành phần trong `self._exclude_from_cpu_offload`) sẽ được lưu xuống CPU, sau đó được chuyển đến `torch.device('meta')` và chỉ được tải lên accelerator khi phương thức `forward` của submodule cụ thể đó được gọi. Việc offload diễn ra ở cấp độ submodule. Tiết kiệm bộ nhớ cao hơn so với `enable_model_cpu_offload`, nhưng hiệu suất thấp hơn.

#### enable_attention_slicing[[diffusers.StableDiffusionLatentUpscalePipeline.enable_attention_slicing]]

```python
enable_attention_slicing(slice_size: str | int = 'auto')
```

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

**Tham số:**

slice_size (`str` hoặc `int`, *tuỳ chọn*, mặc định là `"auto"`) : Khi là `"auto"`, sẽ chia đôi đầu vào của các attention head, do đó attention sẽ được tính trong hai bước. Nếu là `"max"`, lượng bộ nhớ tối đa sẽ được tiết kiệm bằng cách chỉ chạy một lát một lúc. Nếu cung cấp một số, sẽ sử dụng nhiều lát bằng `attention_head_dim // slice_size`. Trong trường hợp này, `attention_head_dim` phải là bội số của `slice_size`.

Bật tính toán chú ý dạng lát cắt. Khi tùy chọn này được bật, module chú ý sẽ chia tensor đầu vào thành các lát cắt để tính toán chú ý qua nhiều bước. Với nhiều hơn một đầu chú ý, phép tính được thực hiện tuần tự trên từng đầu. Điều này hữu ích để tiết kiệm một phần bộ nhớ, đổi lại là sự giảm tốc độ nhỏ.

> [!WARNING] > ⚠️ Không bật attention slicing nếu bạn đã đang sử dụng `scaled_dot_product_attention` (SDPA)
từ PyTorch > 2.0 hoặc xFormers. Các phép tính attention này đã rất tiết kiệm bộ nhớ nên bạn không cần bật > chức năng này. Nếu bạn bật attention slicing với SDPA hoặc xFormers, nó có thể dẫn đến việc chậm đi đáng kể!

Ví dụ:

```py
>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     dtype=torch.float16,
...     use_safetensors=True,
... )

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

#### disable_attention_slicing[[diffusers.StableDiffusionLatentUpscalePipeline.disable_attention_slicing]]

```python
disable_attention_slicing()
```

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

Tắt tính toán chú ý dạng lát cắt. Nếu `enable_attention_slicing` đã được gọi trước đó, chú ý sẽ được tính toán trong một bước duy nhất.

#### enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionLatentUpscalePipeline.enable_xformers_memory_efficient_attention]]

```python
enable_xformers_memory_efficient_attention(attention_op: typing.Optional[typing.Callable] = None)
```

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

**Tham số:**

attention_op (`Callable`, *tùy chọn*) : Ghi đè toán tử mặc định `None` để sử dụng làm đối số `op` cho hàm [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) của xFormers.

Bật chú ý tiết kiệm bộ nhớ từ [xFormers](https://facebookresearch.github.io/xformers/). Khi tùy chọn này được bật, bạn nên quan sát thấy mức sử dụng bộ nhớ GPU thấp hơn và có thể tăng tốc trong quá trình suy luận. Việc tăng tốc trong quá trình huấn luyện không được đảm bảo.

> [!WARNING] > ⚠️ Khi cả memory efficient attention và sliced attention đều được bật, memory efficient
attention có > ưu tiên.

Ví dụ:

```py
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
```

#### disable_xformers_memory_efficient_attention[[diffusers.StableDiffusionLatentUpscalePipeline.disable_xformers_memory_efficient_attention]]

```python
disable_xformers_memory_efficient_attention()
```

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

Tắt chú ý tiết kiệm bộ nhớ từ [xFormers](https://facebookresearch.github.io/xformers/).

#### encode_prompt[[diffusers.StableDiffusionLatentUpscalePipeline.encode_prompt]]

```python
encode_prompt(prompt, device, do_classifier_free_guidance, negative_prompt = 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py#L166)

**Tham số:**

prompt (`str` hoặc `list(int)`) : prompt cần được mã hóa

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

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

negative_prompt (`str` hoặc `list[str]`) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh. Bỏ qua khi không sử dụng guidance (tức là 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`.

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.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`.

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

## StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

#### diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

```python
diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray, nsfw_content_detected: list[bool] | None)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion/pipeline_output.py#L10)

**Tham số:**

images (`list[PIL.Image.Image]` hoặc `np.ndarray`) : danh sách các hình ảnh PIL đã khử nhiễu có độ dài `batch_size` hoặc mảng NumPy có hình dạng `(batch_size, height, width, num_channels)`.

nsfw_content_detected (`list[bool]`) : danh sách cho biết hình ảnh tương ứng có chứa nội dung "không an toàn cho công việc" (nsfw) hay không, hoặc `None` nếu không thể thực hiện kiểm tra an toàn.

Lớp đầu ra cho các pipeline Stable Diffusion.

