# Phân giải siêu cao

  

Mô hình khuếch tán Stable Diffusion upscaler được tạo ra bởi các nhà nghiên cứu và kỹ sư từ [CompVis](https://github.com/CompVis), [Stability AI](https://stability.ai/) và [LAION](https://laion.ai/). Nó được sử dụng để tăng độ phân giải của hình ảnh đầu vào lên 4 lần.

> [!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!

## StableDiffusionUpscalePipeline[[diffusers.StableDiffusionUpscalePipeline]]

#### diffusers.StableDiffusionUpscalePipeline[[diffusers.StableDiffusionUpscalePipeline]]

```python
diffusers.StableDiffusionUpscalePipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, low_res_scheduler: DDPMScheduler, scheduler: KarrasDiffusionSchedulers, safety_checker: typing.Any | None = None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = None, watermarker: typing.Any | None = None, max_noise_level: int = 350)
```

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

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

low_res_scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/vi/api/schedulers/overview#diffusers.SchedulerMixin)) : Một scheduler được sử dụng để thêm nhiễu ban đầu vào ảnh điều kiện có độ phân giải thấp. Nó phải là một instance của [DDPMScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/ddpm#diffusers.DDPMScheduler).

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 cho siêu phân giải hình ảnh có hướng dẫn bằng văn bản sử dụng Stable Diffusion 2.

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`

#### __call__[[diffusers.StableDiffusionUpscalePipeline.__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, noise_level: int = 20, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int = None)
```

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

**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` hoặc tensor đại diện cho một lô ảnh cần được phóng to.

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

noise_level (`int`, *optional*, mặc định là 20) : Lượng nhiễu cần thêm vào ảnh đầu vào đã được phóng to. Giá trị phải nằm trong khoảng `[0, max_noise_level]` trong đó `max_noise_level` được định nghĩa bởi trình lập lịch. `noise_level` cao hơn sẽ thêm nhiều nhiễu hơn vào đầu vào, làm tăng sự biến đổi nhưng giảm độ trung thực so với ảnh nguồn.

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

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.

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.

**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 requests
>>> from PIL import Image
>>> from io import BytesIO
>>> from diffusers import StableDiffusionUpscalePipeline
>>> import torch

>>> # load model and scheduler
>>> model_id = "stabilityai/stable-diffusion-x4-upscaler"
>>> pipeline = StableDiffusionUpscalePipeline.from_pretrained(
...     model_id, variant="fp16", torch_dtype=torch.float16
... )
>>> pipeline = pipeline.to("cuda")

>>> # let's download an  image
>>> url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
>>> response = requests.get(url)
>>> low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> low_res_img = low_res_img.resize((128, 128))
>>> prompt = "a white cat"

>>> upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
>>> upscaled_image.save("upsampled_cat.png")
```

#### enable_attention_slicing[[diffusers.StableDiffusionUpscalePipeline.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.StableDiffusionUpscalePipeline.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.StableDiffusionUpscalePipeline.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.StableDiffusionUpscalePipeline.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.StableDiffusionUpscalePipeline.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/stable_diffusion/pipeline_stable_diffusion_upscale.py#L217)

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

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

