# Biến thể hình ảnh

Mô hình Stable Diffusion cũng có thể tạo ra các biến thể từ một hình ảnh đầu vào. Nó sử dụng một phiên bản tinh chỉnh của mô hình Stable Diffusion do [Justin Pinkney](https://www.justinpinkney.com/) từ [Lambda](https://lambdalabs.com/) phát triển.

Mã nguồn gốc có thể được tìm thấy tại [LambdaLabsML/lambda-diffusers](https://github.com/LambdaLabsML/lambda-diffusers#stable-diffusion-image-variations) và các checkpoint chính thức bổ sung cho image variation có thể được tìm thấy tại [lambdalabs/sd-image-variations-diffusers](https://huggingface.co/lambdalabs/sd-image-variations-diffusers).

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

## StableDiffusionImageVariationPipeline[[diffusers.StableDiffusionImageVariationPipeline]]

#### diffusers.StableDiffusionImageVariationPipeline[[diffusers.StableDiffusionImageVariationPipeline]]

```python
diffusers.StableDiffusionImageVariationPipeline(vae: AutoencoderKL, image_encoder: CLIPVisionModelWithProjection, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, requires_safety_checker: bool = True)
```

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

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

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

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 ra các biến thể hình ảnh từ một hình ảnh đầu vào 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.).

#### __call__[[diffusers.StableDiffusionImageVariationPipeline.__call__]]

```python
__call__(image: typing.Union[PIL.Image.Image, list[PIL.Image.Image], torch.Tensor], height: int | None = None, width: int | None = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, 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, 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_image_variation.py#L259)

**Tham số:**

image (`PIL.Image.Image` hoặc `list[PIL.Image.Image]` hoặc `torch.Tensor`) : Ảnh hoặc các ảnh để hướng dẫn tạo ảnh. Nếu bạn cung cấp một tensor, nó cần phải tương thích với [`CLIPImageProcessor`](https://huggingface.co/lambdalabs/sd-image-variations-diffusers/blob/main/feature_extractor/preprocessor_config.json).

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, đổ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`.

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.

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 đã 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
from diffusers import StableDiffusionImageVariationPipeline
from PIL import Image
from io import BytesIO
import requests

pipe = StableDiffusionImageVariationPipeline.from_pretrained(
    "lambdalabs/sd-image-variations-diffusers", revision="v2.0"
)
pipe = pipe.to("cuda")

url = "https://lh3.googleusercontent.com/y-iFOHfLTwkuQSUegpwDdgKmOjRSTvPxat63dQLB25xkTs4lhIbRUFeNBWZzYf370g=s1200"

response = requests.get(url)
image = Image.open(BytesIO(response.content)).convert("RGB")

out = pipe(image, num_images_per_prompt=3, guidance_scale=15)
out["images"][0].save("result.jpg")
```

#### enable_attention_slicing[[diffusers.StableDiffusionImageVariationPipeline.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.StableDiffusionImageVariationPipeline.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.StableDiffusionImageVariationPipeline.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.StableDiffusionImageVariationPipeline.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/).

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

