AdithyaSK HF Staff commited on
Commit
991dcfc
·
verified ·
1 Parent(s): 1451559

Stage Harbor release files 95001-95500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/inpaint.md +63 -0
  2. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/kandinsky.md +759 -0
  3. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/loading.md +436 -0
  4. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/loading_adapters.md +346 -0
  5. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/other-formats.md +188 -0
  6. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/push_to_hub.md +177 -0
  7. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/schedulers.md +326 -0
  8. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/sdxl_turbo.md +114 -0
  9. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/shap-e.md +189 -0
  10. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/stable_diffusion_jax_how_to.md +264 -0
  11. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/svd.md +121 -0
  12. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/textual_inversion_inference.md +80 -0
  13. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/unconditional_image_generation.md +57 -0
  14. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/weighted_prompts.md +115 -0
  15. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/write_own_pipeline.md +281 -0
  16. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/_toctree.yml +10 -0
  17. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/index.md +48 -0
  18. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/installation.md +153 -0
  19. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/quicktour.md +302 -0
  20. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/stable_diffusion.md +132 -0
  21. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/_toctree.yml +164 -0
  22. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/community_projects.md +97 -0
  23. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/conceptual/contribution.md +485 -0
  24. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/conceptual/ethical_guidelines.md +56 -0
  25. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/conceptual/evaluation.md +546 -0
  26. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/conceptual/philosophy.md +104 -0
  27. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/hybrid_inference/api_reference.md +9 -0
  28. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/hybrid_inference/overview.md +55 -0
  29. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/hybrid_inference/vae_encode.md +184 -0
  30. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/index.md +101 -0
  31. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/installation.md +143 -0
  32. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/auto_pipeline_blocks.md +156 -0
  33. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/components_manager.md +188 -0
  34. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/loop_sequential_pipeline_blocks.md +93 -0
  35. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/modular_diffusers_states.md +74 -0
  36. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/modular_pipeline.md +358 -0
  37. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/overview.md +38 -0
  38. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/pipeline_block.md +114 -0
  39. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/quickstart.md +346 -0
  40. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/sequential_pipeline_blocks.md +112 -0
  41. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/cache.md +67 -0
  42. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/coreml.md +160 -0
  43. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/deepcache.md +59 -0
  44. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/fp16.md +304 -0
  45. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/habana.md +28 -0
  46. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/memory.md +581 -0
  47. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/mps.md +79 -0
  48. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/neuron.md +56 -0
  49. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/onnx.md +79 -0
  50. tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/open_vino.md +77 -0
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/inpaint.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Text-guided 이미지 인페인팅(inpainting)
14
+
15
+ [[open-in-colab]]
16
+
17
+ [`StableDiffusionInpaintPipeline`]은 마스크와 텍스트 프롬프트를 제공하여 이미지의 특정 부분을 편집할 수 있도록 합니다. 이 기능은 인페인팅 작업을 위해 특별히 훈련된 [`stable-diffusion-v1-5/stable-diffusion-inpainting`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-inpainting)과 같은 Stable Diffusion 버전을 사용합니다.
18
+
19
+ 먼저 [`StableDiffusionInpaintPipeline`] 인스턴스를 불러옵니다:
20
+
21
+ ```python
22
+ import PIL
23
+ import requests
24
+ import torch
25
+ from io import BytesIO
26
+
27
+ from diffusers import StableDiffusionInpaintPipeline
28
+
29
+ pipeline = StableDiffusionInpaintPipeline.from_pretrained(
30
+ "stable-diffusion-v1-5/stable-diffusion-inpainting",
31
+ torch_dtype=torch.float16,
32
+ )
33
+ pipeline = pipeline.to("cuda")
34
+ ```
35
+
36
+ 나중에 교체할 강아지 이미지와 마스크를 다운로드하세요:
37
+
38
+ ```python
39
+ def download_image(url):
40
+ response = requests.get(url)
41
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
42
+
43
+
44
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
45
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
46
+
47
+ init_image = download_image(img_url).resize((512, 512))
48
+ mask_image = download_image(mask_url).resize((512, 512))
49
+ ```
50
+
51
+ 이제 마스크를 다른 것으로 교체하라는 프롬프트를 만들 수 있습니다:
52
+
53
+ ```python
54
+ prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
55
+ image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
56
+ ```
57
+
58
+ `image` | `mask_image` | `prompt` | output |
59
+ :-------------------------:|:-------------------------:|:-------------------------:|-------------------------:|
60
+ <img src="https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" alt="drawing" width="250"/> | <img src="https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" alt="drawing" width="250"/> | ***Face of a yellow cat, high resolution, sitting on a park bench*** | <img src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/in_paint/yellow_cat_sitting_on_a_park_bench.png" alt="drawing" width="250"/> |
61
+
62
+ > [!WARNING]
63
+ > 이전의 실험적인 인페인팅 구현에서는 품질이 낮은 다른 프로세스를 사용했습니다. 이전 버전과의 호환성을 보장하기 위해 새 모델이 포함되지 않은 사전학습된 파이프라인을 불러오면 이전 인페인팅 방법이 계속 적용됩니다.
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/kandinsky.md ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Kandinsky
14
+
15
+ [[open-in-colab]]
16
+
17
+ Kandinsky 모델은 일련의 다국어 text-to-image 생성 모델입니다. Kandinsky 2.0 모델은 두 개의 다국어 텍스트 인코더를 사용하고 그 결과를 연결해 UNet에 사용됩니다.
18
+
19
+ [Kandinsky 2.1](../api/pipelines/kandinsky)은 텍스트와 이미지 임베딩 간의 매핑을 생성하는 image prior 모델([`CLIP`](https://huggingface.co/docs/transformers/model_doc/clip))을 포함하도록 아키텍처를 변경했습니다. 이 매핑은 더 나은 text-image alignment를 제공하며, 학습 중에 텍스트 임베딩과 함께 사용되어 더 높은 품질의 결과를 가져옵니다. 마지막으로, Kandinsky 2.1은 spatial conditional 정규화 레이어를 추가하여 사실감을 높여주는 [Modulating Quantized Vectors (MoVQ)](https://huggingface.co/papers/2209.09002) 디코더를 사용하여 latents를 이미지로 디코딩합니다.
20
+
21
+ [Kandinsky 2.2](../api/pipelines/kandinsky_v22)는 image prior 모델의 이미지 인코더를 더 큰 CLIP-ViT-G 모델로 교체하여 품질을 개선함으로써 이전 모델을 개선했습니다. 또한 image prior 모델은 해상도와 종횡비가 다른 이미지로 재훈련되어 더 높은 해상도의 이미지와 다양한 이미지 크기를 생성합니다.
22
+
23
+ [Kandinsky 3](../api/pipelines/kandinsky3)는 아키텍처를 단순화하고 prior 모델과 diffusion 모델을 포함하는 2단계 생성 프로세스에서 벗어나고 있습니다. 대신, Kandinsky 3는 [Flan-UL2](https://huggingface.co/google/flan-ul2)를 사용하여 텍스트를 인코딩하고, [BigGan-deep](https://hf.co/papers/1809.11096) 블록이 포함된 UNet을 사용하며, [Sber-MoVQGAN](https://github.com/ai-forever/MoVQGAN)을 사용하여 latents를 이미지로 디코딩합니다. 텍스트 이해와 생성된 이미지 품질은 주로 더 큰 텍스트 인코더와 UNet을 사용함으로써 달성됩니다.
24
+
25
+ 이 가이드에서는 text-to-image, image-to-image, 인페인팅, 보간 등을 위해 Kandinsky 모델을 사용하는 방법을 설명합니다.
26
+
27
+ 시작하기 전에 다음 라이브러리가 설치되어 있는지 확인하세요:
28
+
29
+ ```py
30
+ # Colab에서 필요한 라이브러리를 설치하기 위해 주석을 제외하세요
31
+ #!pip install -q diffusers transformers accelerate
32
+ ```
33
+
34
+ > [!WARNING]
35
+ > Kandinsky 2.1과 2.2의 사용법은 매우 유사합니다! 유일한 차이점은 Kandinsky 2.2는 latents를 디코딩할 때 `프롬프트`를 입력으로 받지 않는다는 것입니다. 대신, Kandinsky 2.2는 디코딩 중에는 `image_embeds`만 받아들입니다.
36
+ >
37
+ > <br>
38
+ >
39
+ > Kandinsky 3는 더 간결한 아키텍처를 가지고 있으며 prior 모델이 필요하지 않습니다. 즉, [Stable Diffusion XL](sdxl)과 같은 다른 diffusion 모델과 사용법이 동일합니다.
40
+
41
+ ## Text-to-image
42
+
43
+ 모든 작업에 Kandinsky 모델을 사용하려면 항상 프롬프트를 인코딩하고 이미지 임베딩을 생성하는 prior 파이프라인을 설정하는 것부터 시작해야 합니다. 이전 파이프라인은 negative 프롬프트 `""`에 해당하는 `negative_image_embeds`도 생성합니다. 더 나은 결과를 얻으려면 이전 파이프라인에 실제 `negative_prompt`를 전달할 수 있지만, 이렇게 하면 prior 파이프라인의 유효 배치 크기가 2배로 증가합니다.
44
+
45
+ <hfoptions id="text-to-image">
46
+ <hfoption id="Kandinsky 2.1">
47
+
48
+ ```py
49
+ from diffusers import KandinskyPriorPipeline, KandinskyPipeline
50
+ import torch
51
+
52
+ prior_pipeline = KandinskyPriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-1-prior", torch_dtype=torch.float16).to("cuda")
53
+ pipeline = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16).to("cuda")
54
+
55
+ prompt = "A alien cheeseburger creature eating itself, claymation, cinematic, moody lighting"
56
+ negative_prompt = "low quality, bad quality" # negative 프롬프트 포함은 선택적이지만, 보통 결과는 더 좋습니다
57
+ image_embeds, negative_image_embeds = prior_pipeline(prompt, negative_prompt, guidance_scale=1.0).to_tuple()
58
+ ```
59
+
60
+ 이제 모든 프롬프트와 임베딩을 [`KandinskyPipeline`]에 전달하여 이미지를 생성합니다:
61
+
62
+ ```py
63
+ image = pipeline(prompt, image_embeds=image_embeds, negative_prompt=negative_prompt, negative_image_embeds=negative_image_embeds, height=768, width=768).images[0]
64
+ image
65
+ ```
66
+
67
+ <div class="flex justify-center">
68
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/kandinsky-docs/cheeseburger.png"/>
69
+ </div>
70
+
71
+ </hfoption>
72
+ <hfoption id="Kandinsky 2.2">
73
+
74
+ ```py
75
+ from diffusers import KandinskyV22PriorPipeline, KandinskyV22Pipeline
76
+ import torch
77
+
78
+ prior_pipeline = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16).to("cuda")
79
+ pipeline = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16).to("cuda")
80
+
81
+ prompt = "A alien cheeseburger creature eating itself, claymation, cinematic, moody lighting"
82
+ negative_prompt = "low quality, bad quality" # negative 프롬프트 포함은 선택적이지만, 보통 결과는 더 좋습니다
83
+ image_embeds, negative_image_embeds = prior_pipeline(prompt, guidance_scale=1.0).to_tuple()
84
+ ```
85
+
86
+ 이미지 생성을 위해 `image_embeds`와 `negative_image_embeds`를 [`KandinskyV22Pipeline`]에 전달합니다:
87
+
88
+ ```py
89
+ image = pipeline(image_embeds=image_embeds, negative_image_embeds=negative_image_embeds, height=768, width=768).images[0]
90
+ image
91
+ ```
92
+
93
+ <div class="flex justify-center">
94
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/kandinsky-text-to-image.png"/>
95
+ </div>
96
+
97
+ </hfoption>
98
+ <hfoption id="Kandinsky 3">
99
+
100
+ Kandinsky 3는 prior 모델이 필요하지 않으므로 [`Kandinsky3Pipeline`]을 직접 불러오고 이미지 생성 프롬프트를 전달할 수 있습니다:
101
+
102
+ ```py
103
+ from diffusers import Kandinsky3Pipeline
104
+ import torch
105
+
106
+ pipeline = Kandinsky3Pipeline.from_pretrained("kandinsky-community/kandinsky-3", variant="fp16", torch_dtype=torch.float16)
107
+ pipeline.enable_model_cpu_offload()
108
+
109
+ prompt = "A alien cheeseburger creature eating itself, claymation, cinematic, moody lighting"
110
+ image = pipeline(prompt).images[0]
111
+ image
112
+ ```
113
+
114
+ </hfoption>
115
+ </hfoptions>
116
+
117
+ 🤗 Diffusers는 또한 [`KandinskyCombinedPipeline`] 및 [`KandinskyV22CombinedPipeline`]이 포함된 end-to-end API를 제공하므로 prior 파이프라인과 text-to-image 변환 파이프라인을 별도로 불러올 필요가 없습니다. 결합된 파이프라인은 prior 모델과 디코더를 모두 자동으로 불러옵니다. 원하는 경우 `prior_guidance_scale` 및 `prior_num_inference_steps` 매개 변수를 사용하여 prior 파이프라인에 대해 다른 값을 설정할 수 있습니다.
118
+
119
+ 내부에서 결합된 파이프라인을 자동으로 호출하려면 [`AutoPipelineForText2Image`]를 사용합니다:
120
+
121
+ <hfoptions id="text-to-image">
122
+ <hfoption id="Kandinsky 2.1">
123
+
124
+ ```py
125
+ from diffusers import AutoPipelineForText2Image
126
+ import torch
127
+
128
+ pipeline = AutoPipelineForText2Image.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16)
129
+ pipeline.enable_model_cpu_offload()
130
+
131
+ prompt = "A alien cheeseburger creature eating itself, claymation, cinematic, moody lighting"
132
+ negative_prompt = "low quality, bad quality"
133
+
134
+ image = pipeline(prompt=prompt, negative_prompt=negative_prompt, prior_guidance_scale=1.0, guidance_scale=4.0, height=768, width=768).images[0]
135
+ image
136
+ ```
137
+
138
+ </hfoption>
139
+ <hfoption id="Kandinsky 2.2">
140
+
141
+ ```py
142
+ from diffusers import AutoPipelineForText2Image
143
+ import torch
144
+
145
+ pipeline = AutoPipelineForText2Image.from_pretrained("kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16)
146
+ pipeline.enable_model_cpu_offload()
147
+
148
+ prompt = "A alien cheeseburger creature eating itself, claymation, cinematic, moody lighting"
149
+ negative_prompt = "low quality, bad quality"
150
+
151
+ image = pipeline(prompt=prompt, negative_prompt=negative_prompt, prior_guidance_scale=1.0, guidance_scale=4.0, height=768, width=768).images[0]
152
+ image
153
+ ```
154
+
155
+ </hfoption>
156
+ </hfoptions>
157
+
158
+ ## Image-to-image
159
+
160
+ Image-to-image 경우, 초기 이미지와 텍스트 프롬프트를 전달하여 파이프라인에 이미지를 conditioning합니다. Prior 파이프라인을 불러오는 것으로 시작합니다:
161
+
162
+ <hfoptions id="image-to-image">
163
+ <hfoption id="Kandinsky 2.1">
164
+
165
+ ```py
166
+ import torch
167
+ from diffusers import KandinskyImg2ImgPipeline, KandinskyPriorPipeline
168
+
169
+ prior_pipeline = KandinskyPriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-1-prior", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
170
+ pipeline = KandinskyImg2ImgPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
171
+ ```
172
+
173
+ </hfoption>
174
+ <hfoption id="Kandinsky 2.2">
175
+
176
+ ```py
177
+ import torch
178
+ from diffusers import KandinskyV22Img2ImgPipeline, KandinskyPriorPipeline
179
+
180
+ prior_pipeline = KandinskyPriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
181
+ pipeline = KandinskyV22Img2ImgPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
182
+ ```
183
+
184
+ </hfoption>
185
+ <hfoption id="Kandinsky 3">
186
+
187
+ Kandinsky 3는 prior 모델이 필요하지 않으므로 image-to-image 파이프라인을 직접 불러올 수 있습니다:
188
+
189
+ ```py
190
+ from diffusers import Kandinsky3Img2ImgPipeline
191
+ from diffusers.utils import load_image
192
+ import torch
193
+
194
+ pipeline = Kandinsky3Img2ImgPipeline.from_pretrained("kandinsky-community/kandinsky-3", variant="fp16", torch_dtype=torch.float16)
195
+ pipeline.enable_model_cpu_offload()
196
+ ```
197
+
198
+ </hfoption>
199
+ </hfoptions>
200
+
201
+ Conditioning할 이미지를 다운로드합니다:
202
+
203
+ ```py
204
+ from diffusers.utils import load_image
205
+
206
+ # 이미지 다운로드
207
+ url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
208
+ original_image = load_image(url)
209
+ original_image = original_image.resize((768, 512))
210
+ ```
211
+
212
+ <div class="flex justify-center">
213
+ <img class="rounded-xl" src="https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"/>
214
+ </div>
215
+
216
+ Prior 파이프라인으로 `image_embeds`와 `negative_image_embeds`를 생성합니다:
217
+
218
+ ```py
219
+ prompt = "A fantasy landscape, Cinematic lighting"
220
+ negative_prompt = "low quality, bad quality"
221
+
222
+ image_embeds, negative_image_embeds = prior_pipeline(prompt, negative_prompt).to_tuple()
223
+ ```
224
+
225
+ 이제 원본 이미지와 모든 프롬프트 및 임베딩을 파이프라인으로 전달하여 이미지를 생성합니다:
226
+
227
+ <hfoptions id="image-to-image">
228
+ <hfoption id="Kandinsky 2.1">
229
+
230
+ ```py
231
+ from diffusers.utils import make_image_grid
232
+
233
+ image = pipeline(prompt, negative_prompt=negative_prompt, image=original_image, image_embeds=image_embeds, negative_image_embeds=negative_image_embeds, height=768, width=768, strength=0.3).images[0]
234
+ make_image_grid([original_image.resize((512, 512)), image.resize((512, 512))], rows=1, cols=2)
235
+ ```
236
+
237
+ <div class="flex justify-center">
238
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/kandinsky-docs/img2img_fantasyland.png"/>
239
+ </div>
240
+
241
+ </hfoption>
242
+ <hfoption id="Kandinsky 2.2">
243
+
244
+ ```py
245
+ from diffusers.utils import make_image_grid
246
+
247
+ image = pipeline(image=original_image, image_embeds=image_embeds, negative_image_embeds=negative_image_embeds, height=768, width=768, strength=0.3).images[0]
248
+ make_image_grid([original_image.resize((512, 512)), image.resize((512, 512))], rows=1, cols=2)
249
+ ```
250
+
251
+ <div class="flex justify-center">
252
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/kandinsky-image-to-image.png"/>
253
+ </div>
254
+
255
+ </hfoption>
256
+ <hfoption id="Kandinsky 3">
257
+
258
+ ```py
259
+ image = pipeline(prompt, negative_prompt=negative_prompt, image=image, strength=0.75, num_inference_steps=25).images[0]
260
+ image
261
+ ```
262
+
263
+ </hfoption>
264
+ </hfoptions>
265
+
266
+ 또한 🤗 Diffusers에서는 [`KandinskyImg2ImgCombinedPipeline`] 및 [`KandinskyV22Img2ImgCombinedPipeline`]이 포함된 end-to-end API를 제공하므로 prior 파이프라인과 image-to-image 파이프라인을 별도로 불러올 필요가 없습니다. 결합된 파이프라인은 prior 모델과 디코더를 모두 자동으로 불러옵니다. 원하는 경우 `prior_guidance_scale` 및 `prior_num_inference_steps` 매개 변수를 사용하여 이전 파이프라인에 대해 다른 값을 설정할 수 있습니다.
267
+
268
+ 내부에서 결합된 파이프라인을 자동으로 호출하려면 [`AutoPipelineForImage2Image`]를 사용합니다:
269
+
270
+ <hfoptions id="image-to-image">
271
+ <hfoption id="Kandinsky 2.1">
272
+
273
+ ```py
274
+ from diffusers import AutoPipelineForImage2Image
275
+ from diffusers.utils import make_image_grid, load_image
276
+ import torch
277
+
278
+ pipeline = AutoPipelineForImage2Image.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16, use_safetensors=True)
279
+ pipeline.enable_model_cpu_offload()
280
+
281
+ prompt = "A fantasy landscape, Cinematic lighting"
282
+ negative_prompt = "low quality, bad quality"
283
+
284
+ url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
285
+ original_image = load_image(url)
286
+
287
+ original_image.thumbnail((768, 768))
288
+
289
+ image = pipeline(prompt=prompt, negative_prompt=negative_prompt, image=original_image, strength=0.3).images[0]
290
+ make_image_grid([original_image.resize((512, 512)), image.resize((512, 512))], rows=1, cols=2)
291
+ ```
292
+
293
+ </hfoption>
294
+ <hfoption id="Kandinsky 2.2">
295
+
296
+ ```py
297
+ from diffusers import AutoPipelineForImage2Image
298
+ from diffusers.utils import make_image_grid, load_image
299
+ import torch
300
+
301
+ pipeline = AutoPipelineForImage2Image.from_pretrained("kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16)
302
+ pipeline.enable_model_cpu_offload()
303
+
304
+ prompt = "A fantasy landscape, Cinematic lighting"
305
+ negative_prompt = "low quality, bad quality"
306
+
307
+ url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
308
+ original_image = load_image(url)
309
+
310
+ original_image.thumbnail((768, 768))
311
+
312
+ image = pipeline(prompt=prompt, negative_prompt=negative_prompt, image=original_image, strength=0.3).images[0]
313
+ make_image_grid([original_image.resize((512, 512)), image.resize((512, 512))], rows=1, cols=2)
314
+ ```
315
+
316
+ </hfoption>
317
+ </hfoptions>
318
+
319
+ ## Inpainting
320
+
321
+ > [!WARNING]
322
+ > ⚠️ Kandinsky 모델은 이제 검은색 픽셀 대신 ⬜️ **흰색 픽셀**을 사용하여 마스크 영역을 표현합니다. 프로덕션에서 [`KandinskyInpaintPipeline`]을 사용하는 경우 흰색 픽셀을 사용하도록 마스크를 변경해야 합니다:
323
+ >
324
+ > ```py
325
+ > # PIL 입력에 대해
326
+ > import PIL.ImageOps
327
+ > mask = PIL.ImageOps.invert(mask)
328
+ >
329
+ > # PyTorch와 NumPy 입력에 대해
330
+ > mask = 1 - mask
331
+ > ```
332
+
333
+ 인페인팅에서는 원본 이미지, 원본 이미지에서 대체할 영역의 마스크, 인페인팅할 내용에 대한 텍스트 프롬프트가 필요합니다. Prior 파이프라인을 불러옵니다:
334
+
335
+ <hfoptions id="inpaint">
336
+ <hfoption id="Kandinsky 2.1">
337
+
338
+ ```py
339
+ from diffusers import KandinskyInpaintPipeline, KandinskyPriorPipeline
340
+ from diffusers.utils import load_image, make_image_grid
341
+ import torch
342
+ import numpy as np
343
+ from PIL import Image
344
+
345
+ prior_pipeline = KandinskyPriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-1-prior", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
346
+ pipeline = KandinskyInpaintPipeline.from_pretrained("kandinsky-community/kandinsky-2-1-inpaint", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
347
+ ```
348
+
349
+ </hfoption>
350
+ <hfoption id="Kandinsky 2.2">
351
+
352
+ ```py
353
+ from diffusers import KandinskyV22InpaintPipeline, KandinskyV22PriorPipeline
354
+ from diffusers.utils import load_image, make_image_grid
355
+ import torch
356
+ import numpy as np
357
+ from PIL import Image
358
+
359
+ prior_pipeline = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
360
+ pipeline = KandinskyV22InpaintPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder-inpaint", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
361
+ ```
362
+
363
+ </hfoption>
364
+ </hfoptions>
365
+
366
+ 초기 이미지를 불러오고 마스크를 생성합니다:
367
+
368
+ ```py
369
+ init_image = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png")
370
+ mask = np.zeros((768, 768), dtype=np.float32)
371
+ # mask area above cat's head
372
+ mask[:250, 250:-250] = 1
373
+ ```
374
+
375
+ Prior 파이프라인으로 임베딩을 생성합니다:
376
+
377
+ ```py
378
+ prompt = "a hat"
379
+ prior_output = prior_pipeline(prompt)
380
+ ```
381
+
382
+ 이제 이미지 생성을 위해 초기 이미지, 마스크, 프롬프트와 임베딩을 파이프라인에 전달합니다:
383
+
384
+ <hfoptions id="inpaint">
385
+ <hfoption id="Kandinsky 2.1">
386
+
387
+ ```py
388
+ output_image = pipeline(prompt, image=init_image, mask_image=mask, **prior_output, height=768, width=768, num_inference_steps=150).images[0]
389
+ mask = Image.fromarray((mask*255).astype('uint8'), 'L')
390
+ make_image_grid([init_image, mask, output_image], rows=1, cols=3)
391
+ ```
392
+
393
+ <div class="flex justify-center">
394
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/kandinsky-docs/inpaint_cat_hat.png"/>
395
+ </div>
396
+
397
+ </hfoption>
398
+ <hfoption id="Kandinsky 2.2">
399
+
400
+ ```py
401
+ output_image = pipeline(image=init_image, mask_image=mask, **prior_output, height=768, width=768, num_inference_steps=150).images[0]
402
+ mask = Image.fromarray((mask*255).astype('uint8'), 'L')
403
+ make_image_grid([init_image, mask, output_image], rows=1, cols=3)
404
+ ```
405
+
406
+ <div class="flex justify-center">
407
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/kandinskyv22-inpaint.png"/>
408
+ </div>
409
+
410
+ </hfoption>
411
+ </hfoptions>
412
+
413
+ [`KandinskyInpaintCombinedPipeline`] 및 [`KandinskyV22InpaintCombinedPipeline`]을 사용하여 내부에서 prior 및 디코더 파이프라인을 함께 호출할 수 있습니다. 이를 위해 [`AutoPipelineForInpainting`]을 사용합니다:
414
+
415
+ <hfoptions id="inpaint">
416
+ <hfoption id="Kandinsky 2.1">
417
+
418
+ ```py
419
+ import torch
420
+ import numpy as np
421
+ from PIL import Image
422
+ from diffusers import AutoPipelineForInpainting
423
+ from diffusers.utils import load_image, make_image_grid
424
+
425
+ pipe = AutoPipelineForInpainting.from_pretrained("kandinsky-community/kandinsky-2-1-inpaint", torch_dtype=torch.float16)
426
+ pipe.enable_model_cpu_offload()
427
+
428
+ init_image = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png")
429
+ mask = np.zeros((768, 768), dtype=np.float32)
430
+ # 고양이 머리 위 마스크 지역
431
+ mask[:250, 250:-250] = 1
432
+ prompt = "a hat"
433
+
434
+ output_image = pipe(prompt=prompt, image=init_image, mask_image=mask).images[0]
435
+ mask = Image.fromarray((mask*255).astype('uint8'), 'L')
436
+ make_image_grid([init_image, mask, output_image], rows=1, cols=3)
437
+ ```
438
+
439
+ </hfoption>
440
+ <hfoption id="Kandinsky 2.2">
441
+
442
+ ```py
443
+ import torch
444
+ import numpy as np
445
+ from PIL import Image
446
+ from diffusers import AutoPipelineForInpainting
447
+ from diffusers.utils import load_image, make_image_grid
448
+
449
+ pipe = AutoPipelineForInpainting.from_pretrained("kandinsky-community/kandinsky-2-2-decoder-inpaint", torch_dtype=torch.float16)
450
+ pipe.enable_model_cpu_offload()
451
+
452
+ init_image = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png")
453
+ mask = np.zeros((768, 768), dtype=np.float32)
454
+ # 고양이 머리 위 마스크 영역
455
+ mask[:250, 250:-250] = 1
456
+ prompt = "a hat"
457
+
458
+ output_image = pipe(prompt=prompt, image=original_image, mask_image=mask).images[0]
459
+ mask = Image.fromarray((mask*255).astype('uint8'), 'L')
460
+ make_image_grid([init_image, mask, output_image], rows=1, cols=3)
461
+ ```
462
+
463
+ </hfoption>
464
+ </hfoptions>
465
+
466
+ ## Interpolation (보간)
467
+
468
+ Interpolation(보간)을 사용하면 이미지와 텍스트 임베딩 사이의 latent space를 탐색할 수 있어 prior 모델의 중간 결과물을 볼 수 있는 멋진 방법입니다. Prior 파이프라인과 보간하려는 두 개의 이미지를 불러옵니다:
469
+
470
+ <hfoptions id="interpolate">
471
+ <hfoption id="Kandinsky 2.1">
472
+
473
+ ```py
474
+ from diffusers import KandinskyPriorPipeline, KandinskyPipeline
475
+ from diffusers.utils import load_image, make_image_grid
476
+ import torch
477
+
478
+ prior_pipeline = KandinskyPriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-1-prior", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
479
+ img_1 = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png")
480
+ img_2 = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/starry_night.jpeg")
481
+ make_image_grid([img_1.resize((512,512)), img_2.resize((512,512))], rows=1, cols=2)
482
+ ```
483
+
484
+ </hfoption>
485
+ <hfoption id="Kandinsky 2.2">
486
+
487
+ ```py
488
+ from diffusers import KandinskyV22PriorPipeline, KandinskyV22Pipeline
489
+ from diffusers.utils import load_image, make_image_grid
490
+ import torch
491
+
492
+ prior_pipeline = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
493
+ img_1 = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png")
494
+ img_2 = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/starry_night.jpeg")
495
+ make_image_grid([img_1.resize((512,512)), img_2.resize((512,512))], rows=1, cols=2)
496
+ ```
497
+
498
+ </hfoption>
499
+ </hfoptions>
500
+
501
+ <div class="flex gap-4">
502
+ <div>
503
+ <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"/>
504
+ <figcaption class="mt-2 text-center text-sm text-gray-500">a cat</figcaption>
505
+ </div>
506
+ <div>
507
+ <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/starry_night.jpeg"/>
508
+ <figcaption class="mt-2 text-center text-sm text-gray-500">Van Gogh's Starry Night painting</figcaption>
509
+ </div>
510
+ </div>
511
+
512
+ 보간할 텍스트 또는 이미지를 지정하고 각 텍스트 또는 이미지에 대한 가중치를 설정합니다. 가중치를 실험하여 보간에 어떤 영향을 미치는지 확인하세요!
513
+
514
+ ```py
515
+ images_texts = ["a cat", img_1, img_2]
516
+ weights = [0.3, 0.3, 0.4]
517
+ ```
518
+
519
+ `interpolate` 함수를 호출하여 임베딩을 생성한 다음, 파이프라인으로 전달하여 이미지를 생성합니다:
520
+
521
+ <hfoptions id="interpolate">
522
+ <hfoption id="Kandinsky 2.1">
523
+
524
+ ```py
525
+ # 프롬프트는 빈칸으로 남겨도 됩니다
526
+ prompt = ""
527
+ prior_out = prior_pipeline.interpolate(images_texts, weights)
528
+
529
+ pipeline = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
530
+
531
+ image = pipeline(prompt, **prior_out, height=768, width=768).images[0]
532
+ image
533
+ ```
534
+
535
+ <div class="flex justify-center">
536
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/kandinsky-docs/starry_cat.png"/>
537
+ </div>
538
+
539
+ </hfoption>
540
+ <hfoption id="Kandinsky 2.2">
541
+
542
+ ```py
543
+ # 프롬프트는 빈칸으로 남겨도 됩니다
544
+ prompt = ""
545
+ prior_out = prior_pipeline.interpolate(images_texts, weights)
546
+
547
+ pipeline = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
548
+
549
+ image = pipeline(prompt, **prior_out, height=768, width=768).images[0]
550
+ image
551
+ ```
552
+
553
+ <div class="flex justify-center">
554
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/kandinskyv22-interpolate.png"/>
555
+ </div>
556
+
557
+ </hfoption>
558
+ </hfoptions>
559
+
560
+ ## ControlNet
561
+
562
+ > [!WARNING]
563
+ > ⚠️ ControlNet은 Kandinsky 2.2에서만 지원됩니다!
564
+
565
+ ControlNet을 사용하면 depth map이나 edge detection와 같은 추가 입력을 통해 사전학습된 large diffusion 모델을 conditioning할 수 있습니다. 예를 들어, 모델이 depth map의 구조를 이해하고 보존할 수 있도록 깊이 맵으로 Kandinsky 2.2를 conditioning할 수 있습니다.
566
+
567
+ 이미지를 불러오고 depth map을 추출해 보겠습니다:
568
+
569
+ ```py
570
+ from diffusers.utils import load_image
571
+
572
+ img = load_image(
573
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinskyv22/cat.png"
574
+ ).resize((768, 768))
575
+ img
576
+ ```
577
+
578
+ <div class="flex justify-center">
579
+ <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinskyv22/cat.png"/>
580
+ </div>
581
+
582
+ 그런 다음 🤗 Transformers의 `depth-estimation` [`~transformers.Pipeline`]을 사용하여 이미지를 처리해 depth map을 구할 수 있습니다:
583
+
584
+ ```py
585
+ import torch
586
+ import numpy as np
587
+
588
+ from transformers import pipeline
589
+
590
+ def make_hint(image, depth_estimator):
591
+ image = depth_estimator(image)["depth"]
592
+ image = np.array(image)
593
+ image = image[:, :, None]
594
+ image = np.concatenate([image, image, image], axis=2)
595
+ detected_map = torch.from_numpy(image).float() / 255.0
596
+ hint = detected_map.permute(2, 0, 1)
597
+ return hint
598
+
599
+ depth_estimator = pipeline("depth-estimation")
600
+ hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")
601
+ ```
602
+
603
+ ### Text-to-image [[controlnet-text-to-image]]
604
+
605
+ Prior 파이프라인과 [`KandinskyV22ControlnetPipeline`]를 불러옵니다:
606
+
607
+ ```py
608
+ from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline
609
+
610
+ prior_pipeline = KandinskyV22PriorPipeline.from_pretrained(
611
+ "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16, use_safetensors=True
612
+ ).to("cuda")
613
+
614
+ pipeline = KandinskyV22ControlnetPipeline.from_pretrained(
615
+ "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16
616
+ ).to("cuda")
617
+ ```
618
+
619
+ 프롬프트와 negative 프롬프트로 이미지 임베딩을 생성합니다:
620
+
621
+ ```py
622
+ prompt = "A robot, 4k photo"
623
+ negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"
624
+
625
+ generator = torch.Generator(device="cuda").manual_seed(43)
626
+
627
+ image_emb, zero_image_emb = prior_pipeline(
628
+ prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator
629
+ ).to_tuple()
630
+ ```
631
+
632
+ 마지막으로 이미지 임베딩과 depth 이미지를 [`KandinskyV22ControlnetPipeline`]에 전달하여 이미지를 생성합니다:
633
+
634
+ ```py
635
+ image = pipeline(image_embeds=image_emb, negative_image_embeds=zero_image_emb, hint=hint, num_inference_steps=50, generator=generator, height=768, width=768).images[0]
636
+ image
637
+ ```
638
+
639
+ <div class="flex justify-center">
640
+ <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinskyv22/robot_cat_text2img.png"/>
641
+ </div>
642
+
643
+ ### Image-to-image [[controlnet-image-to-image]]
644
+
645
+ ControlNet을 사용한 image-to-image의 경우, 다음을 사용할 필요가 있습니다:
646
+
647
+ - [`KandinskyV22PriorEmb2EmbPipeline`]로 텍스트 프롬프트와 이미지에서 이미지 임베딩을 생성합니다.
648
+ - [`KandinskyV22ControlnetImg2ImgPipeline`]로 초기 이미지와 이미지 임베딩에서 이미지를 생성합니다.
649
+
650
+ 🤗 Transformers에서 `depth-estimation` [`~transformers.Pipeline`]을 사용하여 고양이의 초기 이미지의 depth map을 처리해 추출합니다:
651
+
652
+ ```py
653
+ import torch
654
+ import numpy as np
655
+
656
+ from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline
657
+ from diffusers.utils import load_image
658
+ from transformers import pipeline
659
+
660
+ img = load_image(
661
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinskyv22/cat.png"
662
+ ).resize((768, 768))
663
+
664
+ def make_hint(image, depth_estimator):
665
+ image = depth_estimator(image)["depth"]
666
+ image = np.array(image)
667
+ image = image[:, :, None]
668
+ image = np.concatenate([image, image, image], axis=2)
669
+ detected_map = torch.from_numpy(image).float() / 255.0
670
+ hint = detected_map.permute(2, 0, 1)
671
+ return hint
672
+
673
+ depth_estimator = pipeline("depth-estimation")
674
+ hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")
675
+ ```
676
+
677
+ Prior 파이프라인과 [`KandinskyV22ControlnetImg2ImgPipeline`]을 불러옵니다:
678
+
679
+ ```py
680
+ prior_pipeline = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(
681
+ "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16, use_safetensors=True
682
+ ).to("cuda")
683
+
684
+ pipeline = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(
685
+ "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16
686
+ ).to("cuda")
687
+ ```
688
+
689
+ 텍스트 프롬프트와 초기 이미지를 이전 파이프라인에 전달하여 이미지 임베딩을 생성합니다:
690
+
691
+ ```py
692
+ prompt = "A robot, 4k photo"
693
+ negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"
694
+
695
+ generator = torch.Generator(device="cuda").manual_seed(43)
696
+
697
+ img_emb = prior_pipeline(prompt=prompt, image=img, strength=0.85, generator=generator)
698
+ negative_emb = prior_pipeline(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)
699
+ ```
700
+
701
+ 이제 [`KandinskyV22ControlnetImg2ImgPipeline`]을 실행하여 초기 이미지와 이미지 임베딩으로부터 이미지를 생성할 수 있습니다:
702
+
703
+ ```py
704
+ image = pipeline(image=img, strength=0.5, image_embeds=img_emb.image_embeds, negative_image_embeds=negative_emb.image_embeds, hint=hint, num_inference_steps=50, generator=generator, height=768, width=768).images[0]
705
+ make_image_grid([img.resize((512, 512)), image.resize((512, 512))], rows=1, cols=2)
706
+ ```
707
+
708
+ <div class="flex justify-center">
709
+ <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinskyv22/robot_cat.png"/>
710
+ </div>
711
+
712
+ ## 최적화
713
+
714
+ Kandinsky는 mapping을 생성하기 위한 prior 파이프라인과 latents를 이미지로 디코딩하기 위한 두 번째 파이프라인이 필요하다는 점에서 독특합니다. 대부분의 계산이 두 번째 파이프라인에서 이루어지므로 최적화의 노력은 두 번째 파이프라인에 집중되어야 합니다. 다음은 추론 중 Kandinsky키를 개선하기 위한 몇 가지 팁입니다.
715
+
716
+ 1. PyTorch < 2.0을 사용할 경우 [xFormers](../optimization/xformers)을 활성화합니다.
717
+
718
+ ```diff
719
+ from diffusers import DiffusionPipeline
720
+ import torch
721
+
722
+ pipe = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16)
723
+ + pipe.enable_xformers_memory_efficient_attention()
724
+ ```
725
+
726
+ 2. PyTorch >= 2.0을 사용할 경우 `torch.compile`을 활성화하여 scaled dot-product attention (SDPA)를 자동으로 사용하도록 합니다:
727
+
728
+ ```diff
729
+ pipe.unet.to(memory_format=torch.channels_last)
730
+ + pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
731
+ ```
732
+
733
+ 이는 attention processor를 명시적으로 [`~models.attention_processor.AttnAddedKVProcessor2_0`]을 사용하도록 설정하는 것과 동일합니다:
734
+
735
+ ```py
736
+ from diffusers.models.attention_processor import AttnAddedKVProcessor2_0
737
+
738
+ pipe.unet.set_attn_processor(AttnAddedKVProcessor2_0())
739
+ ```
740
+
741
+ 3. 메모리 부족 오류를 방지하기 위해 [`~KandinskyPriorPipeline.enable_model_cpu_offload`]를 사용하여 모델을 CPU로 오프로드합니다:
742
+
743
+ ```diff
744
+ from diffusers import DiffusionPipeline
745
+ import torch
746
+
747
+ pipe = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16)
748
+ + pipe.enable_model_cpu_offload()
749
+ ```
750
+
751
+ 4. 기본적으로 text-to-image 파이프라인은 [`DDIMScheduler`]를 사용하지만, [`DDPMScheduler`]와 같은 다른 스케줄러로 대체하여 추론 속도와 이미지 품질 간의 균형에 어떤 영향을 미치는지 확인할 수 있습니다:
752
+
753
+ ```py
754
+ from diffusers import DDPMScheduler
755
+ from diffusers import DiffusionPipeline
756
+
757
+ scheduler = DDPMScheduler.from_pretrained("kandinsky-community/kandinsky-2-1", subfolder="ddpm_scheduler")
758
+ pipe = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", scheduler=scheduler, torch_dtype=torch.float16, use_safetensors=True).to("cuda")
759
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/loading.md ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+
14
+
15
+ # 파이프라인, 모델, 스케줄러 불러오기
16
+
17
+ 기본적으로 diffusion 모델은 다양한 컴포넌트들(모델, 토크나이저, 스케줄러) 간의 복잡한 상호작용을 기반으로 동작합니다. 디퓨저스(Diffusers)는 이러한 diffusion 모델을 보다 쉽고 간편한 API로 제공하는 것을 목표로 설계되었습니다. [`DiffusionPipeline`]은 diffusion 모델이 갖는 복잡성을 하나의 파이프라인 API로 통합하고, 동시에 이를 구성하는 각각의 컴포넌트들을 태스크에 맞춰 유연하게 커스터마이징할 수 있도록 지원하고 있습니다.
18
+
19
+ diffusion 모델의 훈련과 추론에 필요한 모든 것은 [`DiffusionPipeline.from_pretrained`] 메서드를 통해 접근할 수 있습니다. (이 말의 의미는 다음 단락에서 보다 자세하게 다뤄보도록 하겠습니다.)
20
+
21
+ 이 문서에서는 설명할 내용은 다음과 같습니다.
22
+
23
+ * 허브를 통해 혹은 로컬로 파이프라인을 불러오는 법
24
+
25
+ * 파이프라인에 다른 컴포넌트들을 적용하는 법
26
+ * 오리지널 체크포인트가 아닌 variant를 불러오는 법 (variant란 기본으로 설정된 `fp32`가 아닌 다른 부동 소수점 타입(예: `fp16`)을 사용하거나 Non-EMA 가중치를 사용하는 체크포인트들을 의미합니다.)
27
+ * 모델과 스케줄러를 불러오는 법
28
+
29
+
30
+
31
+ ## Diffusion 파이프라인
32
+
33
+ > [!TIP]
34
+ > 💡 [`DiffusionPipeline`] 클래스가 동작하는 방식에 보다 자세한 내용이 궁금하다면, [DiffusionPipeline explained](#diffusionpipeline에-대해-알아보기) 섹션을 확인해보세요.
35
+
36
+ [`DiffusionPipeline`] 클래스는 diffusion 모델을 [허브](https://huggingface.co/models?library=diffusers)로부터 불러오는 가장 심플하면서 보편적인 방식입니다. [`DiffusionPipeline.from_pretrained`] 메서드는 적합한 파이프라인 클래스를 자동으로 탐지하고, 필요한 구성요소(configuration)와 가중치(weight) 파일들을 다운로드하고 캐싱한 다음, 해당 파이프라인 인스턴스를 반환합니다.
37
+
38
+ ```python
39
+ from diffusers import DiffusionPipeline
40
+
41
+ repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
42
+ pipe = DiffusionPipeline.from_pretrained(repo_id)
43
+ ```
44
+
45
+ 물론 [`DiffusionPipeline`] 클래스를 사용하지 않고, 명시적으로 직접 해당 파이프라인 클래스를 불러오는 것도 가능합니다. 아래 예시 코드는 위 예시와 동일한 인스턴스를 반환합니다.
46
+
47
+ ```python
48
+ from diffusers import StableDiffusionPipeline
49
+
50
+ repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
51
+ pipe = StableDiffusionPipeline.from_pretrained(repo_id)
52
+ ```
53
+
54
+ [CompVis/stable-diffusion-v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4)이나 [stable-diffusion-v1-5/stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) 같은 체크포인트들의 경우, 하나 이상의 다양한 태스크에 활용될 수 있습니다. (예를 들어 위의 두 체크포인트의 경우, text-to-image와 image-to-image에 모두 활용될 수 있습니다.) 만약 이러한 체크포인트들을 기본 설정 태스크가 아닌 다른 태스크에 활용하고자 한다면, 해당 태스크에 대응되는 파이프라인(task-specific pipeline)을 사용해야 합니다.
55
+
56
+ ```python
57
+ from diffusers import StableDiffusionImg2ImgPipeline
58
+
59
+ repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
60
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(repo_id)
61
+ ```
62
+
63
+
64
+
65
+ ### 로컬 파이프라인
66
+
67
+ 파이프라인을 로컬로 불러오고자 한다면, `git-lfs`를 사용하여 직접 체크포인트를 로컬 디스크에 다운로드 받아야 합니다. 아래의 명령어를 실행하면 `./stable-diffusion-v1-5`란 이름으로 폴더가 로컬디스크에 생성됩니다.
68
+
69
+ ```bash
70
+ git lfs install
71
+ git clone https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5
72
+ ```
73
+
74
+ 그런 다음 해당 로컬 경로를 [`~DiffusionPipeline.from_pretrained`] 메서드에 전달합니다.
75
+
76
+ ```python
77
+ from diffusers import DiffusionPipeline
78
+
79
+ repo_id = "./stable-diffusion-v1-5"
80
+ stable_diffusion = DiffusionPipeline.from_pretrained(repo_id)
81
+ ```
82
+
83
+ 위의 예시코드처럼 만약 `repo_id`가 로컬 패스(local path)라면, [`~DiffusionPipeline.from_pretrained`] 메서드는 이를 자동으로 감지하여 허브에서 파일을 다운로드하지 않습��다. 만약 로컬 디스크에 저장된 파이프라인 체크포인트가 최신 버전이 아닐 경우에도, 최신 버전을 다운로드하지 않고 기존 로컬 디스크에 저장된 체크포인트를 사용한다는 것을 의미합니다.
84
+
85
+
86
+
87
+ ### 파이프라인 내부의 컴포넌트 교체하기
88
+
89
+ 파이프라인 내부의 컴포넌트들은 호환 가능한 다른 컴포넌트로 교체될 수 있습니다. 이와 같은 컴포넌트 교체가 중요한 이유는 다음과 같습니다.
90
+
91
+ - 어떤 스케줄러를 사용할 것인가는 생성속도와 생성품질 간의 트레이드오프를 정의하는 중요한 요소입니다.
92
+ - diffusion 모델 내부의 컴포넌트들은 일반적으로 각각 독립적으로 훈련되기 때문에, 더 좋은 성능을 보여주는 컴포넌트가 있다면 그걸로 교체하는 식으로 성능을 향상시킬 수 있습니다.
93
+ - 파인 튜닝 단계에서는 일반적으로 UNet 혹은 텍스트 인코더와 같은 일부 컴포넌트들만 훈련하게 됩니다.
94
+
95
+ 어떤 스케줄러들이 호환가능한지는 `compatibles` 속성을 통해 확인할 수 있습니다.
96
+
97
+ ```python
98
+ from diffusers import DiffusionPipeline
99
+
100
+ repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
101
+ stable_diffusion = DiffusionPipeline.from_pretrained(repo_id)
102
+ stable_diffusion.scheduler.compatibles
103
+ ```
104
+
105
+ 이번에는 [`SchedulerMixin.from_pretrained`] 메서드를 사용해서, 기존 기본 스케줄러였던 [`PNDMScheduler`]를 보다 우수한 성능의 [`EulerDiscreteScheduler`]로 바꿔봅시다. 스케줄러를 로드할 때는 `subfolder` 인자를 통해, 해당 파이프라인의 리포지토리에서 [스케줄러에 관한 하위폴더](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/tree/main/scheduler)를 명시해주어야 합니다.
106
+
107
+ 그 다음 새롭게 생성한 [`EulerDiscreteScheduler`] 인스턴스를 [`DiffusionPipeline`]의 `scheduler` 인자에 전달합니다.
108
+
109
+ ```python
110
+ from diffusers import DiffusionPipeline, EulerDiscreteScheduler, DPMSolverMultistepScheduler
111
+
112
+ repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
113
+
114
+ scheduler = EulerDiscreteScheduler.from_pretrained(repo_id, subfolder="scheduler")
115
+
116
+ stable_diffusion = DiffusionPipeline.from_pretrained(repo_id, scheduler=scheduler)
117
+ ```
118
+
119
+ ### 세이프티 체커
120
+
121
+ 스테이블 diffusion과 같은 diffusion 모델들은 유해한 이미지를 생성할 수도 있습니다. 이를 예방하기 위해 디퓨저스는 생성된 이미지의 유해성을 판단하는 [세이프티 체커(safety checker)](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py) 기능을 지원하고 있습니다. 만약 세이프티 체커의 사용을 원하지 않는다면, `safety_checker` 인자에 `None`을 전달해주시면 됩니다.
122
+
123
+ ```python
124
+ from diffusers import DiffusionPipeline
125
+
126
+ repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
127
+ stable_diffusion = DiffusionPipeline.from_pretrained(repo_id, safety_checker=None)
128
+ ```
129
+
130
+ ### 컴포넌트 재사용
131
+
132
+ 복수의 파이프라인에 동일한 모델이 반복적으로 사용한다면, 굳이 해당 모델의 동일한 가중치를 중복으로 RAM에 불러올 필요는 없을 것입니다. [`~DiffusionPipeline.components`] 속성을 통해 파이프라인 내부의 컴포넌트들을 참조할 수 있는데, 이번 단락에서는 이를 통해 동일한 모델 가중치를 RAM에 중복으로 불러오는 것을 방지하는 법에 대해 알아보겠습니다.
133
+
134
+ ```python
135
+ from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline
136
+
137
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
138
+ stable_diffusion_txt2img = StableDiffusionPipeline.from_pretrained(model_id)
139
+
140
+ components = stable_diffusion_txt2img.components
141
+ ```
142
+
143
+ 그 다음 위 예시 코드에서 선언한 `components` 변수를 다른 파이프라인에 전달함으로써, 모델의 가중치를 중복으로 RAM에 로딩하지 않고, 동일한 컴포넌트를 재사용할 수 있습니다.
144
+
145
+ ```python
146
+ stable_diffusion_img2img = StableDiffusionImg2ImgPipeline(**components)
147
+ ```
148
+
149
+ 물론 각각의 컴포넌트들을 따로 따로 파이프라인에 전달할 수도 있습니다. 예를 들어 `stable_diffusion_txt2img` 파이프라인 안의 컴포넌트들 가운데서 세이프티 체커(`safety_checker`)와 피쳐 익스트랙터(`feature_extractor`)를 제외한 컴포넌트들만 `stable_diffusion_img2img` 파이프라인에서 재사용하는 방식 역시 가능합니다.
150
+
151
+ ```python
152
+ from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline
153
+
154
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
155
+ stable_diffusion_txt2img = StableDiffusionPipeline.from_pretrained(model_id)
156
+ stable_diffusion_img2img = StableDiffusionImg2ImgPipeline(
157
+ vae=stable_diffusion_txt2img.vae,
158
+ text_encoder=stable_diffusion_txt2img.text_encoder,
159
+ tokenizer=stable_diffusion_txt2img.tokenizer,
160
+ unet=stable_diffusion_txt2img.unet,
161
+ scheduler=stable_diffusion_txt2img.scheduler,
162
+ safety_checker=None,
163
+ feature_extractor=None,
164
+ requires_safety_checker=False,
165
+ )
166
+ ```
167
+
168
+ ## Checkpoint variants
169
+
170
+ Variant란 일반적으로 다음과 같은 체크포인트들을 의미합니다.
171
+
172
+ - `torch.float16`과 같이 정밀도는 더 낮지만, 용량 역시 더 작은 부동소수점 타입의 가중치를 사용하는 체크포인트. *(다만 이와 같은 variant의 경우, 추가적인 훈련과 CPU환경에서의 구동이 불가능합니다.)*
173
+ - Non-EMA 가중치를 사용하는 체크포인트. *(Non-EMA 가중치의 경우, 파인 튜닝 단계에서 사용하는 것이 권장되는데, 추론 단계에선 사용하지 않는 것이 권장됩니다.)*
174
+
175
+ > [!TIP]
176
+ > 💡 모델 구조는 동일하지만 서로 다른 학습 환경에서 서로 다른 데이터셋으로 학습된 체크포인트들이 있을 경우, 해당 체크포인트들은 variant 단계가 아닌 리포지토리 단계에서 분리되어 관리되어야 합니다. (즉, 해당 체크포인트들은 서로 다른 리포지토리에서 따로 관리되어야 합니다. 예시: [`stable-diffusion-v1-4`], [`stable-diffusion-v1-5`]).
177
+
178
+ | **checkpoint type** | **weight name** | **argument for loading weights** |
179
+ | ------------------- | ----------------------------------- | -------------------------------- |
180
+ | original | diffusion_pytorch_model.bin | |
181
+ | floating point | diffusion_pytorch_model.fp16.bin | `variant`, `torch_dtype` |
182
+ | non-EMA | diffusion_pytorch_model.non_ema.bin | `variant` |
183
+
184
+ variant를 로드할 때 2개의 중요한 argument가 있습니다.
185
+
186
+ * `torch_dtype`은 불러올 체크포인트의 부동소수점을 정의합니다. 예를 들어 `torch_dtype=torch.float16`을 명시함으로써 가중치의 부동소수점 타입을 `fl16`으로 변환할 수 있습니다. (만약 따로 설정하지 않을 경우, 기본값으로 `fp32` 타입의 가중치가 로딩됩니다.) 또한 `variant` 인자를 명시하지 않은 채로 체크포인트를 불러온 다음, 해당 체크포인트를 `torch_dtype=torch.float16` 인자를 통해 `fp16` 타입으로 변환하는 것 역시 가능합니다. 이 경우 기본으로 설정된 `fp32` 가중치가 먼저 다운로드되고, 해당 가중치들을 불러온 다음 `fp16` 타입으로 변환하게 됩니다.
187
+ * `variant` 인자는 리포지토리에서 어떤 variant를 불러올 것인가를 정의합니다. 가령 [`diffusers/stable-diffusion-variants`](https://huggingface.co/diffusers/stable-diffusion-variants/tree/main/unet) 리포지토리로부터 `non_ema` 체크포인트를 불러오고자 한다면, `variant="non_ema"` 인자를 전달해야 합니다.
188
+
189
+ ```python
190
+ from diffusers import DiffusionPipeline
191
+
192
+ # load fp16 variant
193
+ stable_diffusion = DiffusionPipeline.from_pretrained(
194
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", variant="fp16", torch_dtype=torch.float16
195
+ )
196
+ # load non_ema variant
197
+ stable_diffusion = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", variant="non_ema")
198
+ ```
199
+
200
+ 다른 부동소수점 타입의 가중치 혹은 non-EMA 가중치를 사용하는 체크포인트를 저장하기 위해서는, [`DiffusionPipeline.save_pretrained`] 메서드를 사용해야 하며, 이 때 `variant` 인자를 명시해줘야 합니다. 원래의 체크포인트와 동일한 폴더에 variant를 저장해야 하며, 이렇게 하면 동일한 폴더에서 오리지널 체크포인트과 variant를 모두 불러올 수 있습니다.
201
+
202
+ ```python
203
+ from diffusers import DiffusionPipeline
204
+
205
+ # save as fp16 variant
206
+ stable_diffusion.save_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", variant="fp16")
207
+ # save as non-ema variant
208
+ stable_diffusion.save_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", variant="non_ema")
209
+ ```
210
+
211
+ 만약 variant를 기존 폴더에 저장하지 않을 경우, `variant` 인자를 반드시 명시해야 합니다. 그렇게 하지 않을 경우 원래의 오리지널 체크포인트를 찾을 수 없게 되기 때문에 에러가 발생합니다.
212
+
213
+ ```python
214
+ # 👎 this won't work
215
+ stable_diffusion = DiffusionPipeline.from_pretrained("./stable-diffusion-v1-5", torch_dtype=torch.float16)
216
+ # 👍 this works
217
+ stable_diffusion = DiffusionPipeline.from_pretrained(
218
+ "./stable-diffusion-v1-5", variant="fp16", torch_dtype=torch.float16
219
+ )
220
+ ```
221
+
222
+ ### 모델 불러오기
223
+
224
+ 모델들은 [`ModelMixin.from_pretrained`] 메서드를 통해 불러올 수 있습니다. 해당 메서드는 최신 버전의 모델 가중치 파일과 설정 파일(configurations)을 다운로드하고 캐싱합니다. 만약 이러한 파일들이 최신 버전으로 로컬 캐시에 저장되어 있다면, [`ModelMixin.from_pretrained`]는 굳이 해당 파일들을 다시 다운로드하지 않으며, 그저 캐시에 있는 최신 파일들을 재사용합니다.
225
+
226
+ 모델은 `subfolder` 인자에 명시된 하위 폴더로부터 로드됩니다. 예를 들어 `stable-diffusion-v1-5/stable-diffusion-v1-5`의 UNet 모델의 가중치는 [`unet`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/tree/main/unet) 폴더에 저장되어 있습니다.
227
+
228
+ ```python
229
+ from diffusers import UNet2DConditionModel
230
+
231
+ repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
232
+ model = UNet2DConditionModel.from_pretrained(repo_id, subfolder="unet")
233
+ ```
234
+
235
+ 혹은 [해당 모델의 리포지토리](https://huggingface.co/google/ddpm-cifar10-32/tree/main)로부터 다이렉트로 가져오는 것 역시 가능합니다.
236
+
237
+ ```python
238
+ from diffusers import UNet2DModel
239
+
240
+ repo_id = "google/ddpm-cifar10-32"
241
+ model = UNet2DModel.from_pretrained(repo_id)
242
+ ```
243
+
244
+ 또한 앞서 봤던 `variant` 인자를 명시함으로써, Non-EMA나 `fp16`의 가중치를 가져오는 것 역시 가능합니다.
245
+
246
+ ```python
247
+ from diffusers import UNet2DConditionModel
248
+
249
+ model = UNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="unet", variant="non-ema")
250
+ model.save_pretrained("./local-unet", variant="non-ema")
251
+ ```
252
+
253
+ ### 스케줄러
254
+
255
+ 스케줄러들은 [`SchedulerMixin.from_pretrained`] 메서드를 통해 불러올 수 있습니다. 모델과 달리 스케줄러는 별도의 가중치를 갖지 않으며, 따라서 당연히 별도의 학습과정을 요구하지 않습니다. 이러한 스케줄러들은 (해당 스케줄러 하위폴더의) configration 파일을 통해 정의됩니다.
256
+
257
+ 여러개의 스케줄러를 불러온다고 해서 많은 메모리를 소모하는 것은 아니며, 다양한 스케줄러들에 동일한 스케줄러 configration을 적용하는 것 역시 가능합니다. 다음 예시 코드에서 불러오는 스케줄러들은 모두 [`StableDiffusionPipeline`]과 호환되는데, 이는 곧 해당 스케줄러들에 동일한 스케줄러 configration 파일을 적용할 수 있음을 의미합니다.
258
+
259
+ ```python
260
+ from diffusers import StableDiffusionPipeline
261
+ from diffusers import (
262
+ DDPMScheduler,
263
+ DDIMScheduler,
264
+ PNDMScheduler,
265
+ LMSDiscreteScheduler,
266
+ EulerDiscreteScheduler,
267
+ EulerAncestralDiscreteScheduler,
268
+ DPMSolverMultistepScheduler,
269
+ )
270
+
271
+ repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
272
+
273
+ ddpm = DDPMScheduler.from_pretrained(repo_id, subfolder="scheduler")
274
+ ddim = DDIMScheduler.from_pretrained(repo_id, subfolder="scheduler")
275
+ pndm = PNDMScheduler.from_pretrained(repo_id, subfolder="scheduler")
276
+ lms = LMSDiscreteScheduler.from_pretrained(repo_id, subfolder="scheduler")
277
+ euler_anc = EulerAncestralDiscreteScheduler.from_pretrained(repo_id, subfolder="scheduler")
278
+ euler = EulerDiscreteScheduler.from_pretrained(repo_id, subfolder="scheduler")
279
+ dpm = DPMSolverMultistepScheduler.from_pretrained(repo_id, subfolder="scheduler")
280
+
281
+ # replace `dpm` with any of `ddpm`, `ddim`, `pndm`, `lms`, `euler_anc`, `euler`
282
+ pipeline = StableDiffusionPipeline.from_pretrained(repo_id, scheduler=dpm)
283
+ ```
284
+
285
+ ### DiffusionPipeline에 대해 알아보기
286
+
287
+ 클래스 메서드로서 [`DiffusionPipeline.from_pretrained`]은 2가지를 담당합니다.
288
+
289
+ - 첫째로, `from_pretrained` 메서드는 최신 버전의 파이프라인을 다운로드하고, 캐시에 저장합니다. 이미 로컬 캐시에 최신 버전의 파이프라인이 저장되어 있다면, [`DiffusionPipeline.from_pretrained`]은 해당 파일들을 다시 다운로드하지 않고, 로컬 캐시에 저장되어 있는 파이프라인을 불러옵니다.
290
+ - `model_index.json` 파일을 통해 체크포인트에 대응되는 적합한 파이프라인 클래스로 불러옵니다.
291
+
292
+ 파이프라인의 폴더 구조는 해당 파이프라인 클래스의 구조와 직접적으로 일치합니다. 예를 들어 [`StableDiffusionPipeline`] 클래스는 [`stable-diffusion-v1-5/stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) 리포지토리와 대응되는 구조를 갖습니다.
293
+
294
+ ```python
295
+ from diffusers import DiffusionPipeline
296
+
297
+ repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
298
+ pipeline = DiffusionPipeline.from_pretrained(repo_id)
299
+ print(pipeline)
300
+ ```
301
+
302
+ 위의 코드 출력 결과를 확인해보면, `pipeline`은 [`StableDiffusionPipeline`]의 인스턴스이며, 다음과 같이 총 7개의 컴포넌트로 구성된다는 것을 알 수 있습니다.
303
+
304
+ - `"feature_extractor"`: [`~transformers.CLIPImageProcessor`]의 인스턴스
305
+ - `"safety_checker"`: 유해한 컨텐츠를 스크리닝하기 위한 [컴포넌트](https://github.com/huggingface/diffusers/blob/e55687e1e15407f60f32242027b7bb8170e58266/src/diffusers/pipelines/stable_diffusion/safety_checker.py#L32)
306
+ - `"scheduler"`: [`PNDMScheduler`]의 인스턴스
307
+ - `"text_encoder"`: [`~transformers.CLIPTextModel`]의 인스턴스
308
+ - `"tokenizer"`: a [`~transformers.CLIPTokenizer`]의 인스턴스
309
+ - `"unet"`: [`UNet2DConditionModel`]의 인스턴스
310
+ - `"vae"` [`AutoencoderKL`]의 인스턴스
311
+
312
+ ```json
313
+ StableDiffusionPipeline {
314
+ "feature_extractor": [
315
+ "transformers",
316
+ "CLIPImageProcessor"
317
+ ],
318
+ "safety_checker": [
319
+ "stable_diffusion",
320
+ "StableDiffusionSafetyChecker"
321
+ ],
322
+ "scheduler": [
323
+ "diffusers",
324
+ "PNDMScheduler"
325
+ ],
326
+ "text_encoder": [
327
+ "transformers",
328
+ "CLIPTextModel"
329
+ ],
330
+ "tokenizer": [
331
+ "transformers",
332
+ "CLIPTokenizer"
333
+ ],
334
+ "unet": [
335
+ "diffusers",
336
+ "UNet2DConditionModel"
337
+ ],
338
+ "vae": [
339
+ "diffusers",
340
+ "AutoencoderKL"
341
+ ]
342
+ }
343
+ ```
344
+
345
+ 파이프라인 인스턴스의 컴포넌트들을 [`stable-diffusion-v1-5/stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)의 폴더 구조와 비교해볼 경우, 각각의 컴포넌트마다 별도의 폴더가 있음을 확인할 수 있습니다.
346
+
347
+ ```
348
+ .
349
+ ├── feature_extractor
350
+ │ └── preprocessor_config.json
351
+ ├── model_index.json
352
+ ├── safety_checker
353
+ │ ├── config.json
354
+ │ └── pytorch_model.bin
355
+ ├── scheduler
356
+ │ └── scheduler_config.json
357
+ ├── text_encoder
358
+ │ ├── config.json
359
+ │ └── pytorch_model.bin
360
+ ├── tokenizer
361
+ │ ├── merges.txt
362
+ │ ├── special_tokens_map.json
363
+ │ ├── tokenizer_config.json
364
+ │ └── vocab.json
365
+ ├── unet
366
+ │ ├── config.json
367
+ │ ├── diffusion_pytorch_model.bin
368
+ └── vae
369
+ ├── config.json
370
+ ├── diffusion_pytorch_model.bin
371
+ ```
372
+
373
+ 또한 각각의 컴포넌트들을 파이프라인 인스턴스의 속성으로써 참조할 수 있습니다.
374
+
375
+ ```py
376
+ pipeline.tokenizer
377
+ ```
378
+
379
+ ```python
380
+ CLIPTokenizer(
381
+ name_or_path="/root/.cache/huggingface/hub/models--runwayml--stable-diffusion-v1-5/snapshots/39593d5650112b4cc580433f6b0435385882d819/tokenizer",
382
+ vocab_size=49408,
383
+ model_max_length=77,
384
+ is_fast=False,
385
+ padding_side="right",
386
+ truncation_side="right",
387
+ special_tokens={
388
+ "bos_token": AddedToken("<|startoftext|>", rstrip=False, lstrip=False, single_word=False, normalized=True),
389
+ "eos_token": AddedToken("<|endoftext|>", rstrip=False, lstrip=False, single_word=False, normalized=True),
390
+ "unk_token": AddedToken("<|endoftext|>", rstrip=False, lstrip=False, single_word=False, normalized=True),
391
+ "pad_token": "<|endoftext|>",
392
+ },
393
+ )
394
+ ```
395
+
396
+ 모든 파이프라인은 `model_index.json` 파일을 통해 [`DiffusionPipeline`]에 다음과 같은 정보를 전달합니다.
397
+
398
+ - `_class_name` 는 어떤 파이프라인 클래스를 사용해야 하는지에 대해 알려줍니다.
399
+ - `_diffusers_version`는 어떤 버전의 디퓨저스로 파이프라인 안의 모델들이 만들어졌는지를 알려줍니다.
400
+ - 그 다음은 각각의 컴포넌트들이 어떤 라이브러리의 어떤 클래스로 만들어졌는지에 대해 알려줍니다. (아래 예시에서 `"feature_extractor" : ["transformers", "CLIPImageProcessor"]`의 경우, `feature_extractor` 컴포넌트는 `transformers` 라이브러리의 `CLIPImageProcessor` 클래스를 통해 만들어졌다는 것을 의미합니다.)
401
+
402
+ ```json
403
+ {
404
+ "_class_name": "StableDiffusionPipeline",
405
+ "_diffusers_version": "0.6.0",
406
+ "feature_extractor": [
407
+ "transformers",
408
+ "CLIPImageProcessor"
409
+ ],
410
+ "safety_checker": [
411
+ "stable_diffusion",
412
+ "StableDiffusionSafetyChecker"
413
+ ],
414
+ "scheduler": [
415
+ "diffusers",
416
+ "PNDMScheduler"
417
+ ],
418
+ "text_encoder": [
419
+ "transformers",
420
+ "CLIPTextModel"
421
+ ],
422
+ "tokenizer": [
423
+ "transformers",
424
+ "CLIPTokenizer"
425
+ ],
426
+ "unet": [
427
+ "diffusers",
428
+ "UNet2DConditionModel"
429
+ ],
430
+ "vae": [
431
+ "diffusers",
432
+ "AutoencoderKL"
433
+ ]
434
+ }
435
+ ```
436
+
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/loading_adapters.md ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # 어댑터 불러오기
14
+
15
+ [[open-in-colab]]
16
+
17
+ 특정 물체의 이미지 또는 특정 스타일의 이미지를 생성하도록 diffusion 모델을 개인화하기 위한 몇 가지 [학습](../training/overview) 기법이 있습니다. 이러한 학습 방법은 각각 다른 유형의 어댑터를 생성합니다. 일부 어댑터는 완전히 새로운 모델을 생성하는 반면, 다른 어댑터는 임베딩 또는 가중치의 작은 부분만 수정합니다. 이는 각 어댑터의 로딩 프로세스도 다르다는 것을 의미합니다.
18
+
19
+ 이 가이드에서는 DreamBooth, textual inversion 및 LoRA 가중치를 불러오는 방법을 설명합니다.
20
+
21
+ > [!TIP]
22
+ > 사용할 체크포인트와 임베딩은 [Stable Diffusion Conceptualizer](https://huggingface.co/spaces/sd-concepts-library/stable-diffusion-conceptualizer), [LoRA the Explorer](https://huggingface.co/spaces/multimodalart/LoraTheExplorer), [Diffusers Models Gallery](https://huggingface.co/spaces/huggingface-projects/diffusers-gallery)에서 찾아보시기 바랍니다.
23
+
24
+ ## DreamBooth
25
+
26
+ [DreamBooth](https://dreambooth.github.io/)는 물체의 여러 이미지에 대한 *diffusion 모델 전체*를 미세 조정하여 새로운 스타일과 설정으로 해당 물체의 이미지를 생성합니다. 이 방법은 모델이 물체 이미지와 연관시키는 방법을 학습하는 프롬프트에 특수 단어를 사용하는 방식으로 작동합니다. 모든 학습 방법 중에서 드림부스는 전체 체크포인트 모델이기 때문에 파일 크기가 가장 큽니다(보통 몇 GB).
27
+
28
+ Hergé가 그린 단 10개의 이미지로 학습된 [herge_style](https://huggingface.co/sd-dreambooth-library/herge-style) 체크포인트를 불러와 해당 스타일의 이미지를 생성해 보겠습니다. 이 모델이 작동하려면 체크포인트를 트리거하는 프롬프트에 특수 단어 `herge_style`을 포함시켜야 합니다:
29
+
30
+ ```py
31
+ from diffusers import AutoPipelineForText2Image
32
+ import torch
33
+
34
+ pipeline = AutoPipelineForText2Image.from_pretrained("sd-dreambooth-library/herge-style", torch_dtype=torch.float16).to("cuda")
35
+ prompt = "A cute herge_style brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration"
36
+ image = pipeline(prompt).images[0]
37
+ image
38
+ ```
39
+
40
+ <div class="flex justify-center">
41
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_dreambooth.png" />
42
+ </div>
43
+
44
+ ## Textual inversion
45
+
46
+ [Textual inversion](https://textual-inversion.github.io/)은 DreamBooth와 매우 유사하며 몇 개의 이미지만으로 특정 개념(스타일, 개체)을 생성하는 diffusion 모델을 개인화할 수도 있습니다. 이 방법은 프롬프트에 특정 단어를 입력하면 해당 이미지를 나타내는 새로운 임베딩을 학습하고 찾아내는 방식으로 작동합니다. 결과적으로 diffusion 모델 가중치는 동일하게 유지되고 훈련 프로세스는 비교적 작은(수 KB) 파일을 생성합니다.
47
+
48
+ Textual inversion은 임베딩을 생성하기 때문에 DreamBooth처럼 단독으로 사용할 수 없으며 또 다른 모델이 필요합니다.
49
+
50
+ ```py
51
+ from diffusers import AutoPipelineForText2Image
52
+ import torch
53
+
54
+ pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16).to("cuda")
55
+ ```
56
+
57
+ 이제 [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] 메서드를 사용하여 textual inversion 임베딩을 불러와 이미지를 생성할 수 있습니다. [sd-concepts-library/gta5-artwork](https://huggingface.co/sd-concepts-library/gta5-artwork) 임베딩을 불러와 보겠습니다. 이를 트리거하려면 프롬프트에 특수 단어 `<gta5-artwork>`를 포함시켜야 합니다:
58
+
59
+ ```py
60
+ pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
61
+ prompt = "A cute brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration, <gta5-artwork> style"
62
+ image = pipeline(prompt).images[0]
63
+ image
64
+ ```
65
+
66
+ <div class="flex justify-center">
67
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_txt_embed.png" />
68
+ </div>
69
+
70
+ Textual inversion은 또한 바람직하지 않은 사물에 대해 *네거티브 임베딩*을 생성하여 모델이 흐릿한 이미지나 손의 추가 손가락과 같은 바람직하지 않은 사물이 포함된 이미지를 생성하지 못하도록 학습할 수도 있습니다. 이는 프롬프트를 빠르게 개선하는 것이 쉬운 방법이 될 수 있습니다. 이는 이전과 같이 임베딩을 [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`]으로 불러오지만 이번에는 두 개의 매개변수가 더 필요합니다:
71
+
72
+ - `weight_name`: 파일이 특정 이름의 🤗 Diffusers 형식으로 저장된 경우이거나 파일이 A1111 형식으로 저장된 경우, 불러올 가중치 파일을 지정합니다.
73
+ - `token`: 임베딩을 트리거하기 위해 프롬프트에서 사용할 특수 단어를 지정합니다.
74
+
75
+ [sayakpaul/EasyNegative-test](https://huggingface.co/sayakpaul/EasyNegative-test) 임베딩을 불러와 보겠습니다:
76
+
77
+ ```py
78
+ pipeline.load_textual_inversion(
79
+ "sayakpaul/EasyNegative-test", weight_name="EasyNegative.safetensors", token="EasyNegative"
80
+ )
81
+ ```
82
+
83
+ 이제 `token`을 사용해 네거티브 임베딩이 있는 이미지를 생성할 수 있습니다:
84
+
85
+ ```py
86
+ prompt = "A cute brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration, EasyNegative"
87
+ negative_prompt = "EasyNegative"
88
+
89
+ image = pipeline(prompt, negative_prompt=negative_prompt, num_inference_steps=50).images[0]
90
+ image
91
+ ```
92
+
93
+ <div class="flex justify-center">
94
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_neg_embed.png" />
95
+ </div>
96
+
97
+ ## LoRA
98
+
99
+ [Low-Rank Adaptation (LoRA)](https://huggingface.co/papers/2106.09685)은 속도가 빠르고 파일 크기가 (수백 MB로) 작기 때문에 널리 사용되는 학습 기법입니다. 이 가이드의 다른 방법과 마찬가지로, LoRA는 몇 장의 이미지만으로 새로운 스타일을 학습하도록 모델을 학습시킬 수 있습니다. 이는 diffusion 모델에 새로운 가중치를 삽입한 다음 전체 모델 대신 새로운 가중치만 학습시키는 방식으로 작동합니다. 따라서 LoRA를 더 빠르게 학습시키고 더 쉽게 저장할 수 있습니다.
100
+
101
+ > [!TIP]
102
+ > LoRA는 다른 학습 방법과 함께 사용할 수 있는 매우 일반적인 학습 기법입니다. 예를 들어, DreamBooth와 LoRA로 모델을 학습하는 것이 일반적입니다. 또한 새롭고 고유한 이미지를 생성하기 위해 여러 개의 LoRA를 불러오고 병합하는 것이 점점 더 일반화되고 있습니다. 병합은 이 불러오기 가이드의 범위를 벗어나므로 자세한 내용은 심층적인 [LoRA 병합](merge_loras) 가이드에서 확인할 수 있습니다.
103
+
104
+ LoRA는 다른 모델과 함께 사용해야 합니다:
105
+
106
+ ```py
107
+ from diffusers import AutoPipelineForText2Image
108
+ import torch
109
+
110
+ pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16).to("cuda")
111
+ ```
112
+
113
+ 그리고 [`~loaders.LoraLoaderMixin.load_lora_weights`] 메서드를 사용하여 [ostris/super-cereal-sdxl-lora](https://huggingface.co/ostris/super-cereal-sdxl-lora) 가중치를 불러오고 리포지토리에서 가중치 파일명을 지정합니다:
114
+
115
+ ```py
116
+ pipeline.load_lora_weights("ostris/super-cereal-sdxl-lora", weight_name="cereal_box_sdxl_v1.safetensors")
117
+ prompt = "bears, pizza bites"
118
+ image = pipeline(prompt).images[0]
119
+ image
120
+ ```
121
+
122
+ <div class="flex justify-center">
123
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_lora.png" />
124
+ </div>
125
+
126
+ [`~loaders.LoraLoaderMixin.load_lora_weights`] 메서드는 LoRA 가중치를 UNet과 텍스트 인코더에 모두 불러옵니다. 이 메서드는 해당 케이스에서 LoRA를 불러오는 데 선호되는 방식입니다:
127
+
128
+ - LoRA 가중치에 UNet 및 텍스트 인코더에 대한 별도의 식별자가 없는 경우
129
+ - LoRA 가중치에 UNet과 텍스트 인코더에 대한 별도의 식별자가 있는 경우
130
+
131
+ 하지만 LoRA 가중치만 UNet에 로드해야 하는 경우에는 [`~loaders.UNet2DConditionLoadersMixin.load_attn_procs`] 메서드를 사용할 수 있습니다. [jbilcke-hf/sdxl-cinematic-1](https://huggingface.co/jbilcke-hf/sdxl-cinematic-1) LoRA를 불러와 보겠습니다:
132
+
133
+ ```py
134
+ from diffusers import AutoPipelineForText2Image
135
+ import torch
136
+
137
+ pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16).to("cuda")
138
+ pipeline.unet.load_attn_procs("jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors")
139
+
140
+ # 프롬프트에서 cnmt를 사용하여 LoRA를 트리거합니다.
141
+ prompt = "A cute cnmt eating a slice of pizza, stunning color scheme, masterpiece, illustration"
142
+ image = pipeline(prompt).images[0]
143
+ image
144
+ ```
145
+
146
+ <div class="flex justify-center">
147
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_attn_proc.png" />
148
+ </div>
149
+
150
+ LoRA 가중치를 언로드하려면 [`~loaders.LoraLoaderMixin.unload_lora_weights`] 메서드를 사용하여 LoRA 가중치를 삭제하고 모델을 원래 가중치로 복���합니다:
151
+
152
+ ```py
153
+ pipeline.unload_lora_weights()
154
+ ```
155
+
156
+ ### LoRA 가중치 스케일 조정하기
157
+
158
+ [`~loaders.LoraLoaderMixin.load_lora_weights`] 및 [`~loaders.UNet2DConditionLoadersMixin.load_attn_procs`] 모두 `cross_attention_kwargs={"scale": 0.5}` 파라미터를 전달하여 얼마나 LoRA 가중치를 사용할지 조정할 수 있습니다. 값이 `0`이면 기본 모델 가중치만 사용하는 것과 같고, 값이 `1`이면 완전히 미세 조정된 LoRA를 사용하는 것과 같습니다.
159
+
160
+ 레이어당 사용되는 LoRA 가중치의 양을 보다 세밀하게 제어하려면 [`~loaders.LoraLoaderMixin.set_adapters`]를 사용하여 각 레이어의 가중치를 얼마만큼 조정할지 지정하는 딕셔너리를 전달할 수 있습니다.
161
+ ```python
162
+ pipe = ... # 파이프라인 생성
163
+ pipe.load_lora_weights(..., adapter_name="my_adapter")
164
+ scales = {
165
+ "text_encoder": 0.5,
166
+ "text_encoder_2": 0.5, # 파이프에 두 번째 텍스트 인코더가 있는 경우에만 사용 가능
167
+ "unet": {
168
+ "down": 0.9, # down 부분의 모든 트랜스포머는 스케일 0.9를 사용
169
+ # "mid" # 이 예제에서는 "mid"가 지정되지 않았으므로 중간 부분의 모든 트랜스포머는 기본 스케일 1.0을 사용
170
+ "up": {
171
+ "block_0": 0.6, # # up의 0번째 블록에 있는 3개의 트랜스포머는 모두 스케일 0.6을 사용
172
+ "block_1": [0.4, 0.8, 1.0], # up의 첫 번째 블록에 있는 3개의 트랜스포머는 각각 스케일 0.4, 0.8, 1.0을 사용
173
+ }
174
+ }
175
+ }
176
+ pipe.set_adapters("my_adapter", scales)
177
+ ```
178
+
179
+ 이는 여러 어댑터에서도 작동합니다. 방법은 [이 가이드](https://huggingface.co/docs/diffusers/tutorials/using_peft_for_inference#customize-adapters-strength)를 참조하세요.
180
+
181
+ > [!WARNING]
182
+ > 현재 [`~loaders.LoraLoaderMixin.set_adapters`]는 어텐션 가중치의 스케일링만 지원합니다. LoRA에 다른 부분(예: resnets or down-/upsamplers)이 있는 경우 1.0의 스케일을 유지합니다.
183
+
184
+ ### Kohya와 TheLastBen
185
+
186
+ 커뮤니티에서 인기 있는 다른 LoRA trainer로는 [Kohya](https://github.com/kohya-ss/sd-scripts/)와 [TheLastBen](https://github.com/TheLastBen/fast-stable-diffusion)의 trainer가 있습니다. 이 trainer들은 🤗 Diffusers가 훈련한 것과는 다른 LoRA 체크포인트를 생성하지만, 같은 방식으로 불러올 수 있습니다.
187
+
188
+ <hfoptions id="other-trainers">
189
+ <hfoption id="Kohya">
190
+
191
+ Kohya LoRA를 불러오기 위해, 예시로 [Civitai](https://civitai.com/)에서 [Blueprintify SD XL 1.0](https://civitai.com/models/150986/blueprintify-sd-xl-10) 체크포인트를 다운로드합니다:
192
+
193
+ ```sh
194
+ !wget https://civitai.com/api/download/models/168776 -O blueprintify-sd-xl-10.safetensors
195
+ ```
196
+
197
+ LoRA 체크포인트를 [`~loaders.LoraLoaderMixin.load_lora_weights`] 메서드로 불러오고 `weight_name` 파라미터에 파일명을 지정합니다:
198
+
199
+ ```py
200
+ from diffusers import AutoPipelineForText2Image
201
+ import torch
202
+
203
+ pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16).to("cuda")
204
+ pipeline.load_lora_weights("path/to/weights", weight_name="blueprintify-sd-xl-10.safetensors")
205
+ ```
206
+
207
+ 이미지를 생성합니다:
208
+
209
+ ```py
210
+ # LoRA를 트리거하기 위해 bl3uprint를 프롬프트에 사용
211
+ prompt = "bl3uprint, a highly detailed blueprint of the eiffel tower, explaining how to build all parts, many txt, blueprint grid backdrop"
212
+ image = pipeline(prompt).images[0]
213
+ image
214
+ ```
215
+
216
+ > [!WARNING]
217
+ > Kohya LoRA를 🤗 Diffusers와 함께 사용할 때 몇 가지 제한 사항이 있습니다:
218
+ >
219
+ > - [여기](https://github.com/huggingface/diffusers/pull/4287/#issuecomment-1655110736)에 설명된 여러 가지 이유로 인해 이미지가 ComfyUI와 같은 UI에서 생성된 이미지와 다르게 보일 수 있습니다.
220
+ > - [LyCORIS 체크포인트](https://github.com/KohakuBlueleaf/LyCORIS)가 완전히 지원되지 않습니다. [`~loaders.LoraLoaderMixin.load_lora_weights`] 메서드는 LoRA 및 LoCon 모듈로 LyCORIS 체크포인트를 불러올 수 있지만, Hada 및 LoKR은 지원되지 않습니다.
221
+
222
+ </hfoption>
223
+ <hfoption id="TheLastBen">
224
+
225
+ TheLastBen에서 체크포인트를 불러오는 방법은 매우 유사합니다. 예를 들어, [TheLastBen/William_Eggleston_Style_SDXL](https://huggingface.co/TheLastBen/William_Eggleston_Style_SDXL) 체크포인트를 불러오려면:
226
+
227
+ ```py
228
+ from diffusers import AutoPipelineForText2Image
229
+ import torch
230
+
231
+ pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16).to("cuda")
232
+ pipeline.load_lora_weights("TheLastBen/William_Eggleston_Style_SDXL", weight_name="wegg.safetensors")
233
+
234
+ # LoRA를 트리거하기 위해 william eggleston를 프롬프트에 사용
235
+ prompt = "a house by william eggleston, sunrays, beautiful, sunlight, sunrays, beautiful"
236
+ image = pipeline(prompt=prompt).images[0]
237
+ image
238
+ ```
239
+
240
+ </hfoption>
241
+ </hfoptions>
242
+
243
+ ## IP-Adapter
244
+
245
+ [IP-Adapter](https://ip-adapter.github.io/)는 모든 diffusion 모델에 이미지 프롬프트를 사용할 수 있는 경량 어댑터입니다. 이 어댑터는 이미지와 텍스트 feature의 cross-attention 레이어를 분리하여 작동합니다. 다른 모든 모델 컴포넌트튼 freeze되고 UNet의 embedded 이미지 features만 학습됩니다. 따라서 IP-Adapter 파일은 일반적으로 최대 100MB에 불과합니다.
246
+
247
+ 다양한 작업과 구체적인 사용 사례에 IP-Adapter를 사용하는 방법에 대한 자세한 내용은 [IP-Adapter](../using-diffusers/ip_adapter) 가이드에서 확인할 수 있습니다.
248
+
249
+ > [!TIP]
250
+ > Diffusers는 현재 가장 많이 사용되는 일부 파이프라인에 대해서만 IP-Adapter를 지원합니다. 멋진 사용 사례가 있는 지원되지 않는 파이프라인에 IP-Adapter를 통합하고 싶다면 언제든지 기능 요청을 여세요!
251
+ > 공식 IP-Adapter 체크포인트는 [h94/IP-Adapter](https://huggingface.co/h94/IP-Adapter)에서 확인할 수 있습니다.
252
+
253
+ 시작하려면 Stable Diffusion 체크포인트를 불러오세요.
254
+
255
+ ```py
256
+ from diffusers import AutoPipelineForText2Image
257
+ import torch
258
+ from diffusers.utils import load_image
259
+
260
+ pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16).to("cuda")
261
+ ```
262
+
263
+ 그런 다음 IP-Adapter 가중치를 불러와 [`~loaders.IPAdapterMixin.load_ip_adapter`] 메서드를 사용하여 파이프라인에 추가합니다.
264
+
265
+ ```py
266
+ pipeline.load_ip_adapter("h94/IP-Adapter", subfolder="models", weight_name="ip-adapter_sd15.bin")
267
+ ```
268
+
269
+ 불러온 뒤, 이미지 및 텍스트 프롬프트가 있는 파이프라인을 사용하여 이미지 생성 프로세스를 가이드할 수 있습니다.
270
+
271
+ ```py
272
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_neg_embed.png")
273
+ generator = torch.Generator(device="cpu").manual_seed(33)
274
+ images = pipeline(
275
+     prompt='best quality, high quality, wearing sunglasses',
276
+     ip_adapter_image=image,
277
+     negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
278
+     num_inference_steps=50,
279
+     generator=generator,
280
+ ).images[0]
281
+ images
282
+ ```
283
+
284
+ <div class="flex justify-center">
285
+     <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/ip-bear.png" />
286
+ </div>
287
+
288
+ ### IP-Adapter Plus
289
+
290
+ IP-Adapter는 이미지 인코더를 사용하여 이미지 feature를 생성합니다. IP-Adapter 리포지토리에 `image_encoder` 하위 폴더가 있는 경우, 이미지 인코더가 자동으로 불러와 파이프라인에 등록됩니다. 그렇지 않은 경우, [`~transformers.CLIPVisionModelWithProjection`] 모델을 사용하여 이미지 인코더를 명시적으로 불러와 파이프라인에 전달해야 합니다.
291
+
292
+ 이는 ViT-H 이미지 인코더를 사용하는 *IP-Adapter Plus* 체크포인트에 해당하는 케이스입니다.
293
+
294
+ ```py
295
+ from transformers import CLIPVisionModelWithProjection
296
+
297
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
298
+ "h94/IP-Adapter",
299
+ subfolder="models/image_encoder",
300
+ torch_dtype=torch.float16
301
+ )
302
+
303
+ pipeline = AutoPipelineForText2Image.from_pretrained(
304
+ "stabilityai/stable-diffusion-xl-base-1.0",
305
+ image_encoder=image_encoder,
306
+ torch_dtype=torch.float16
307
+ ).to("cuda")
308
+
309
+ pipeline.load_ip_adapter("h94/IP-Adapter", subfolder="sdxl_models", weight_name="ip-adapter-plus_sdxl_vit-h.safetensors")
310
+ ```
311
+
312
+ ### IP-Adapter Face ID 모델
313
+
314
+ IP-Adapter FaceID 모델은 CLIP 이미지 임베딩 대신 `insightface`에서 생성한 이미지 임베딩을 사용하는 실험적인 IP Adapter입니다. 이러한 모델 중 일부는 LoRA를 사용하여 ID 일관성을 개선하기도 합니다.
315
+ 이러한 모델을 사용하려면 `insightface`와 해당 요구 사항을 모두 설치해야 합니다.
316
+
317
+ > [!WARNING]
318
+ > InsightFace 사전학습된 모델은 비상업적 연구 목적으로만 사용할 수 있으므로, IP-Adapter-FaceID 모델은 연구 목적으로만 릴리즈되었으며 상업적 용도로는 사용할 수 없습니다.
319
+
320
+ ```py
321
+ pipeline = AutoPipelineForText2Image.from_pretrained(
322
+ "stabilityai/stable-diffusion-xl-base-1.0",
323
+ torch_dtype=torch.float16
324
+ ).to("cuda")
325
+
326
+ pipeline.load_ip_adapter("h94/IP-Adapter-FaceID", subfolder=None, weight_name="ip-adapter-faceid_sdxl.bin", image_encoder_folder=None)
327
+ ```
328
+
329
+ 두 가지 IP 어댑터 FaceID Plus 모델 중 하나를 사용하려는 경우, 이 모델들은 더 나은 사실감을 얻기 위해 `insightface`와 CLIP 이미지 임베딩을 모두 사용하므로, CLIP 이미지 인코더도 불러와야 합니다.
330
+
331
+ ```py
332
+ from transformers import CLIPVisionModelWithProjection
333
+
334
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
335
+ "laion/CLIP-ViT-H-14-laion2B-s32B-b79K",
336
+ torch_dtype=torch.float16,
337
+ )
338
+
339
+ pipeline = AutoPipelineForText2Image.from_pretrained(
340
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
341
+ image_encoder=image_encoder,
342
+ torch_dtype=torch.float16
343
+ ).to("cuda")
344
+
345
+ pipeline.load_ip_adapter("h94/IP-Adapter-FaceID", subfolder=None, weight_name="ip-adapter-faceid-plus_sd15.bin")
346
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/other-formats.md ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # 다양한 Stable Diffusion 포맷 불러오기
14
+
15
+ Stable Diffusion 모델들은 학습 및 저장된 프레임워크와 다운로드 위치에 따라 다양한 형식으로 제공됩니다. 이러한 형식을 🤗 Diffusers에서 사용할 수 있도록 변환하면 추론을 위한 [다양한 스케줄러 사용](schedulers), 사용자 지정 파이프라인 구축, 추론 속도 최적화를 위한 다양한 기법과 방법 등 라이브러리에서 지원하는 모든 기능을 사용할 수 있습니다.
16
+
17
+ > [!TIP]
18
+ > 우리는 `.safetensors` 형식을 추천합니다. 왜냐하면 기존의 pickled 파일은 취약하고 머신에서 코드를 실행할 때 악용될 수 있는 것에 비해 훨씬 더 안전합니다. (safetensors 불러오기 가이드에서 자세히 알아보세요.)
19
+
20
+ 이 가이드에서는 다른 Stable Diffusion 형식을 🤗 Diffusers와 호환되도록 변환하는 방법을 설명합니다.
21
+
22
+ ## PyTorch .ckpt
23
+
24
+ 체크포인트 또는 `.ckpt` 형식은 일반적으로 모델을 저장하는 데 사용됩니다. `.ckpt` 파일은 전체 모델을 포함하며 일반적으로 크기가 몇 GB입니다. `.ckpt` 파일을 [~StableDiffusionPipeline.from_ckpt] 메서드를 사용하여 직접 불러와서 사용할 수도 있지만, 일반적으로 두 가지 형식을 모두 사용할 수 있도록 `.ckpt` 파일을 🤗 Diffusers로 변환하는 것이 더 좋습니다.
25
+
26
+ `.ckpt` 파일을 변환하는 두 가지 옵션이 있습니다. Space를 사용하여 체크포인트를 변환하거나 스크립트를 사용하여 `.ckpt` 파일을 변환합니다.
27
+
28
+ ### Space로 변환하기
29
+
30
+ `.ckpt` 파일을 변환하는 가장 쉽고 편리한 방법은 SD에서 Diffusers로 스페이스를 사용하는 것입니다. Space의 지침에 따라 .ckpt 파일을 변환 할 수 있습니다.
31
+
32
+ 이 접근 방식은 기본 모델에서는 잘 작동하지만 더 많은 사용자 정의 모델에서는 어려움을 겪을 수 있습니다. 빈 pull request나 오류를 반환하면 Space가 실패한 것입니다.
33
+ 이 경우 스크립트를 사용하여 `.ckpt` 파일을 변환해 볼 수 있습니다.
34
+
35
+ ### 스크립트로 변환하기
36
+
37
+ 🤗 Diffusers는 `.ckpt`  파일 변환을 위한 변환 스크립트를 제공합니다. 이 접근 방식은 위의 Space보다 더 안정적입니다.
38
+
39
+ 시작하기 전에 스크립트를 실행할 🤗 Diffusers의 로컬 클론(clone)이 있는지 확인하고 Hugging Face 계정에 로그인하여 pull request를 열고 변환된 모델을 허브에 푸시할 수 있도록 하세요.
40
+
41
+ ```bash
42
+ hf auth login
43
+ ```
44
+
45
+ 스크립트를 사용하려면:
46
+
47
+ 1. 변환하려는 `.ckpt`  파일이 포함된 리포지토리를 Git으로 클론(clone)합니다.
48
+
49
+ 이 예제에서는 TemporalNet .ckpt 파일을 변환해 보겠습니다:
50
+
51
+ ```bash
52
+ git lfs install
53
+ git clone https://huggingface.co/CiaraRowles/TemporalNet
54
+ ```
55
+
56
+ 2. 체크포인트를 변환할 리포지토리에서 pull request를 엽니다:
57
+
58
+ ```bash
59
+ cd TemporalNet && git fetch origin refs/pr/13:pr/13
60
+ git checkout pr/13
61
+ ```
62
+
63
+ 3. 변환 스크립트에서 구성할 입력 인수는 여러 가지가 있지만 가장 중요한 인수는 다음과 같습니다:
64
+
65
+ - `checkpoint_path`: 변환할 `.ckpt` 파일의 경로를 입력합니다.
66
+ - `original_config_file`: 원래 아키텍처의 구성을 정의하는 YAML 파일입니다. 이 파일을 찾을 수 없는 경우 `.ckpt` 파일을 찾은 GitHub 리포지토리에서 YAML 파일을 검색해 보세요.
67
+ - `dump_path`: 변환된 모델의 경로
68
+
69
+ 예를 들어, TemporalNet 모델은 Stable Diffusion v1.5 및 ControlNet 모델이기 때문에 ControlNet 리포지토리에서 cldm_v15.yaml 파일을 가져올 수 있습니다.
70
+
71
+ 4. 이제 스크립트를 실행하여 .ckpt 파일을 변환할 수 있습니다:
72
+
73
+ ```bash
74
+ python ../diffusers/scripts/convert_original_stable_diffusion_to_diffusers.py --checkpoint_path temporalnetv3.ckpt --original_config_file cldm_v15.yaml --dump_path ./ --controlnet
75
+ ```
76
+
77
+ 5. 변환이 완료되면 변환된 모델을 업로드하고 결과물을 pull request [pull request](https://huggingface.co/CiaraRowles/TemporalNet/discussions/13)를 테스트하세요!
78
+
79
+ ```bash
80
+ git push origin pr/13:refs/pr/13
81
+ ```
82
+
83
+ ## **Keras .pb or .h5**
84
+
85
+ 🧪 이 기능은 실험적인 기능입니다. 현재로서는 Stable Diffusion v1 체크포인트만 변환 KerasCV Space에서 지원됩니다.
86
+
87
+ [KerasCV](https://keras.io/keras_cv/)는 [Stable Diffusion](https://github.com/keras-team/keras-cv/blob/master/keras_cv/models/stable_diffusion)  v1 및 v2에 대한 학습을 지원합니다. 그러나 추론 및 배포를 위한 Stable Diffusion 모델 실험을 제한적으로 지원하는 반면, 🤗 Diffusers는 다양한 [noise schedulers](https://huggingface.co/docs/diffusers/using-diffusers/schedulers), [flash attention](https://huggingface.co/docs/diffusers/optimization/xformers), and [other optimization techniques](https://huggingface.co/docs/diffusers/optimization/fp16) 등 이러한 목적을 위한 보다 완벽한 기능을 갖추고 있습니다.
88
+
89
+ [Convert KerasCV](https://huggingface.co/spaces/sayakpaul/convert-kerascv-sd-diffusers) Space 변환은 `.pb` 또는 `.h5`을 PyTorch로 변환한 다음, 추론할 수 있도록 [`StableDiffusionPipeline`] 으로 감싸서 준비합니다. 변환된 체크포인트는 Hugging Face Hub의 리포지토리에 저장됩니다.
90
+
91
+ 예제로, textual-inversion으로 학습된 `[sayakpaul/textual-inversion-kerasio](https://huggingface.co/sayakpaul/textual-inversion-kerasio/tree/main)` 체크포인트를 변환해 보겠습니다. 이것은 특수 토큰  `<my-funny-cat>`을 사용하여 고양이로 이미지를 개인화합니다.
92
+
93
+ KerasCV Space 변환에서는 다음을 입력할 수 있습니다:
94
+
95
+ - Hugging Face 토큰.
96
+ - UNet 과 텍스트 인코더(text encoder) 가중치를 다운로드하는 경로입니다. 모델을 어떻게 학습할지 방식에 따라, UNet과 텍스트 인코더의 경로를 모두 제공할 필요는 없습니다. 예를 들어, textual-inversion에는 텍스트 인코더의 임베딩만 필요하고 텍스트-이미지(text-to-image) 모델 변환에는 UNet 가중치만 필요합니다.
97
+ - Placeholder 토큰은 textual-inversion 모델에만 적용됩니다.
98
+ - `output_repo_prefix`는 변환된 모델이 저장되는 리포지토리의 이름입니다.
99
+
100
+ **Submit** (제출) 버튼을 클릭하면 KerasCV 체크포인트가 자동으로 변환됩니다! 체크포인트가 성공적으로 변환되면, 변환된 체크포인트가 포함된 새 리포지토리로 연결되는 링크가 표시됩니다. 새 리포지토리로 연결되는 링크를 따라가면 변환된 모델을 사용해 볼 수 있는 추론 위젯이 포함된 모델 카드가 생성된 KerasCV Space 변환을 확인할 수 있습니다.
101
+
102
+ 코드를 사용하여 추론을 실행하려면 모델 카드의 오른쪽 상단 모서리에 있는 **Use in Diffusers**  버튼을 클릭하여 예시 코드를 복사하여 붙여넣습니다:
103
+
104
+ ```py
105
+ from diffusers import DiffusionPipeline
106
+
107
+ pipeline = DiffusionPipeline.from_pretrained("sayakpaul/textual-inversion-cat-kerascv_sd_diffusers_pipeline")
108
+ ```
109
+
110
+ 그러면 다음과 같은 이미지를 생성할 수 있습니다:
111
+
112
+ ```py
113
+ from diffusers import DiffusionPipeline
114
+
115
+ pipeline = DiffusionPipeline.from_pretrained("sayakpaul/textual-inversion-cat-kerascv_sd_diffusers_pipeline")
116
+ pipeline.to("cuda")
117
+
118
+ placeholder_token = "<my-funny-cat-token>"
119
+ prompt = f"two {placeholder_token} getting married, photorealistic, high quality"
120
+ image = pipeline(prompt, num_inference_steps=50).images[0]
121
+ ```
122
+
123
+ ## **A1111 LoRA files**
124
+
125
+ [Automatic1111](https://github.com/AUTOMATIC1111/stable-diffusion-webui) (A1111)은 Stable Diffusion을 위해 널리 사용되는 웹 UI로, [Civitai](https://civitai.com/) 와 같은 모델 공유 플랫폼을 지원합니다. 특히 LoRA 기법으로 학습된 모델은 학습 속도가 빠르고 완전히 파인튜닝된 모델보다 파일 크기가 훨씬 작기 때문에 인기가 높습니다.
126
+
127
+ 🤗 Diffusers는 [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`]:를 사용하여 A1111 LoRA 체크포인트 불러오기를 지원합니다:
128
+
129
+ ```py
130
+ from diffusers import DiffusionPipeline, UniPCMultistepScheduler
131
+ import torch
132
+
133
+ pipeline = DiffusionPipeline.from_pretrained(
134
+ "andite/anything-v4.0", torch_dtype=torch.float16, safety_checker=None
135
+ ).to("cuda")
136
+ pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config)
137
+ ```
138
+
139
+ Civitai에서 LoRA 체크포인트를 다운로드하세요; 이 예제에서는  [Howls Moving Castle,Interior/Scenery LoRA (Ghibli Stlye)](https://civitai.com/models/14605?modelVersionId=19998) 체크포인트를 사용했지만, 어떤 LoRA 체크포인트든 자유롭게 사용해 보세요!
140
+
141
+ ```bash
142
+ !wget https://civitai.com/api/download/models/19998 -O howls_moving_castle.safetensors
143
+ ```
144
+
145
+ 메서드를 사용하여 파이프라인에 LoRA 체크포인트를 불러옵니다:
146
+
147
+ ```py
148
+ pipeline.load_lora_weights(".", weight_name="howls_moving_castle.safetensors")
149
+ ```
150
+
151
+ 이제 파이프라인을 사용하여 이미지를 생성할 수 있습니다:
152
+
153
+ ```py
154
+ prompt = "masterpiece, illustration, ultra-detailed, cityscape, san francisco, golden gate bridge, california, bay area, in the snow, beautiful detailed starry sky"
155
+ negative_prompt = "lowres, cropped, worst quality, low quality, normal quality, artifacts, signature, watermark, username, blurry, more than one bridge, bad architecture"
156
+
157
+ images = pipeline(
158
+ prompt=prompt,
159
+ negative_prompt=negative_prompt,
160
+ width=512,
161
+ height=512,
162
+ num_inference_steps=25,
163
+ num_images_per_prompt=4,
164
+ generator=torch.manual_seed(0),
165
+ ).images
166
+ ```
167
+
168
+ 마지막으로, 디스플레이에 이미지를 표시하는 헬퍼 함수를 만듭니다:
169
+
170
+ ```py
171
+ from PIL import Image
172
+
173
+
174
+ def image_grid(imgs, rows=2, cols=2):
175
+ w, h = imgs[0].size
176
+ grid = Image.new("RGB", size=(cols * w, rows * h))
177
+
178
+ for i, img in enumerate(imgs):
179
+ grid.paste(img, box=(i % cols * w, i // cols * h))
180
+ return grid
181
+
182
+
183
+ image_grid(images)
184
+ ```
185
+
186
+ <div class="flex justify-center">
187
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/a1111-lora-sf.png" />
188
+ </div>
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/push_to_hub.md ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # 파일들을 Hub로 푸시하기
14
+
15
+ [[open-in-colab]]
16
+
17
+ 🤗 Diffusers는 모델, 스케줄러 또는 파이프라인을 Hub에 업로드할 수 있는 [`~diffusers.utils.PushToHubMixin`]을 제공합니다. 이는 Hub에 당신의 파일을 저장하는 쉬운 방법이며, 다른 사람들과 작업을 공유할 수도 있습니다. 실제적으로 [`~diffusers.utils.PushToHubMixin`]가 동작하는 방식은 다음과 같습니다:
18
+
19
+ 1. Hub에 리포지토리를 생성합니다.
20
+ 2. 나중에 다시 불러올 수 있도록 모델, 스케줄러 또는 파이프라인 파일을 저장합니다.
21
+ 3. 이러한 파일이 포함된 폴더를 Hub에 업로드합니다.
22
+
23
+ 이 가이드는 [`~diffusers.utils.PushToHubMixin`]을 사용하여 Hub에 파일을 업로드하는 방법을 보여줍니다.
24
+
25
+ 먼저 액세스 [토큰](https://huggingface.co/settings/tokens)으로 Hub 계정에 로그인해야 합니다:
26
+
27
+ ```py
28
+ from huggingface_hub import notebook_login
29
+
30
+ notebook_login()
31
+ ```
32
+
33
+ ## 모델
34
+
35
+ 모델을 허브에 푸시하려면 [`~diffusers.utils.PushToHubMixin.push_to_hub`]를 호출하고 Hub에 저장할 모델의 리포지토리 id를 지정합니다:
36
+
37
+ ```py
38
+ from diffusers import ControlNetModel
39
+
40
+ controlnet = ControlNetModel(
41
+ block_out_channels=(32, 64),
42
+ layers_per_block=2,
43
+ in_channels=4,
44
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
45
+ cross_attention_dim=32,
46
+ conditioning_embedding_out_channels=(16, 32),
47
+ )
48
+ controlnet.push_to_hub("my-controlnet-model")
49
+ ```
50
+
51
+ 모델의 경우 Hub에 푸시할 가중치의 [*변형*](loading#checkpoint-variants)을 지정할 수도 있습니다. 예를 들어, `fp16` 가중치를 푸시하려면 다음과 같이 하세요:
52
+
53
+ ```py
54
+ controlnet.push_to_hub("my-controlnet-model", variant="fp16")
55
+ ```
56
+
57
+ [`~diffusers.utils.PushToHubMixin.push_to_hub`] 함수는 모델의 `config.json` 파일을 저장하고 가중치는 `safetensors` 형식으로 자동으로 저장됩니다.
58
+
59
+ 이제 Hub의 리포지토리에서 모델을 다시 불러올 수 있습니다:
60
+
61
+ ```py
62
+ model = ControlNetModel.from_pretrained("your-namespace/my-controlnet-model")
63
+ ```
64
+
65
+ ## 스케줄러
66
+
67
+ 스케줄러를 허브에 푸시하려면 [`~diffusers.utils.PushToHubMixin.push_to_hub`]를 호출하고 Hub에 저장할 스케줄러의 리포지토리 id를 지정합니다:
68
+
69
+ ```py
70
+ from diffusers import DDIMScheduler
71
+
72
+ scheduler = DDIMScheduler(
73
+ beta_start=0.00085,
74
+ beta_end=0.012,
75
+ beta_schedule="scaled_linear",
76
+ clip_sample=False,
77
+ set_alpha_to_one=False,
78
+ )
79
+ scheduler.push_to_hub("my-controlnet-scheduler")
80
+ ```
81
+
82
+ [`~diffusers.utils.PushToHubMixin.push_to_hub`] 함수는 스케줄러의 `scheduler_config.json` 파일을 지정된 리포지토리에 저장합니다.
83
+
84
+ 이제 허브의 리포지토리에서 스케줄러를 다시 불러올 수 있습니다:
85
+
86
+ ```py
87
+ scheduler = DDIMScheduler.from_pretrained("your-namepsace/my-controlnet-scheduler")
88
+ ```
89
+
90
+ ## 파이프라인
91
+
92
+ 모든 컴포넌트가 포함된 전체 파이프라인을 Hub로 푸시할 수도 있습니다. 예를 들어, 원하는 파라미터로 [`StableDiffusionPipeline`]의 컴포넌트들을 초기화합니다:
93
+
94
+ ```py
95
+ from diffusers import (
96
+ UNet2DConditionModel,
97
+ AutoencoderKL,
98
+ DDIMScheduler,
99
+ StableDiffusionPipeline,
100
+ )
101
+ from transformers import CLIPTextModel, CLIPTextConfig, CLIPTokenizer
102
+
103
+ unet = UNet2DConditionModel(
104
+ block_out_channels=(32, 64),
105
+ layers_per_block=2,
106
+ sample_size=32,
107
+ in_channels=4,
108
+ out_channels=4,
109
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
110
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
111
+ cross_attention_dim=32,
112
+ )
113
+
114
+ scheduler = DDIMScheduler(
115
+ beta_start=0.00085,
116
+ beta_end=0.012,
117
+ beta_schedule="scaled_linear",
118
+ clip_sample=False,
119
+ set_alpha_to_one=False,
120
+ )
121
+
122
+ vae = AutoencoderKL(
123
+ block_out_channels=[32, 64],
124
+ in_channels=3,
125
+ out_channels=3,
126
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
127
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
128
+ latent_channels=4,
129
+ )
130
+
131
+ text_encoder_config = CLIPTextConfig(
132
+ bos_token_id=0,
133
+ eos_token_id=2,
134
+ hidden_size=32,
135
+ intermediate_size=37,
136
+ layer_norm_eps=1e-05,
137
+ num_attention_heads=4,
138
+ num_hidden_layers=5,
139
+ pad_token_id=1,
140
+ vocab_size=1000,
141
+ )
142
+ text_encoder = CLIPTextModel(text_encoder_config)
143
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
144
+ ```
145
+
146
+ 모든 컴포넌트들을 [`StableDiffusionPipeline`]에 전달하고 [`~diffusers.utils.PushToHubMixin.push_to_hub`]를 호출하여 파이프라인을 Hub로 푸시합니다:
147
+
148
+ ```py
149
+ components = {
150
+ "unet": unet,
151
+ "scheduler": scheduler,
152
+ "vae": vae,
153
+ "text_encoder": text_encoder,
154
+ "tokenizer": tokenizer,
155
+ "safety_checker": None,
156
+ "feature_extractor": None,
157
+ }
158
+
159
+ pipeline = StableDiffusionPipeline(**components)
160
+ pipeline.push_to_hub("my-pipeline")
161
+ ```
162
+
163
+ [`~diffusers.utils.PushToHubMixin.push_to_hub`] 함수는 각 컴포넌트를 리포지토리의 하위 폴더에 저장합니다. 이제 Hub의 리포지토리에서 파이프라인을 다시 불러올 수 있습니다:
164
+
165
+ ```py
166
+ pipeline = StableDiffusionPipeline.from_pretrained("your-namespace/my-pipeline")
167
+ ```
168
+
169
+ ## 비공개
170
+
171
+ 모델, 스케줄러 또는 파이프라인 파일들을 비공개로 두려면 [`~diffusers.utils.PushToHubMixin.push_to_hub`] 함수에서 `private=True`를 설정하세요:
172
+
173
+ ```py
174
+ controlnet.push_to_hub("my-controlnet-model-private", private=True)
175
+ ```
176
+
177
+ 비공개 리포지토리는 본인만 볼 수 있으며 다른 사용자는 리포지토리를 복제할 수 없고 리포지토리가 검색 결과에 표시되지 않습니다. 사용자가 비공개 리포지토리의 URL을 가지고 있더라도 `404 - Sorry, we can't find the page you are looking for`라는 메시지가 표시됩니다. 비공개 리포지토리에서 모델을 로드하려면 [로그인](https://huggingface.co/docs/huggingface_hub/quick-start#login) 상태여야 합니다.
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/schedulers.md ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # 스케줄러
14
+
15
+ diffusion 파이프라인은 diffusion 모델, 스케줄러 등의 컴포넌트들로 구성됩니다. 그리고 파이프라인 안의 일부 컴포넌트를 다른 컴포넌트로 교체하는 식의 커스터마이징 역시 가능합니다. 이와 같은 컴포넌트 커스터마이징의 가장 대표적인 예시가 바로 [스케줄러](../api/schedulers/overview.md)를 교체하는 것입니다.
16
+
17
+
18
+
19
+ 스케쥴러는 다음과 같이 diffusion 시스템의 전반적인 디노이징 프로세스를 정의합니다.
20
+
21
+ - 디노이징 스텝을 얼마나 가져가야 할까?
22
+ - 확률적으로(stochastic) 혹은 확정적으로(deterministic)?
23
+ - 디노이징 된 샘플을 찾아내기 위해 어떤 알고리즘을 사용해야 할까?
24
+
25
+ 이러한 프로세스는 다소 난해하고, 디노이징 속도와 디노이징 퀄리티 사이의 트레이드 오프를 정의해야 하는 문제가 될 수 있습니다. 주어진 파이프라인에 어떤 스케줄러가 가장 적합한지를 정량적으로 판단하는 것은 매우 어려운 일입니다. 이로 인해 일단 해당 스케줄러를 직접 사용하여, 생성되는 이미지를 직접 눈으로 보며, 정성적으로 성능을 판단해보는 것이 추천되곤 합니다.
26
+
27
+
28
+
29
+
30
+
31
+ ## 파이프라인 불러오기
32
+
33
+ 먼저 스테이블 diffusion 파이프라인을 불러오도록 해보겠습니다. 물론 스테이블 diffusion을 사용하기 위해서는, 허깅페이스 허브에 등록된 사용자여야 하며, 관련 [라이센스](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)에 동의해야 한다는 점을 잊지 말아주세요.
34
+
35
+ *역자 주: 다만, 현재 신규로 생성한 허깅페이스 계정에 대해서는 라이센스 동의를 요구하지 않는 것으로 보입니다!*
36
+
37
+ ```python
38
+ from huggingface_hub import login
39
+ from diffusers import DiffusionPipeline
40
+ import torch
41
+
42
+ # first we need to login with our access token
43
+ login()
44
+
45
+ # Now we can download the pipeline
46
+ pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16)
47
+ ```
48
+
49
+ 다음으로, GPU로 이동합니다.
50
+
51
+ ```python
52
+ pipeline.to("cuda")
53
+ ```
54
+
55
+
56
+
57
+
58
+
59
+ ## 스케줄러 액세스
60
+
61
+ 스케줄러는 언제나 파이프라인의 컴포넌트로서 존재하며, 일반적으로 파이프라인 인스턴스 내에 `scheduler`라는 이름의 속성(property)으로 정의되어 있습니다.
62
+
63
+ ```python
64
+ pipeline.scheduler
65
+ ```
66
+
67
+ **Output**:
68
+
69
+ ```
70
+ PNDMScheduler {
71
+ "_class_name": "PNDMScheduler",
72
+ "_diffusers_version": "0.8.0.dev0",
73
+ "beta_end": 0.012,
74
+ "beta_schedule": "scaled_linear",
75
+ "beta_start": 0.00085,
76
+ "clip_sample": false,
77
+ "num_train_timesteps": 1000,
78
+ "set_alpha_to_one": false,
79
+ "skip_prk_steps": true,
80
+ "steps_offset": 1,
81
+ "trained_betas": null
82
+ }
83
+ ```
84
+
85
+ 출력 결과를 통해, 우리는 해당 스케줄러가 [`PNDMScheduler`]의 인스턴스라는 것을 알 수 있습니다. 이제 [`PNDMScheduler`]와 다른 스케줄러들의 성능을 비교해보도록 하겠습니다. 먼저 테스트에 사용할 프롬프트를 다음과 같이 정의해보도록 하겠습니다.
86
+
87
+ ```python
88
+ prompt = "A photograph of an astronaut riding a horse on Mars, high resolution, high definition."
89
+ ```
90
+
91
+ 다음으로 유사한 이미지 생성을 보장하기 위해서, 다음과 같이 랜덤시드를 고정해주도록 하겠습니다.
92
+
93
+ ```python
94
+ generator = torch.Generator(device="cuda").manual_seed(8)
95
+ image = pipeline(prompt, generator=generator).images[0]
96
+ image
97
+ ```
98
+
99
+ <p align="center">
100
+ <br>
101
+ <img src="https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/diffusers_docs/astronaut_pndm.png" width="400"/>
102
+ <br>
103
+ </p>
104
+
105
+
106
+
107
+
108
+ ## 스케줄러 교체하기
109
+
110
+ 다음으로 파이프라인의 스케줄러를 다른 스케줄러로 교체하는 방법에 대해 알아보겠습니다. 모든 스케줄러는 [`SchedulerMixin.compatibles`]라는 속성(property)을 갖고 있습니다. 해당 속성은 **호환 가능한** 스케줄러들에 대한 정보를 담고 있습니다.
111
+
112
+ ```python
113
+ pipeline.scheduler.compatibles
114
+ ```
115
+
116
+ **Output**:
117
+
118
+ ```
119
+ [diffusers.schedulers.scheduling_lms_discrete.LMSDiscreteScheduler,
120
+ diffusers.schedulers.scheduling_ddim.DDIMScheduler,
121
+ diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler,
122
+ diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler,
123
+ diffusers.schedulers.scheduling_pndm.PNDMScheduler,
124
+ diffusers.schedulers.scheduling_ddpm.DDPMScheduler,
125
+ diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler]
126
+ ```
127
+
128
+ 호환되는 스케줄러들을 살펴보면 아래와 같습니다.
129
+
130
+ - [`LMSDiscreteScheduler`],
131
+ - [`DDIMScheduler`],
132
+ - [`DPMSolverMultistepScheduler`],
133
+ - [`EulerDiscreteScheduler`],
134
+ - [`PNDMScheduler`],
135
+ - [`DDPMScheduler`],
136
+ - [`EulerAncestralDiscreteScheduler`].
137
+
138
+ 앞서 정의했던 프롬프트를 사용해서 각각의 스케줄러들을 비교해보도록 하겠습니다.
139
+
140
+ 먼저 파이프라인 안의 스케줄러를 바꾸기 위해 [`ConfigMixin.config`] 속성과 [`ConfigMixin.from_config`] 메서드를 활용해보려고 합니다.
141
+
142
+
143
+
144
+ ```python
145
+ pipeline.scheduler.config
146
+ ```
147
+
148
+ **Output**:
149
+
150
+ ```
151
+ FrozenDict([('num_train_timesteps', 1000),
152
+ ('beta_start', 0.00085),
153
+ ('beta_end', 0.012),
154
+ ('beta_schedule', 'scaled_linear'),
155
+ ('trained_betas', None),
156
+ ('skip_prk_steps', True),
157
+ ('set_alpha_to_one', False),
158
+ ('steps_offset', 1),
159
+ ('_class_name', 'PNDMScheduler'),
160
+ ('_diffusers_version', '0.8.0.dev0'),
161
+ ('clip_sample', False)])
162
+ ```
163
+
164
+ 기존 스케줄러의 config를 호환 가능한 다른 스케줄러에 이식하는 것 역시 가능합니다.
165
+
166
+ 다음 예시는 기존 스케줄러(`pipeline.scheduler`)를 다른 종류의 스케줄러(`DDIMScheduler`)로 바꾸는 코드입니다. 기존 스케줄러가 갖고 있던 config를 `.from_config` 메서드의 인자로 전달하는 것을 확인할 수 있습니다.
167
+
168
+ ```python
169
+ from diffusers import DDIMScheduler
170
+
171
+ pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
172
+ ```
173
+
174
+
175
+
176
+ 이제 파이프라인을 실행해서 두 스케줄러 사이의 생성된 이미지의 퀄리티를 비교해봅시다.
177
+
178
+ ```python
179
+ generator = torch.Generator(device="cuda").manual_seed(8)
180
+ image = pipeline(prompt, generator=generator).images[0]
181
+ image
182
+ ```
183
+
184
+ <p align="center">
185
+ <br>
186
+ <img src="https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/diffusers_docs/astronaut_ddim.png" width="400"/>
187
+ <br>
188
+ </p>
189
+
190
+
191
+
192
+
193
+ ## 스케줄러들 비교해보기
194
+
195
+ 지금까지는 [`PNDMScheduler`]와 [`DDIMScheduler`] 스케줄러를 실행해보았습니다. 아직 비교해볼 스케줄러들이 더 많이 남아있으니 계속 비교해보도록 하겠습니다.
196
+
197
+
198
+
199
+ [`LMSDiscreteScheduler`]을 일반적으로 더 좋은 결과를 보여줍니다.
200
+
201
+ ```python
202
+ from diffusers import LMSDiscreteScheduler
203
+
204
+ pipeline.scheduler = LMSDiscreteScheduler.from_config(pipeline.scheduler.config)
205
+
206
+ generator = torch.Generator(device="cuda").manual_seed(8)
207
+ image = pipeline(prompt, generator=generator).images[0]
208
+ image
209
+ ```
210
+
211
+ <p align="center">
212
+ <br>
213
+ <img src="https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/diffusers_docs/astronaut_lms.png" width="400"/>
214
+ <br>
215
+ </p>
216
+
217
+
218
+ [`EulerDiscreteScheduler`]와 [`EulerAncestralDiscreteScheduler`] 고작 30번의 inference step만으로도 높은 퀄리티의 이미지를 생성하는 것을 알 수 있습니다.
219
+
220
+ ```python
221
+ from diffusers import EulerDiscreteScheduler
222
+
223
+ pipeline.scheduler = EulerDiscreteScheduler.from_config(pipeline.scheduler.config)
224
+
225
+ generator = torch.Generator(device="cuda").manual_seed(8)
226
+ image = pipeline(prompt, generator=generator, num_inference_steps=30).images[0]
227
+ image
228
+ ```
229
+
230
+ <p align="center">
231
+ <br>
232
+ <img src="https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/diffusers_docs/astronaut_euler_discrete.png" width="400"/>
233
+ <br>
234
+ </p>
235
+
236
+
237
+ ```python
238
+ from diffusers import EulerAncestralDiscreteScheduler
239
+
240
+ pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(pipeline.scheduler.config)
241
+
242
+ generator = torch.Generator(device="cuda").manual_seed(8)
243
+ image = pipeline(prompt, generator=generator, num_inference_steps=30).images[0]
244
+ image
245
+ ```
246
+
247
+ <p align="center">
248
+ <br>
249
+ <img src="https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/diffusers_docs/astronaut_euler_ancestral.png" width="400"/>
250
+ <br>
251
+ </p>
252
+
253
+
254
+ 지금 이 문서를 작성하는 현시점 기준에선, [`DPMSolverMultistepScheduler`]가 시간 대비 가장 좋은 품질의 이미지를 생성하는 것 같습니다. 20번 정도의 스텝만으로도 실행될 수 있습니다.
255
+
256
+
257
+
258
+ ```python
259
+ from diffusers import DPMSolverMultistepScheduler
260
+
261
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
262
+
263
+ generator = torch.Generator(device="cuda").manual_seed(8)
264
+ image = pipeline(prompt, generator=generator, num_inference_steps=20).images[0]
265
+ image
266
+ ```
267
+
268
+ <p align="center">
269
+ <br>
270
+ <img src="https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/diffusers_docs/astronaut_dpm.png" width="400"/>
271
+ <br>
272
+ </p>
273
+
274
+
275
+ 보시다시피 생성된 이미지들은 매우 비슷하고, 비슷한 퀄리티를 보이는 것 같습��다. 실제로 어떤 스케줄러를 선택할 것인가는 종종 특정 이용 사례에 기반해서 결정되곤 합니다. 결국 여러 종류의 스케줄러를 직접 실행시켜보고 눈으로 직접 비교해서 판단하는 게 좋은 선택일 것 같습니다.
276
+
277
+
278
+
279
+ ## Flax에서 스케줄러 교체하기
280
+
281
+ JAX/Flax 사용자인 경우 기본 파이프라인 스케줄러를 변경할 수도 있습니다. 다음은 Flax Stable Diffusion 파이프라인과 초고속 [DDPM-Solver++ 스케줄러를](../api/schedulers/multistep_dpm_solver) 사용하여 추론을 실행하는 방법에 대한 예시입니다 .
282
+
283
+ ```Python
284
+ import jax
285
+ import numpy as np
286
+ from flax.jax_utils import replicate
287
+ from flax.training.common_utils import shard
288
+
289
+ from diffusers import FlaxStableDiffusionPipeline, FlaxDPMSolverMultistepScheduler
290
+
291
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
292
+ scheduler, scheduler_state = FlaxDPMSolverMultistepScheduler.from_pretrained(
293
+ model_id,
294
+ subfolder="scheduler"
295
+ )
296
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
297
+ model_id,
298
+ scheduler=scheduler,
299
+ variant="bf16",
300
+ dtype=jax.numpy.bfloat16,
301
+ )
302
+ params["scheduler"] = scheduler_state
303
+
304
+ # Generate 1 image per parallel device (8 on TPUv2-8 or TPUv3-8)
305
+ prompt = "a photo of an astronaut riding a horse on mars"
306
+ num_samples = jax.device_count()
307
+ prompt_ids = pipeline.prepare_inputs([prompt] * num_samples)
308
+
309
+ prng_seed = jax.random.PRNGKey(0)
310
+ num_inference_steps = 25
311
+
312
+ # shard inputs and rng
313
+ params = replicate(params)
314
+ prng_seed = jax.random.split(prng_seed, jax.device_count())
315
+ prompt_ids = shard(prompt_ids)
316
+
317
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
318
+ images = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
319
+ ```
320
+
321
+ > [!WARNING]
322
+ > 다음 Flax 스케줄러는 *아직* Flax Stable Diffusion 파이프라인과 호환되지 않습니다.
323
+ >
324
+ > - `FlaxLMSDiscreteScheduler`
325
+ > - `FlaxDDPMScheduler`
326
+
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/sdxl_turbo.md ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Stable Diffusion XL Turbo
14
+
15
+ [[open-in-colab]]
16
+
17
+ SDXL Turbo는 adversarial time-distilled(적대적 시간 전이) [Stable Diffusion XL](https://huggingface.co/papers/2307.01952)(SDXL) 모델로, 단 한 번의 스텝만으로 추론을 실행할 수 있습니다.
18
+
19
+ 이 가이드에서는 text-to-image와 image-to-image를 위한 SDXL-Turbo를 사용하는 방법을 설명합니다.
20
+
21
+ 시작하기 전에 다음 라이브러리가 설치되어 있는지 확인하세요:
22
+
23
+ ```py
24
+ # Colab에서 필요한 라이브러리를 설치하기 위해 주석을 제외하세요
25
+ #!pip install -q diffusers transformers accelerate
26
+ ```
27
+
28
+ ## 모델 체크포인트 불러오기
29
+
30
+ 모델 가중치는 Hub의 별도 하위 폴더 또는 로컬에 저장할 수 있으며, 이 경우 [`~StableDiffusionXLPipeline.from_pretrained`] 메서드를 사용해야 합니다:
31
+
32
+ ```py
33
+ from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
34
+ import torch
35
+
36
+ pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16")
37
+ pipeline = pipeline.to("cuda")
38
+ ```
39
+
40
+ 또한 [`~StableDiffusionXLPipeline.from_single_file`] 메서드를 사용하여 허브 또는 로컬에서 단일 파일 형식(`.ckpt` 또는 `.safetensors`)으로 저장된 모델 체크포인트를 불러올 수도 있습니다:
41
+
42
+ ```py
43
+ from diffusers import StableDiffusionXLPipeline
44
+ import torch
45
+
46
+ pipeline = StableDiffusionXLPipeline.from_single_file(
47
+ "https://huggingface.co/stabilityai/sdxl-turbo/blob/main/sd_xl_turbo_1.0_fp16.safetensors", torch_dtype=torch.float16)
48
+ pipeline = pipeline.to("cuda")
49
+ ```
50
+
51
+ ## Text-to-image
52
+
53
+ Text-to-image의 경우 텍스트 프롬프트를 전달합니다. 기본적으로 SDXL Turbo는 512x512 이미지를 생성하며, 이 해상도에서 최상의 결과를 제공합니다. `height` 및 `width` 매개 변수를 768x768 또는 1024x1024로 설정할 수 있지만 이 경우 품질 저하를 예상할 수 있습니다.
54
+
55
+ 모델이 `guidance_scale` 없이 학습되었으므로 이를 0.0으로 설정해 비활성화해야 합니다. 단일 추론 스텝만으로도 고품질 이미지를 생성할 수 있습니다.
56
+ 스텝 수를 2, 3 또는 4로 늘리면 이미지 품질이 향상됩니다.
57
+
58
+ ```py
59
+ from diffusers import AutoPipelineForText2Image
60
+ import torch
61
+
62
+ pipeline_text2image = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16")
63
+ pipeline_text2image = pipeline_text2image.to("cuda")
64
+
65
+ prompt = "A cinematic shot of a baby racoon wearing an intricate italian priest robe."
66
+
67
+ image = pipeline_text2image(prompt=prompt, guidance_scale=0.0, num_inference_steps=1).images[0]
68
+ image
69
+ ```
70
+
71
+ <div class="flex justify-center">
72
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/sdxl-turbo-text2img.png" alt="generated image of a racoon in a robe"/>
73
+ </div>
74
+
75
+ ## Image-to-image
76
+
77
+ Image-to-image 생성의 경우 `num_inference_steps * strength`가 1보다 크거나 같은지 확인하세요.
78
+ Image-to-image 파이프라인은 아래 예제에서 `0.5 * 2.0 = 1` 스텝과 같이 `int(num_inference_steps * strength)` 스텝으로 실행됩니다.
79
+
80
+ ```py
81
+ from diffusers import AutoPipelineForImage2Image
82
+ from diffusers.utils import load_image, make_image_grid
83
+
84
+ # 체크포인트를 불러올 때 추가 메모리 소모를 피하려면 from_pipe를 사용하세요.
85
+ pipeline = AutoPipelineForImage2Image.from_pipe(pipeline_text2image).to("cuda")
86
+
87
+ init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png")
88
+ init_image = init_image.resize((512, 512))
89
+
90
+ prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k"
91
+
92
+ image = pipeline(prompt, image=init_image, strength=0.5, guidance_scale=0.0, num_inference_steps=2).images[0]
93
+ make_image_grid([init_image, image], rows=1, cols=2)
94
+ ```
95
+
96
+ <div class="flex justify-center">
97
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/sdxl-turbo-img2img.png" alt="Image-to-image generation sample using SDXL Turbo"/>
98
+ </div>
99
+
100
+ ## SDXL Turbo 속도 훨씬 더 빠르게 하기
101
+
102
+ - PyTorch 버전 2 이상을 사용하는 경우 UNet을 컴파일합니다. 첫 번째 추론 실행은 매우 느리지만 이후 실행은 훨씬 빨라집니다.
103
+
104
+ ```py
105
+ pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
106
+ ```
107
+
108
+ - 기본 VAE를 사용하는 경우, 각 생성 전후에 비용이 많이 드는 `dtype` 변환을 피하기 위해 `float32`로 유지하세요. 이 작업은 첫 생성 이전에 한 번만 수행하면 됩니다:
109
+
110
+ ```py
111
+ pipe.upcast_vae()
112
+ ```
113
+
114
+ 또는, 커뮤니티 회원인 [`@madebyollin`](https://huggingface.co/madebyollin)이 만든 [16비트 VAE](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)를 사용할 수도 있으며, 이는 `float32`로 업캐스트할 필요가 없습니다.
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/shap-e.md ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Shap-E
14
+
15
+ [[open-in-colab]]
16
+
17
+ Shap-E는 비디오 게임 개발, 인테리어 디자인, 건축에 사용할 수 있는 3D 에셋을 생성하기 위한 conditional 모델입니다. 대규모 3D 에셋 데이터셋을 학습되었고, 각 오브젝트의 더 많은 뷰를 렌더링하고 4K point cloud 대신 16K를 생성하도록 후처리합니다. Shap-E 모델은 두 단계로 학습됩니다:
18
+
19
+ 1. 인코더가 3D 에셋의 포인트 클라우드와 렌더링된 뷰를 받아들이고 에셋을 나타내는 implicit functions의 파라미터를 출력합니다.
20
+ 2. 인코더가 생성한 latents를 바탕으로 diffusion 모델을 훈련하여 neural radiance fields(NeRF) 또는 textured 3D 메시를 생성하여 다운스트림 애플리케이션에서 3D 에셋을 더 쉽게 렌더링하고 사용할 수 있도록 합니다.
21
+
22
+ 이 가이드에서는 Shap-E를 사용하여 나만의 3D 에셋을 생성하는 방법을 보입니다!
23
+
24
+ 시작하기 전에 다음 라이브러리가 설치되어 있는지 확인하세요:
25
+
26
+ ```py
27
+ # Colab에서 필요한 라이브러리를 설치하기 위해 주석을 제외하세요
28
+ #!pip install -q diffusers transformers accelerate trimesh
29
+ ```
30
+
31
+ ## Text-to-3D
32
+
33
+ 3D 객체의 gif를 생성하려면 텍스트 프롬프트를 [`ShapEPipeline`]에 전달합니다. 파이프라인은 3D 객체를 생성하는 데 사용되는 이미지 프레임 리스트를 생성합니다.
34
+
35
+ ```py
36
+ import torch
37
+ from diffusers import ShapEPipeline
38
+
39
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
+
41
+ pipe = ShapEPipeline.from_pretrained("openai/shap-e", torch_dtype=torch.float16, variant="fp16")
42
+ pipe = pipe.to(device)
43
+
44
+ guidance_scale = 15.0
45
+ prompt = ["A firecracker", "A birthday cupcake"]
46
+
47
+ images = pipe(
48
+ prompt,
49
+ guidance_scale=guidance_scale,
50
+ num_inference_steps=64,
51
+ frame_size=256,
52
+ ).images
53
+ ```
54
+
55
+ 이제 [`~utils.export_to_gif`] 함수를 사용하여 이미지 프레임 리스트를 3D 객체의 gif로 변환합니다.
56
+
57
+ ```py
58
+ from diffusers.utils import export_to_gif
59
+
60
+ export_to_gif(images[0], "firecracker_3d.gif")
61
+ export_to_gif(images[1], "cake_3d.gif")
62
+ ```
63
+
64
+ <div class="flex gap-4">
65
+ <div>
66
+ <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/firecracker_out.gif"/>
67
+ <figcaption class="mt-2 text-center text-sm text-gray-500">prompt = "A firecracker"</figcaption>
68
+ </div>
69
+ <div>
70
+ <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/cake_out.gif"/>
71
+ <figcaption class="mt-2 text-center text-sm text-gray-500">prompt = "A birthday cupcake"</figcaption>
72
+ </div>
73
+ </div>
74
+
75
+ ## Image-to-3D
76
+
77
+ 다른 이미지로부터 3D 개체를 생성하려면 [`ShapEImg2ImgPipeline`]을 사용합니다. 기존 이미지를 사용하거나 완전히 새로운 이미지를 생성할 수 있습니다. [Kandinsky 2.1](../api/pipelines/kandinsky) 모델을 사용하여 새 이미지를 생성해 보겠습니다.
78
+
79
+ ```py
80
+ from diffusers import DiffusionPipeline
81
+ import torch
82
+
83
+ prior_pipeline = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1-prior", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
84
+ pipeline = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
85
+
86
+ prompt = "A cheeseburger, white background"
87
+
88
+ image_embeds, negative_image_embeds = prior_pipeline(prompt, guidance_scale=1.0).to_tuple()
89
+ image = pipeline(
90
+ prompt,
91
+ image_embeds=image_embeds,
92
+ negative_image_embeds=negative_image_embeds,
93
+ ).images[0]
94
+
95
+ image.save("burger.png")
96
+ ```
97
+
98
+ 치즈버거를 [`ShapEImg2ImgPipeline`]에 전달하여 3D representation을 생성합니다.
99
+
100
+ ```py
101
+ from PIL import Image
102
+ from diffusers import ShapEImg2ImgPipeline
103
+ from diffusers.utils import export_to_gif
104
+
105
+ pipe = ShapEImg2ImgPipeline.from_pretrained("openai/shap-e-img2img", torch_dtype=torch.float16, variant="fp16").to("cuda")
106
+
107
+ guidance_scale = 3.0
108
+ image = Image.open("burger.png").resize((256, 256))
109
+
110
+ images = pipe(
111
+ image,
112
+ guidance_scale=guidance_scale,
113
+ num_inference_steps=64,
114
+ frame_size=256,
115
+ ).images
116
+
117
+ gif_path = export_to_gif(images[0], "burger_3d.gif")
118
+ ```
119
+
120
+ <div class="flex gap-4">
121
+ <div>
122
+ <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/burger_in.png"/>
123
+ <figcaption class="mt-2 text-center text-sm text-gray-500">cheeseburger</figcaption>
124
+ </div>
125
+ <div>
126
+ <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/burger_out.gif"/>
127
+ <figcaption class="mt-2 text-center text-sm text-gray-500">3D cheeseburger</figcaption>
128
+ </div>
129
+ </div>
130
+
131
+ ## 메시 생성하기
132
+
133
+ Shap-E는 다운스트림 애플리케이션에 렌더링할 textured 메시 출력을 생성할 수도 있는 유연한 모델입니다. 이 예제에서는 🤗 Datasets 라이브러리에서 [Dataset viewer](https://huggingface.co/docs/hub/datasets-viewer#dataset-preview)를 사용해 메시 시각화를 지원하는 `glb` 파일로 변환합니다.
134
+
135
+ `output_type` 매개변수를 `"mesh"`로 지정함으로써 [`ShapEPipeline`]과 [`ShapEImg2ImgPipeline`] 모두에 대한 메시 출력을 생성할 수 있습니다:
136
+
137
+ ```py
138
+ import torch
139
+ from diffusers import ShapEPipeline
140
+
141
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
142
+
143
+ pipe = ShapEPipeline.from_pretrained("openai/shap-e", torch_dtype=torch.float16, variant="fp16")
144
+ pipe = pipe.to(device)
145
+
146
+ guidance_scale = 15.0
147
+ prompt = "A birthday cupcake"
148
+
149
+ images = pipe(prompt, guidance_scale=guidance_scale, num_inference_steps=64, frame_size=256, output_type="mesh").images
150
+ ```
151
+
152
+ 메시 출력을 `ply` 파일로 저장하려면 [`~utils.export_to_ply`] 함수를 사용합니다:
153
+
154
+ > [!TIP]
155
+ > 선택적으로 [`~utils.export_to_obj`] 함수를 사용하여 메시 출력을 `obj` 파일로 저장할 수 있습니다. 다양한 형식으로 메시 출력을 저장할 수 있어 다운스트림에서 더욱 유연하게 사용할 수 있습니다!
156
+
157
+ ```py
158
+ from diffusers.utils import export_to_ply
159
+
160
+ ply_path = export_to_ply(images[0], "3d_cake.ply")
161
+ print(f"Saved to folder: {ply_path}")
162
+ ```
163
+
164
+ 그 다음 trimesh 라이브러리를 사용하여 `ply` 파일을 `glb` 파일로 변환할 수 있습니다:
165
+
166
+ ```py
167
+ import trimesh
168
+
169
+ mesh = trimesh.load("3d_cake.ply")
170
+ mesh_export = mesh.export("3d_cake.glb", file_type="glb")
171
+ ```
172
+
173
+ 기본적으로 메시 출력은 아래쪽 시점에 초점이 맞춰져 있지만 회전 변환을 적용하여 기본 시점을 변경할 수 있습니다:
174
+
175
+ ```py
176
+ import trimesh
177
+ import numpy as np
178
+
179
+ mesh = trimesh.load("3d_cake.ply")
180
+ rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
181
+ mesh = mesh.apply_transform(rot)
182
+ mesh_export = mesh.export("3d_cake.glb", file_type="glb")
183
+ ```
184
+
185
+ 메시 파일을 데이터셋 레포지토리에 업로드해 Dataset viewer로 시각화하세요!
186
+
187
+ <div class="flex justify-center">
188
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/3D-cake.gif"/>
189
+ </div>
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/stable_diffusion_jax_how_to.md ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # JAX / Flax에서의 🧨 Stable Diffusion!
14
+
15
+ [[open-in-colab]]
16
+
17
+ 🤗 Hugging Face [Diffusers] (https://github.com/huggingface/diffusers) 는 버전 0.5.1부터 Flax를 지원합니다! 이를 통해 Colab, Kaggle, Google Cloud Platform에서 사용할 수 있는 것처럼 Google TPU에서 초고속 추론이 가능합니다.
18
+
19
+ 이 노트북은 JAX / Flax를 사용해 추론을 실행하는 방법을 보여줍니다. Stable Diffusion의 작동 방식에 대한 자세한 내용을 원하거나 GPU에서 실행하려면 이 [노트북] ](https://huggingface.co/docs/diffusers/stable_diffusion)을 참조하세요.
20
+
21
+ 먼저, TPU 백엔드를 사용하고 있는지 확인합니다. Colab에서 이 노트북을 실행하는 경우, 메뉴에서 런타임을 선택한 다음 "런타임 유형 변경" 옵션을 선택한 다음 하드웨어 가속기 설정에서 TPU를 선택합니다.
22
+
23
+ JAX는 TPU 전용은 아니지만 각 TPU 서버에는 8개의 TPU 가속기가 병렬로 작동하기 때문에 해당 하드웨어에서 더 빛을 발한다는 점은 알아두세요.
24
+
25
+
26
+ ## Setup
27
+
28
+ 먼저 diffusers가 설치되어 있는지 확인합니다.
29
+
30
+ ```bash
31
+ !pip install jax==0.3.25 jaxlib==0.3.25 flax transformers ftfy
32
+ !pip install diffusers
33
+ ```
34
+
35
+ ```python
36
+ import jax.tools.colab_tpu
37
+
38
+ jax.tools.colab_tpu.setup_tpu()
39
+ import jax
40
+ ```
41
+
42
+ ```python
43
+ num_devices = jax.device_count()
44
+ device_type = jax.devices()[0].device_kind
45
+
46
+ print(f"Found {num_devices} JAX devices of type {device_type}.")
47
+ assert (
48
+ "TPU" in device_type
49
+ ), "Available device is not a TPU, please select TPU from Edit > Notebook settings > Hardware accelerator"
50
+ ```
51
+
52
+ ```python out
53
+ Found 8 JAX devices of type Cloud TPU.
54
+ ```
55
+
56
+ 그런 다음 모든 dependencies를 가져옵니다.
57
+
58
+ ```python
59
+ import numpy as np
60
+ import jax
61
+ import jax.numpy as jnp
62
+
63
+ from pathlib import Path
64
+ from jax import pmap
65
+ from flax.jax_utils import replicate
66
+ from flax.training.common_utils import shard
67
+ from PIL import Image
68
+
69
+ from huggingface_hub import notebook_login
70
+ from diffusers import FlaxStableDiffusionPipeline
71
+ ```
72
+
73
+ ## 모델 불러오기
74
+
75
+ TPU 장치는 효율적인 half-float 유형인 bfloat16을 지원합니다. 테스트에는 이 유형을 사용하지만 대신 float32를 사용하여 전체 정밀도(full precision)를 사용할 수도 있습니다.
76
+
77
+ ```python
78
+ dtype = jnp.bfloat16
79
+ ```
80
+
81
+ Flax는 함수형 프레임워크이므로 모델은 무상태(stateless)형이며 매개변수는 모델 외부에 저장됩니다. 사전학습된 Flax 파이프라인을 불러오면 파이프라인 자체와 모델 가중치(또는 매개변수)가 모두 반환됩니다. 저희는 bf16 버전의 가중치를 사용하고 있으므로 유형 경고가 표시되지만 무시해도 됩니다.
82
+
83
+ ```python
84
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
85
+ "CompVis/stable-diffusion-v1-4",
86
+ variant="bf16",
87
+ dtype=dtype,
88
+ )
89
+ ```
90
+
91
+ ## 추론
92
+
93
+ TPU에는 일반적으로 8개의 디바이스가 병렬로 작동하므로 보유한 디바이스 수만큼 프롬프트를 복제합니다. 그런 다음 각각 하나의 이미지 생성을 담당하는 8개의 디바이스에서 한 번에 추론을 수행합니다. 따라서 하나의 칩이 하나의 이미지를 생성하는 데 걸리는 시간과 동일한 시간에 8개의 이미지를 얻을 수 있습니다.
94
+
95
+ 프롬프트를 복제하고 나면 파이프라인의 `prepare_inputs` 함수를 호출하여 토큰화된 텍스트 ID를 얻습니다. 토큰화된 텍스트의 길이는 기본 CLIP 텍스트 모델의 구성에 따라 77토큰으로 설정됩니다.
96
+
97
+ ```python
98
+ prompt = "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of field, close up, split lighting, cinematic"
99
+ prompt = [prompt] * jax.device_count()
100
+ prompt_ids = pipeline.prepare_inputs(prompt)
101
+ prompt_ids.shape
102
+ ```
103
+
104
+ ```python out
105
+ (8, 77)
106
+ ```
107
+
108
+ ### 복사(Replication) 및 정렬화
109
+
110
+ 모델 매개변수와 입력값은 우리가 보유한 8개의 병렬 장치에 복사(Replication)되어야 합니다. 매개변수 딕셔너리는 `flax.jax_utils.replicate`(딕셔너리를 순회하며 가중치의 모양을 변경하여 8번 반복하는 함수)를 사용하여 복사됩니다. 배열은 `shard`를 사용하여 복제됩니다.
111
+
112
+ ```python
113
+ p_params = replicate(params)
114
+ ```
115
+
116
+ ```python
117
+ prompt_ids = shard(prompt_ids)
118
+ prompt_ids.shape
119
+ ```
120
+
121
+ ```python out
122
+ (8, 1, 77)
123
+ ```
124
+
125
+ 이 shape은 8개의 디바이스 각각이 shape `(1, 77)`의 jnp 배열을 입력값으로 받는다는 의미입니다. 즉 1은 디바이스당 batch(배치) 크기입니다. 메모리가 충분한 TPU에서는 한 번에 여러 이미지(칩당)를 생성하려는 경우 1보다 클 수 있습니다.
126
+
127
+ 이미지를 생성할 준비가 거의 완료되었습니다! 이제 생성 함수에 전달할 난수 생성기만 만들면 됩니다. 이것은 난수를 다루는 모든 함수에 난수 생성기가 있어야 한다는, 난수에 대해 매우 진지하고 독단적인 Flax의 표준 절차입니다. 이렇게 하면 여러 분산된 기기에서 훈련할 때에도 재현성이 보장됩니다.
128
+
129
+ 아래 헬퍼 함수는 시드를 사용하여 난수 생성기를 초기화합니다. 동일한 시드를 사용하는 한 정확히 동일한 결과를 얻을 수 있습니다. 나중에 노트북에서 결과를 탐색할 때엔 다른 시드를 자유롭게 사용하세요.
130
+
131
+ ```python
132
+ def create_key(seed=0):
133
+ return jax.random.PRNGKey(seed)
134
+ ```
135
+
136
+ rng를 얻은 다음 8번 '분할'하여 각 디바이스가 다른 제너레이터를 수신하도록 합니다. 따라서 각 디바이스마다 다른 이미지가 생성되며 전체 프로세스를 재현할 수 있습니다.
137
+
138
+ ```python
139
+ rng = create_key(0)
140
+ rng = jax.random.split(rng, jax.device_count())
141
+ ```
142
+
143
+ JAX 코드는 매우 빠르게 실행되는 효율적인 표현으로 컴파일할 수 있습니다. 하지만 후속 호출에서 모든 입력이 동일한 모양을 갖도록 해야 하며, 그렇지 않으면 JAX가 코드를 다시 컴파일해야 하므로 최적화된 속도를 활용할 수 없습니다.
144
+
145
+ `jit = True`를 인수로 전달하면 Flax 파이프라인이 코드를 컴파일할 수 있습니다. 또한 모델이 사용 가능한 8개의 디바이스에서 병렬로 실행되도록 보장합니다.
146
+
147
+ 다음 셀을 처음 실행하면 컴파일하는 데 시간이 오래 걸리지만 이후 호출(입력이 다른 경우에도)은 훨씬 빨라집니다. 예를 들어, 테스트했을 때 TPU v2-8에서 컴파일하는 데 1분 이상 걸리지만 이후 추론 실행에는 약 7초가 걸립니다.
148
+
149
+ ```
150
+ %%time
151
+ images = pipeline(prompt_ids, p_params, rng, jit=True)[0]
152
+ ```
153
+
154
+ ```python out
155
+ CPU times: user 56.2 s, sys: 42.5 s, total: 1min 38s
156
+ Wall time: 1min 29s
157
+ ```
158
+
159
+ 반환된 배열의 shape은 `(8, 1, 512, 512, 3)`입니다. 이를 재구성하여 두 번째 차원을 제거하고 512 × 512 × 3의 이미지 8개를 얻은 다음 PIL로 변환합니다.
160
+
161
+ ```python
162
+ images = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
163
+ images = pipeline.numpy_to_pil(images)
164
+ ```
165
+
166
+ ### 시각화
167
+
168
+ 이미지를 그리드에 표시하는 도우미 함수를 만들어 보겠습니다.
169
+
170
+ ```python
171
+ def image_grid(imgs, rows, cols):
172
+ w, h = imgs[0].size
173
+ grid = Image.new("RGB", size=(cols * w, rows * h))
174
+ for i, img in enumerate(imgs):
175
+ grid.paste(img, box=(i % cols * w, i // cols * h))
176
+ return grid
177
+ ```
178
+
179
+ ```python
180
+ image_grid(images, 2, 4)
181
+ ```
182
+
183
+ ![img](https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/stable_diffusion_jax_how_to_cell_38_output_0.jpeg)
184
+
185
+
186
+ ## 다른 프롬프트 사용
187
+
188
+ 모든 디바이스에서 동일한 프롬프트를 복제할 필요는 없습니다. 프롬프트 2개를 각각 4번씩 생성하거나 한 번에 8개의 서로 다른 프롬프트를 생성하는 등 원하는 것은 무엇이든 할 수 있습니다. 한번 해보세요!
189
+
190
+ 먼저 입력 준비 코드를 편리한 함수로 리팩터링하겠습니다:
191
+
192
+ ```python
193
+ prompts = [
194
+ "Labrador in the style of Hokusai",
195
+ "Painting of a squirrel skating in New York",
196
+ "HAL-9000 in the style of Van Gogh",
197
+ "Times Square under water, with fish and a dolphin swimming around",
198
+ "Ancient Roman fresco showing a man working on his laptop",
199
+ "Close-up photograph of young black woman against urban background, high quality, bokeh",
200
+ "Armchair in the shape of an avocado",
201
+ "Clown astronaut in space, with Earth in the background",
202
+ ]
203
+ ```
204
+
205
+ ```python
206
+ prompt_ids = pipeline.prepare_inputs(prompts)
207
+ prompt_ids = shard(prompt_ids)
208
+
209
+ images = pipeline(prompt_ids, p_params, rng, jit=True).images
210
+ images = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
211
+ images = pipeline.numpy_to_pil(images)
212
+
213
+ image_grid(images, 2, 4)
214
+ ```
215
+
216
+ ![img](https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/stable_diffusion_jax_how_to_cell_43_output_0.jpeg)
217
+
218
+
219
+ ## 병렬화(parallelization)는 어떻게 작동하는가?
220
+
221
+ 앞서 `diffusers` Flax 파이프라인이 모델을 자동으로 컴파일하고 사용 가능한 모든 기기에서 병렬로 실행한다고 말씀드렸습니다. 이제 그 프로세스를 간략하게 살펴보고 작동 방식을 보여드리겠습니다.
222
+
223
+ JAX 병렬화는 여러 가지 방법으로 수행할 수 있습니다. 가장 쉬운 방법은 jax.pmap 함수를 사용하여 단�� 프로그램, 다중 데이터(SPMD) 병렬화를 달성하는 것입니다. 즉, 동일한 코드의 복사본을 각각 다른 데이터 입력에 대해 여러 개 실행하는 것입니다. 더 정교한 접근 방식도 가능하므로 관심이 있으시다면 [JAX 문서](https://jax.readthedocs.io/en/latest/index.html)와 [`pjit` 페이지](https://jax.readthedocs.io/en/latest/jax-101/08-pjit.html?highlight=pjit)에서 이 주제를 살펴보시기 바랍니다!
224
+
225
+ `jax.pmap`은 두 가지 기능을 수행합니다:
226
+
227
+ - `jax.jit()`를 호출한 것처럼 코드를 컴파일(또는 `jit`)합니다. 이 작업은 `pmap`을 호출할 때가 아니라 pmapped 함수가 처음 호출될 때 수행됩니다.
228
+ - 컴파일된 코드가 사용 가능한 모든 기기에서 병렬로 실행되도록 합니다.
229
+
230
+ 작동 방식을 보여드리기 위해 이미지 생성을 실행하는 비공개 메서드인 파이프라인의 `_generate` 메서드를 `pmap`합니다. 이 메서드는 향후 `Diffusers` 릴리스에서 이름이 변경되거나 제거될 수 있다는 점에 유의하세요.
231
+
232
+ ```python
233
+ p_generate = pmap(pipeline._generate)
234
+ ```
235
+
236
+ `pmap`을 사용한 후 준비된 함수 `p_generate`는 개념적으로 다음을 수행합니다:
237
+ * 각 장치에서 기본 함수 `pipeline._generate`의 복사본을 호출합니다.
238
+ * 각 장치에 입력 인수의 다른 부분을 보냅니다. 이것이 바로 샤딩이 사용되는 이유입니다. 이 경우 `prompt_ids`의 shape은 `(8, 1, 77, 768)`입니다. 이 배열은 8개로 분할되고 `_generate`의 각 복사본은 `(1, 77, 768)`의 shape을 가진 입력을 받게 됩니다.
239
+
240
+ 병렬로 호출된다는 사실을 완전히 무시하고 `_generate`를 코딩할 수 있습니다. batch(배치) 크기(이 예제에서는 `1`)와 코드에 적합한 차원만 신경 쓰면 되며, 병렬로 작동하기 위해 아무것도 변경할 필요가 없습니다.
241
+
242
+ 파이프라인 호출을 사용할 때와 마찬가지로, 다음 셀을 처음 실행할 때는 시간이 걸리지만 그 이후에는 훨씬 빨라집니다.
243
+
244
+ ```
245
+ %%time
246
+ images = p_generate(prompt_ids, p_params, rng)
247
+ images = images.block_until_ready()
248
+ images.shape
249
+ ```
250
+
251
+ ```python out
252
+ CPU times: user 1min 15s, sys: 18.2 s, total: 1min 34s
253
+ Wall time: 1min 15s
254
+ ```
255
+
256
+ ```python
257
+ images.shape
258
+ ```
259
+
260
+ ```python out
261
+ (8, 1, 512, 512, 3)
262
+ ```
263
+
264
+ JAX는 비동기 디스패치를 사용하고 가능한 한 빨리 제어권을 Python 루프에 반환하기 때문에 추론 시간을 정확하게 측정하기 위해 `block_until_ready()`를 사용합니다. 아직 구체화되지 않은 계산 결과를 사용하려는 경우 자동으로 차단이 수행되므로 코드에서 이 함수를 사용할 필요가 없습니다.
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/svd.md ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Stable Video Diffusion
14
+
15
+ [[open-in-colab]]
16
+
17
+ [Stable Video Diffusion (SVD)](https://huggingface.co/papers/2311.15127)은 입력 이미지에 맞춰 2~4초 분량의 고해상도(576x1024) 비디오를 생성할 수 있는 강력한 image-to-video 생성 모델입니다.
18
+
19
+ 이 가이드에서는 SVD를 사용하여 이미지에서 짧은 동영상을 생성하는 방법을 설명합니다.
20
+
21
+ 시작하기 전에 다음 라이브러리가 설치되어 있는지 확인하세요:
22
+
23
+ ```py
24
+ !pip install -q -U diffusers transformers accelerate
25
+ ```
26
+
27
+ 이 모델에는 [SVD](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid)와 [SVD-XT](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid-xt) 두 가지 종류가 있습니다. SVD 체크포인트는 14개의 프레임을 생성하도록 학습되었고, SVD-XT 체크포인트는 25개의 프레임을 생성하도록 파인튜닝되었습니다.
28
+
29
+ 이 가이드에서는 SVD-XT 체크포인트를 사용합니다.
30
+
31
+ ```python
32
+ import torch
33
+
34
+ from diffusers import StableVideoDiffusionPipeline
35
+ from diffusers.utils import load_image, export_to_video
36
+
37
+ pipe = StableVideoDiffusionPipeline.from_pretrained(
38
+ "stabilityai/stable-video-diffusion-img2vid-xt", torch_dtype=torch.float16, variant="fp16"
39
+ )
40
+ pipe.enable_model_cpu_offload()
41
+
42
+ # Conditioning 이미지 불러오기
43
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/svd/rocket.png")
44
+ image = image.resize((1024, 576))
45
+
46
+ generator = torch.manual_seed(42)
47
+ frames = pipe(image, decode_chunk_size=8, generator=generator).frames[0]
48
+
49
+ export_to_video(frames, "generated.mp4", fps=7)
50
+ ```
51
+
52
+ <div class="flex gap-4">
53
+ <div>
54
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/svd/rocket.png"/>
55
+ <figcaption class="mt-2 text-center text-sm text-gray-500">"source image of a rocket"</figcaption>
56
+ </div>
57
+ <div>
58
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/svd/output_rocket.gif"/>
59
+ <figcaption class="mt-2 text-center text-sm text-gray-500">"generated video from source image"</figcaption>
60
+ </div>
61
+ </div>
62
+
63
+ ## torch.compile
64
+
65
+ UNet을 [컴파일](../optimization/torch2.0#torchcompile)하면 메모리 사용량이 살짝 증가하지만, 20~25%의 속도 향상을 얻을 수 있습니다.
66
+
67
+ ```diff
68
+ - pipe.enable_model_cpu_offload()
69
+ + pipe.to("cuda")
70
+ + pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
71
+ ```
72
+
73
+ ## 메모리 사용량 줄이기
74
+
75
+ 비디오 생성은 기본적으로 배치 크기가 큰 text-to-image 생성과 유사하게 'num_frames'를 한 번에 생성하기 때문에 메모리 사용량이 매우 높습니다. 메모리 사용량을 줄이기 위해 추론 속도와 메모리 사용량을 절충하는 여러 가지 옵션이 있습니다:
76
+
77
+ - 모델 오프로링 활성화: 파이프라인의 각 구성 요소가 더 이상 필요하지 않을 때 CPU로 오프로드됩니다.
78
+ - Feed-forward chunking 활성화: feed-forward 레이어가 배치 크기가 큰 단일 feed-forward를 실행하는 대신 루프로 반복해서 실행됩니다.
79
+ - `decode_chunk_size` 감소: VAE가 프레임들을 한꺼번에 디코딩하는 대신 chunk 단위로 디코딩합니다. `decode_chunk_size=1`을 설정하면 한 번에 한 프레임씩 디코딩하고 최소한의 메모리만 사용하지만(GPU 메모리에 따라 이 값을 조정하는 것이 좋습니다), 동영상에 약간의 깜박임이 발생할 수 있습니다.
80
+
81
+ ```diff
82
+ - pipe.enable_model_cpu_offload()
83
+ - frames = pipe(image, decode_chunk_size=8, generator=generator).frames[0]
84
+ + pipe.enable_model_cpu_offload()
85
+ + pipe.unet.enable_forward_chunking()
86
+ + frames = pipe(image, decode_chunk_size=2, generator=generator, num_frames=25).frames[0]
87
+ ```
88
+
89
+ 이러한 모든 방법들을 사용하면 메모리 사용량이 8GAM VRAM보다 적을 것입니다.
90
+
91
+ ## Micro-conditioning
92
+
93
+ Stable Diffusion Video는 또한 이미지 conditoning 외에도 micro-conditioning을 허용하므로 생성된 비디오를 더 잘 제어할 수 있습니다:
94
+
95
+ - `fps`: 생성된 비디오의 초당 프레임 수입니다.
96
+ - `motion_bucket_id`: 생성된 동영상에 사용할 모션 버킷 아이디입니다. 생성된 동영상의 모션을 제어하는 데 사용할 수 있습니다. 모션 버킷 ��이디를 늘리면 생성되는 동영상의 모션이 증가합니다.
97
+ - `noise_aug_strength`: Conditioning 이미지에 추가되는 노이즈의 양입니다. 값이 클수록 비디오가 conditioning 이미지와 덜 유사해집니다. 이 값을 높이면 생성된 비디오의 움직임도 증가합니다.
98
+
99
+ 예를 들어, 모션이 더 많은 동영상을 생성하려면 `motion_bucket_id` 및 `noise_aug_strength` micro-conditioning 파라미터를 사용합니다:
100
+
101
+ ```python
102
+ import torch
103
+
104
+ from diffusers import StableVideoDiffusionPipeline
105
+ from diffusers.utils import load_image, export_to_video
106
+
107
+ pipe = StableVideoDiffusionPipeline.from_pretrained(
108
+ "stabilityai/stable-video-diffusion-img2vid-xt", torch_dtype=torch.float16, variant="fp16"
109
+ )
110
+ pipe.enable_model_cpu_offload()
111
+
112
+ # Conditioning 이미지 불러오기
113
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/svd/rocket.png")
114
+ image = image.resize((1024, 576))
115
+
116
+ generator = torch.manual_seed(42)
117
+ frames = pipe(image, decode_chunk_size=8, generator=generator, motion_bucket_id=180, noise_aug_strength=0.1).frames[0]
118
+ export_to_video(frames, "generated.mp4", fps=7)
119
+ ```
120
+
121
+ ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/svd/output_rocket_with_conditions.gif)
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/textual_inversion_inference.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Textual inversion
2
+
3
+ [[open-in-colab]]
4
+
5
+ [`StableDiffusionPipeline`]은 textual-inversion을 지원하는데, 이는 몇 개의 샘플 이미지만으로 stable diffusion과 같은 모델이 새로운 컨셉을 학습할 수 있도록 하는 기법입니다. 이를 통해 생성된 이미지를 더 잘 제어하고 특정 컨셉에 맞게 모델을 조정할 수 있습니다. 커뮤니티에서 만들어진 컨셉들의 컬렉션은 [Stable Diffusion Conceptualizer](https://huggingface.co/spaces/sd-concepts-library/stable-diffusion-conceptualizer)를 통해 빠르게 사용해볼 수 있습니다.
6
+
7
+ 이 가이드에서는 Stable Diffusion Conceptualizer에서 사전학습한 컨셉을 사용하여 textual-inversion으로 추론을 실행하는 방법을 보여드립니다. textual-inversion으로 모델에 새로운 컨셉을 학습시키는 데 관심이 있으시다면, [Textual Inversion](./training/text_inversion) 훈련 가이드를 참조하세요.
8
+
9
+ Hugging Face 계정으로 로그인하세요:
10
+
11
+ ```py
12
+ from huggingface_hub import notebook_login
13
+
14
+ notebook_login()
15
+ ```
16
+
17
+ 필요한 라이브러리를 불러오고 생성된 이미지를 시각화하기 위한 도우미 함수 `image_grid`를 만듭니다:
18
+
19
+ ```py
20
+ import os
21
+ import torch
22
+
23
+ import PIL
24
+ from PIL import Image
25
+
26
+ from diffusers import StableDiffusionPipeline
27
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
28
+
29
+
30
+ def image_grid(imgs, rows, cols):
31
+ assert len(imgs) == rows * cols
32
+
33
+ w, h = imgs[0].size
34
+ grid = Image.new("RGB", size=(cols * w, rows * h))
35
+ grid_w, grid_h = grid.size
36
+
37
+ for i, img in enumerate(imgs):
38
+ grid.paste(img, box=(i % cols * w, i // cols * h))
39
+ return grid
40
+ ```
41
+
42
+ Stable Diffusion과 [Stable Diffusion Conceptualizer](https://huggingface.co/spaces/sd-concepts-library/stable-diffusion-conceptualizer)에서 사전학습된 컨셉을 선택합니다:
43
+
44
+ ```py
45
+ pretrained_model_name_or_path = "stable-diffusion-v1-5/stable-diffusion-v1-5"
46
+ repo_id_embeds = "sd-concepts-library/cat-toy"
47
+ ```
48
+
49
+ 이제 파이프라인을 로드하고 사전학습된 컨셉을 파이프라인에 전달할 수 있습니다:
50
+
51
+ ```py
52
+ pipeline = StableDiffusionPipeline.from_pretrained(pretrained_model_name_or_path, torch_dtype=torch.float16).to("cuda")
53
+
54
+ pipeline.load_textual_inversion(repo_id_embeds)
55
+ ```
56
+
57
+ 특별한 placeholder token '`<cat-toy>`'를 사용하여 사전학습된 컨셉으로 프롬프트를 만들고, 생성할 샘플의 수와 이미지 행의 수를 선택합니다:
58
+
59
+ ```py
60
+ prompt = "a grafitti in a favela wall with a <cat-toy> on it"
61
+
62
+ num_samples = 2
63
+ num_rows = 2
64
+ ```
65
+
66
+ 그런 다음 파이프라인을 실행하고, 생성된 이미지들을 저장합니다. 그리고 처음에 만들었던 도우미 함수 `image_grid`를 사용하여 생성 결과들을 시각화합니다. 이 때 `num_inference_steps`와 `guidance_scale`과 같은 매개 변수들을 조정하여, 이것들이 이미지 품질에 어떠한 영향을 미치는지를 자유롭게 확인해보시기 바랍니다.
67
+
68
+ ```py
69
+ all_images = []
70
+ for _ in range(num_rows):
71
+ images = pipe(prompt, num_images_per_prompt=num_samples, num_inference_steps=50, guidance_scale=7.5).images
72
+ all_images.extend(images)
73
+
74
+ grid = image_grid(all_images, num_samples, num_rows)
75
+ grid
76
+ ```
77
+
78
+ <div class="flex justify-center">
79
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/textual_inversion_inference.png">
80
+ </div>
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/unconditional_image_generation.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Unconditional 이미지 생성
14
+
15
+ [[open-in-colab]]
16
+
17
+ Unconditional 이미지 생성은 비교적 간단한 작업입니다. 모델이 텍스트나 이미지와 같은 추가 조건 없이 이미 학습된 학습 데이터와 유사한 이미지만 생성합니다.
18
+
19
+ ['DiffusionPipeline']은 추론을 위해 미리 학습된 diffusion 시스템을 사용하는 가장 쉬운 방법입니다.
20
+
21
+ 먼저 ['DiffusionPipeline']의 인스턴스를 생성하고 다운로드할 파이프라인의 [체크포인트](https://huggingface.co/models?library=diffusers&sort=downloads)를 지정합니다. 허브의 🧨 diffusion 체크포인트 중 하나를 사용할 수 있습니다(사용할 체크포인트는 나비 이미지를 생성합니다).
22
+
23
+ > [!TIP]
24
+ > 💡 나만의 unconditional 이미지 생성 모델을 학습시키고 싶으신가요? 학습 가이드를 살펴보고 나만의 이미지를 생성하는 방법을 알아보세요.
25
+
26
+
27
+ 이 가이드에서는 unconditional 이미지 생성에 ['DiffusionPipeline']과 [DDPM](https://huggingface.co/papers/2006.11239)을 사용합니다:
28
+
29
+ ```python
30
+ >>> from diffusers import DiffusionPipeline
31
+
32
+ >>> generator = DiffusionPipeline.from_pretrained("anton-l/ddpm-butterflies-128")
33
+ ```
34
+
35
+ [diffusion 파이프라인]은 모든 모델링, 토큰화, 스케줄링 구성 요소를 다운로드하고 캐시합니다. 이 모델은 약 14억 개의 파라미터로 구성되어 있기 때문에 GPU에서 실행할 것을 강력히 권장합니다. PyTorch에서와 마찬가지로 제너레이터 객체를 GPU로 옮길 수 있습니다:
36
+
37
+ ```python
38
+ >>> generator.to("cuda")
39
+ ```
40
+
41
+ 이제 제너레이터를 사용하여 이미지를 생성할 수 있습니다:
42
+
43
+ ```python
44
+ >>> image = generator().images[0]
45
+ ```
46
+
47
+ 출력은 기본적으로 [PIL.Image](https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=image#the-image-class) 객체로 감싸집니다.
48
+
49
+ 다음을 호출하여 이미지를 저장할 수 있습니다:
50
+
51
+ ```python
52
+ >>> image.save("generated_image.png")
53
+ ```
54
+
55
+ 아래 스페이스(데모 링크)를 이용해 보고, 추론 단계의 매개변수를 자유롭게 조절하여 이미지 품질에 어떤 영향을 미치는지 확인해 보세요!
56
+
57
+ <iframe src="https://stevhliu-ddpm-butterflies-128.hf.space" frameborder="0" width="850" height="500"></iframe>
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/weighted_prompts.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # 프롬프트에 가중치 부여하기
14
+
15
+ [[open-in-colab]]
16
+
17
+ 텍스트 가이드 기반의 diffusion 모델은 주어진 텍스트 프롬프트를 기반으로 이미지를 생성합니다.
18
+ 텍스트 프롬프트에는 모델이 생성해야 하는 여러 개념이 포함될 수 있으며 프롬프트의 특정 부분에 가중치를 부여하는 것이 바람직한 경우가 많습니다.
19
+
20
+ Diffusion 모델은 문맥화된 텍스트 임베딩으로 diffusion 모델의 cross attention 레이어를 조절함으로써 작동합니다.
21
+ ([더 많은 정보를 위한 Stable Diffusion Guide](https://huggingface.co/docs/optimum-neuron/main/en/package_reference/modeling#stable-diffusion)를 참고하세요).
22
+ 따라서 프롬프트의 특정 부분을 강조하는(또는 강조하지 않는) 간단한 방법은 프롬프트의 관련 부분에 해당하는 텍스트 임베딩 벡터의 크기를 늘리거나 줄이는 것입니다.
23
+ 이것은 "프롬프트 가중치 부여" 라고 하며, 커뮤니티에서 가장 요구하는 기능입니다.([이곳](https://github.com/huggingface/diffusers/issues/2431)의 issue를 보세요 ).
24
+
25
+ ## Diffusers에서 프롬프트 가중치 부여하는 방법
26
+
27
+ 우리는 `diffusers`의 역할이 다른 프로젝트를 가능하게 하는 필수적인 기능을 제공하는 toolbex라고 생각합니다.
28
+ [InvokeAI](https://github.com/invoke-ai/InvokeAI) 나 [diffuzers](https://github.com/abhishekkrthakur/diffuzers) 같은 강력한 UI를 구축할 수 있습니다.
29
+ 프롬프트를 조작하는 방법을 지원하기 위해, `diffusers` 는
30
+ [StableDiffusionPipeline](https://huggingface.co/docs/diffusers/v0.18.2/en/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline)와 같은
31
+ 많은 파이프라인에 [prompt_embeds](https://huggingface.co/docs/diffusers/v0.14.0/en/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline.__call__.prompt_embeds)
32
+ 인수를 노출시켜, "prompt-weighted"/축척된 텍스트 임베딩을 파이프라인에 바로 전달할 수 있게 합니다.
33
+
34
+ [Compel 라이브러리](https://github.com/damian0815/compel)는 프롬프트의 일부를 강조하거나 강조하지 않을 수 있는 쉬운 방법을 제공합니다.
35
+ 임베딩을 직접 준비하는 것 대신 이 방법을 사용하는 것을 강력히 추천합니다.
36
+
37
+ 간단한 예제를 살펴보겠습니다.
38
+ 다음과 같이 `"공을 갖고 노는 붉은색 고양이"` 이미지를 생성하고 싶습니다:
39
+
40
+ ```py
41
+ from diffusers import StableDiffusionPipeline, UniPCMultistepScheduler
42
+
43
+ pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
44
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
45
+
46
+ prompt = "a red cat playing with a ball"
47
+
48
+ generator = torch.Generator(device="cpu").manual_seed(33)
49
+
50
+ image = pipe(prompt, generator=generator, num_inference_steps=20).images[0]
51
+ image
52
+ ```
53
+
54
+ 생성된 이미지:
55
+
56
+ ![img](https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/compel/forest_0.png)
57
+
58
+ 사진에서 알 수 있듯이, "공"은 이미지에 없습니다. 이 부분을 강조해 볼까요!
59
+
60
+ 먼저 `compel` 라이브러리를 설치해야합니다:
61
+
62
+ ```sh
63
+ pip install compel
64
+ ```
65
+
66
+ 그런 다음에는 `Compel` 오브젝트를 생성합니다:
67
+
68
+ ```py
69
+ from compel import Compel
70
+
71
+ compel_proc = Compel(tokenizer=pipe.tokenizer, text_encoder=pipe.text_encoder)
72
+ ```
73
+
74
+ 이제 `"++"` 를 사용해서 "공" 을 강조해 봅시다:
75
+
76
+ ```py
77
+ prompt = "a red cat playing with a ball++"
78
+ ```
79
+
80
+ 그리고 이 프롬프트를 파이프라인에 바로 전달하지 않고, `compel_proc` 를 사용하여 처리해야합니다:
81
+
82
+ ```py
83
+ prompt_embeds = compel_proc(prompt)
84
+ ```
85
+
86
+ 파이프라인에 `prompt_embeds` 를 바로 전달할 수 있습니다:
87
+
88
+ ```py
89
+ generator = torch.Generator(device="cpu").manual_seed(33)
90
+
91
+ images = pipe(prompt_embeds=prompt_embeds, generator=generator, num_inference_steps=20).images[0]
92
+ image
93
+ ```
94
+
95
+ 이제 "공"이 있는 그림을 출력할 수 있습니다!
96
+
97
+ ![img](https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/compel/forest_1.png)
98
+
99
+ 마찬가지로 `--` 접미사를 단어에 사용하여 문장의 일부를 강조하지 않을 수 있습니다. 한번 시도해 보세요!
100
+
101
+ 즐겨찾는 파이프라인에 `prompt_embeds` 입력이 없는 경우 issue를 새로 만들어주세요.
102
+ Diffusers 팀은 ��대한 대응하려고 노력합니다.
103
+
104
+ Compel 1.1.6 는 textual inversions을 사용하여 단순화하는 유티릴티 클래스를 추가합니다.
105
+ `DiffusersTextualInversionManager`를 인스턴스화 한 후 이를 Compel init에 전달합니다:
106
+
107
+ ```
108
+ textual_inversion_manager = DiffusersTextualInversionManager(pipe)
109
+ compel = Compel(
110
+ tokenizer=pipe.tokenizer,
111
+ text_encoder=pipe.text_encoder,
112
+ textual_inversion_manager=textual_inversion_manager)
113
+ ```
114
+
115
+ 더 많은 정보를 얻고 싶다면 [compel](https://github.com/damian0815/compel) 라이브러리 문서를 참고하세요.
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/ko/using-diffusers/write_own_pipeline.md ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # 파이프라인, 모델 및 스케줄러 이해하기
14
+
15
+ [[open-in-colab]]
16
+
17
+ 🧨 Diffusers는 사용자 친화적이며 유연한 도구 상자로, 사용사례에 맞게 diffusion 시스템을 구축 할 수 있도록 설계되었습니다. 이 도구 상자의 핵심은 모델과 스케줄러입니다. [`DiffusionPipeline`]은 편의를 위해 이러한 구성 요소를 번들로 제공하지만, 파이프라인을 분리하고 모델과 스케줄러를 개별적으로 사용해 새로운 diffusion 시스템을 만들 수도 있습니다.
18
+
19
+ 이 튜토리얼에서는 기본 파이프라인부터 시작해 Stable Diffusion 파이프라인까지 진행하며 모델과 스케줄러를 사용해 추론을 위한 diffusion 시스템을 조립하는 방법을 배웁니다.
20
+
21
+ ## 기본 파이프라인 해체하기
22
+
23
+ 파이프라인은 추론을 위해 모델을 실행하는 빠르고 쉬운 방법으로, 이미지를 생성하는 데 코드가 4줄 이상 필요하지 않습니다:
24
+
25
+ ```py
26
+ >>> from diffusers import DDPMPipeline
27
+
28
+ >>> ddpm = DDPMPipeline.from_pretrained("google/ddpm-cat-256").to("cuda")
29
+ >>> image = ddpm(num_inference_steps=25).images[0]
30
+ >>> image
31
+ ```
32
+
33
+ <div class="flex justify-center">
34
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ddpm-cat.png" alt="Image of cat created from DDPMPipeline"/>
35
+ </div>
36
+
37
+ 정말 쉽습니다. 그런데 파이프라인은 어떻게 이렇게 할 수 있었을까요? 파이프라인을 세분화하여 내부에서 어떤 일이 일어나고 있는지 살펴보겠습니다.
38
+
39
+ 위 예시에서 파이프라인에는 [`UNet2DModel`] 모델과 [`DDPMScheduler`]가 포함되어 있습니다. 파이프라인은 원하는 출력 크기의 랜덤 노이즈를 받아 모델을 여러번 통과시켜 이미지의 노이즈를 제거합니다. 각 timestep에서 모델은 *noise residual*을 예측하고 스케줄러는 이를 사용하여 노이즈가 적은 이미지를 예측합니다. 파이프라인은 지정된 추론 스텝수에 도달할 때까지 이 과정을 반복합니다.
40
+
41
+ 모델과 스케줄러를 별도로 사용하여 파이프라인을 다시 생성하기 위해 자체적인 노이즈 제거 프로세스를 작성해 보겠습니다.
42
+
43
+ 1. 모델과 스케줄러를 불러옵니다:
44
+
45
+ ```py
46
+ >>> from diffusers import DDPMScheduler, UNet2DModel
47
+
48
+ >>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cat-256")
49
+ >>> model = UNet2DModel.from_pretrained("google/ddpm-cat-256").to("cuda")
50
+ ```
51
+
52
+ 2. 노이즈 제거 프로세스를 실행할 timestep 수를 설정합니다:
53
+
54
+ ```py
55
+ >>> scheduler.set_timesteps(50)
56
+ ```
57
+
58
+ 3. 스케줄러의 timestep을 설정하면 균등한 간격의 구성 요소를 가진 텐서가 생성됩니다.(이 예시에서는 50개) 각 요소는 모델이 이미지의 노이즈를 제거하는 시간 간격에 해당합니다. 나중에 노이즈 제거 루프를 만들 때 이 텐서를 반복하여 이미지의 노이즈를 제거합니다:
59
+
60
+ ```py
61
+ >>> scheduler.timesteps
62
+ tensor([980, 960, 940, 920, 900, 880, 860, 840, 820, 800, 780, 760, 740, 720,
63
+ 700, 680, 660, 640, 620, 600, 580, 560, 540, 520, 500, 480, 460, 440,
64
+ 420, 400, 380, 360, 340, 320, 300, 280, 260, 240, 220, 200, 180, 160,
65
+ 140, 120, 100, 80, 60, 40, 20, 0])
66
+ ```
67
+
68
+ 4. 원하는 출력과 같은 모양을 가진 랜덤 노이즈를 생성합니다:
69
+
70
+ ```py
71
+ >>> import torch
72
+
73
+ >>> sample_size = model.config.sample_size
74
+ >>> noise = torch.randn((1, 3, sample_size, sample_size), device="cuda")
75
+ ```
76
+
77
+ 5. 이제 timestep을 반복하는 루프를 작성합니다. 각 timestep에서 모델은 [`UNet2DModel.forward`]를 통해 noisy residual을 반환합니다. 스케줄러의 [`~DDPMScheduler.step`] 메서드는 noisy residual, timestep, 그리고 입력을 받아 이전 timestep에서 이미지를 예측합니다. 이 출력은 노이즈 제거 루프의 모델에 대한 다음 입력이 되며, `timesteps` 배열의 끝에 도달할 때까지 반복됩니다.
78
+
79
+ ```py
80
+ >>> input = noise
81
+
82
+ >>> for t in scheduler.timesteps:
83
+ ... with torch.no_grad():
84
+ ... noisy_residual = model(input, t).sample
85
+ ... previous_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
86
+ ... input = previous_noisy_sample
87
+ ```
88
+
89
+ 이것이 전체 노이즈 제거 ��로세스이며, 동일한 패턴을 사용해 모든 diffusion 시스템을 작성할 수 있습니다.
90
+
91
+ 6. 마지막 단계는 노이즈가 제거된 출력을 이미지로 변환하는 것입니다:
92
+
93
+ ```py
94
+ >>> from PIL import Image
95
+ >>> import numpy as np
96
+
97
+ >>> image = (input / 2 + 0.5).clamp(0, 1)
98
+ >>> image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
99
+ >>> image = Image.fromarray((image * 255).round().astype("uint8"))
100
+ >>> image
101
+ ```
102
+
103
+ 다음 섹션에서는 여러분의 기술을 시험해보고 좀 더 복잡한 Stable Diffusion 파이프라인을 분석해 보겠습니다. 방법은 거의 동일합니다. 필요한 구성요소들을 초기화하고 timestep수를 설정하여 `timestep` 배열을 생성합니다. 노이즈 제거 루프에서 `timestep` 배열이 사용되며, 이 배열의 각 요소에 대해 모델은 노이즈가 적은 이미지를 예측합니다. 노이즈 제거 루프는 `timestep`을 반복하고 각 timestep에서 noise residual을 출력하고 스케줄러는 이를 사용하여 이전 timestep에서 노이즈가 덜한 이미지를 예측합니다. 이 프로세스는 `timestep` 배열의 끝에 도달할 때까지 반복됩니다.
104
+
105
+ 한번 사용해 봅시다!
106
+
107
+ ## Stable Diffusion 파이프라인 해체하기
108
+
109
+ Stable Diffusion 은 text-to-image *latent diffusion* 모델입니다. latent diffusion 모델이라고 불리는 이유는 실제 픽셀 공간 대신 이미지의 저차원의 표현으로 작업하기 때문이고, 메모리 효율이 더 높습니다. 인코더는 이미지를 더 작은 표현으로 압축하고, 디코더는 압축된 표현을 다시 이미지로 변환합니다. text-to-image 모델의 경우 텍스트 임베딩을 생성하기 위해 tokenizer와 인코더가 필요합니다. 이전 예제에서 이미 UNet 모델과 스케줄러가 필요하다는 것은 알고 계셨을 것입니다.
110
+
111
+ 보시다시피, 이것은 UNet 모델만 포함된 DDPM 파이프라인보다 더 복잡합니다. Stable Diffusion 모델에는 세 개의 개별 사전학습된 모델이 있습니다.
112
+
113
+ > [!TIP]
114
+ > 💡 VAE, UNet 및 텍스트 인코더 모델의 작동방식에 대한 자세한 내용은 [How does Stable Diffusion work?](https://huggingface.co/blog/stable_diffusion#how-does-stable-diffusion-work) 블로그를 참조하세요.
115
+
116
+ 이제 Stable Diffusion 파이프라인에 필요한 구성요소들이 무엇인지 알았으니, [`~ModelMixin.from_pretrained`] 메서드를 사용해 모든 구성요소를 불러옵니다. 사전학습된 체크포인트 [`stable-diffusion-v1-5/stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)에서 찾을 수 있으며, 각 구성요소들은 별도의 하위 폴더에 저장되어 있습니다:
117
+
118
+ ```py
119
+ >>> from PIL import Image
120
+ >>> import torch
121
+ >>> from transformers import CLIPTextModel, CLIPTokenizer
122
+ >>> from diffusers import AutoencoderKL, UNet2DConditionModel, PNDMScheduler
123
+
124
+ >>> vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
125
+ >>> tokenizer = CLIPTokenizer.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="tokenizer")
126
+ >>> text_encoder = CLIPTextModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="text_encoder")
127
+ >>> unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet")
128
+ ```
129
+
130
+ 기본 [`PNDMScheduler`] 대신, [`UniPCMultistepScheduler`]로 교체하여 다른 스케줄러를 얼마나 쉽게 연결할 수 있는지 확인합니다:
131
+
132
+ ```py
133
+ >>> from diffusers import UniPCMultistepScheduler
134
+
135
+ >>> scheduler = UniPCMultistepScheduler.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="scheduler")
136
+ ```
137
+
138
+ 추론 속도를 높이려면 스케줄러와 달리 학습 가능한 가중치가 있으므로 모델을 GPU로 옮기세요:
139
+
140
+ ```py
141
+ >>> torch_device = "cuda"
142
+ >>> vae.to(torch_device)
143
+ >>> text_encoder.to(torch_device)
144
+ >>> unet.to(torch_device)
145
+ ```
146
+
147
+ ### 텍스트 임베딩 생성하기
148
+
149
+ 다음 단계는 임베딩을 생성하기 위해 텍스트를 토큰화하는 것입니다. 이 텍스트는 UNet 모델에서 condition으로 사용되고 입력 프롬프트와 유사한 방향으로 diffusion 프로세스를 조정하는 데 사용됩니다.
150
+
151
+ > [!TIP]
152
+ > 💡 `guidance_scale` 매개변수는 이미지를 생성할 때 프롬프트에 얼마나 많은 가중치를 부여할지 결정합니다.
153
+
154
+ 다른 프롬프트를 생성하고 싶다면 원하는 프롬프트를 자유롭게 선택하세요!
155
+
156
+ ```py
157
+ >>> prompt = ["a photograph of an astronaut riding a horse"]
158
+ >>> height = 512 # Stable Diffusion의 기본 높이
159
+ >>> width = 512 # Stable Diffusion의 기본 너비
160
+ >>> num_inference_steps = 25 # 노이즈 제거 스텝 수
161
+ >>> guidance_scale = 7.5 # classifier-free guidance를 위한 scale
162
+ >>> generator = torch.manual_seed(0) # 초기 잠재 노이즈를 생성하는 seed generator
163
+ >>> batch_size = len(prompt)
164
+ ```
165
+
166
+ 텍스트를 토큰화하고 프롬프트에서 임베딩을 생성합니다:
167
+
168
+ ```py
169
+ >>> text_input = tokenizer(
170
+ ... prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt"
171
+ ... )
172
+
173
+ >>> with torch.no_grad():
174
+ ... text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
175
+ ```
176
+
177
+ 또한 패딩 토큰의 임베딩인 *unconditional 텍스트 임베딩*을 생성해야 합니다. 이 임베딩은 조건부 `text_embeddings`과 동일한 shape(`batch_size` 그리고 `seq_length`)을 가져야 합니다:
178
+
179
+ ```py
180
+ >>> max_length = text_input.input_ids.shape[-1]
181
+ >>> uncond_input = tokenizer([""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt")
182
+ >>> uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
183
+ ```
184
+
185
+ 두번의 forward pass를 피하기 위해 conditional 임베딩과 unconditional 임베딩을 배치(batch)로 연결하겠습니다:
186
+
187
+ ```py
188
+ >>> text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
189
+ ```
190
+
191
+ ### 랜덤 노이즈 생성
192
+
193
+ 그다음 diffusion 프로세스의 시작점으로 초기 랜덤 노이즈를 생성합니다. 이것이 이미지의 잠재적 표현이며 점차적으로 노이즈가 제거됩니다. 이 시점에서 `latent` 이미지는 최종 이미지 크기보다 작지만 나중에 모델이 이를 512x512 이미지 크기로 변환하므로 괜찮습니다.
194
+
195
+ > [!TIP]
196
+ > 💡 `vae` 모델에는 3개의 다운 샘플링 레이어가 있기 때문에 높이와 너비가 8로 나뉩니다. 다음을 실행하여 확인할 수 있습니다:
197
+ >
198
+ > ```py
199
+ > 2 ** (len(vae.config.block_out_channels) - 1) == 8
200
+ > ```
201
+
202
+ ```py
203
+ >>> latents = torch.randn(
204
+ ... (batch_size, unet.config.in_channels, height // 8, width // 8),
205
+ ... generator=generator,
206
+ ... device=torch_device,
207
+ ... )
208
+ ```
209
+
210
+ ### 이미지 노이즈 제거
211
+
212
+ 먼저 [`UniPCMultistepScheduler`]와 같은 향상된 스케줄러에 필요한 노이즈 스케일 값인 초기 노이즈 분포 *sigma* 로 입력을 스케일링 하는 것부터 시작합니다:
213
+
214
+ ```py
215
+ >>> latents = latents * scheduler.init_noise_sigma
216
+ ```
217
+
218
+ 마지막 단계는 `latent`의 순수한 노이즈를 점진적으로 프롬프트에 설명된 이미지로 변환하는 노이즈 제거 루프를 생성하는 것입니다. 노이즈 제거 루프는 세 가지 작업을 수행해야 한다는 점을 기억하세요:
219
+
220
+ 1. 노이즈 제거 중에 사용할 스케줄러의 timesteps를 설정합니다.
221
+ 2. timestep을 따라 반복합니다.
222
+ 3. 각 timestep에서 UNet 모델을 호출하여 noise residual을 예측하고 스케줄러에 전달하여 이전 노이즈 샘플을 계산합니다.
223
+
224
+ ```py
225
+ >>> from tqdm.auto import tqdm
226
+
227
+ >>> scheduler.set_timesteps(num_inference_steps)
228
+
229
+ >>> for t in tqdm(scheduler.timesteps):
230
+ ... # classifier-free guidance를 수행하는 경우 두번의 forward pass를 수행하지 않도록 latent를 확장.
231
+ ... latent_model_input = torch.cat([latents] * 2)
232
+
233
+ ... latent_model_input = scheduler.scale_model_input(latent_model_input, timestep=t)
234
+
235
+ ... # noise residual 예측
236
+ ... with torch.no_grad():
237
+ ... noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
238
+
239
+ ... # guidance 수행
240
+ ... noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
241
+ ... noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
242
+
243
+ ... # 이전 노이즈 샘플을 계산 x_t -> x_t-1
244
+ ... latents = scheduler.step(noise_pred, t, latents).prev_sample
245
+ ```
246
+
247
+ ### 이미지 디코딩
248
+
249
+ 마지막 단계는 `vae`를 이용하여 잠재 표현을 이미지로 디코딩하고 `sample`과 함께 디코딩된 출력을 얻는 것입니다:
250
+
251
+ ```py
252
+ # latent를 스케일링하고 vae로 이미지 디코딩
253
+ latents = 1 / 0.18215 * latents
254
+ with torch.no_grad():
255
+ image = vae.decode(latents).sample
256
+ ```
257
+
258
+ 마지막으로 이미지를 `PIL.Image`로 변환하면 생성된 이미지를 확인할 수 있습니다!
259
+
260
+ ```py
261
+ >>> image = (image / 2 + 0.5).clamp(0, 1)
262
+ >>> image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
263
+ >>> images = (image * 255).round().astype("uint8")
264
+ >>> pil_images = [Image.fromarray(image) for image in images]
265
+ >>> pil_images[0]
266
+ ```
267
+
268
+ <div class="flex justify-center">
269
+ <img src="https://huggingface.co/blog/assets/98_stable_diffusion/stable_diffusion_k_lms.png"/>
270
+ </div>
271
+
272
+ ## 다음 단계
273
+
274
+ 기본 파이프라인부터 복잡한 파이프라인까지, 자신만의 diffusion 시스템을 작성하는 데 필요한 것은 노이즈 제거 루프뿐이라는 것을 알 수 있었습니다. 이 루프는 스케줄러의 timesteps를 설정하고, 이를 반복하며, UNet 모델을 호출하여 noise residual을 예측하고 스케줄러에 전달하여 이전 노이즈 샘플을 계산하는 과정을 번갈아 가며 수행해야 합니다.
275
+
276
+ 이것이 바로 🧨 Diffusers가 설계된 목적입니다: 모델과 스케줄러를 사용해 자신만의 diffusion 시스템을 직관적이고 쉽게 작성할 수 있도록 하기 위해서입니다.
277
+
278
+ 다음 단계를 자유롭게 진행하세요:
279
+
280
+ * 🧨 Diffusers에 [파이프라인 구축 및 기여](using-diffusers/#contribute_pipeline)하는 방법을 알아보세요. 여러분이 어떤 아이디어를 내놓을지 기대됩니다!
281
+ * 라이브러리에서 [기본 파이프라인](./api/pipelines/overview)을 살펴보고, 모델과 스케줄러를 별도로 사용하여 파이프라인을 처음부터 해체하고 빌드할 수 있는지 확인해 보세요.
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/_toctree.yml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: Diffusers
4
+ - local: installation
5
+ title: Instalação
6
+ - local: quicktour
7
+ title: Tour rápido
8
+ - local: stable_diffusion
9
+ title: Desempenho básico
10
+ title: Primeiros passos
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/index.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ <p align="center">
14
+ <br>
15
+ <img src="https://raw.githubusercontent.com/huggingface/diffusers/77aadfee6a891ab9fcfb780f87c693f7a5beeb8e/docs/source/imgs/diffusers_library.jpg" width="400"/>
16
+ <br>
17
+ </p>
18
+
19
+ # Diffusers
20
+
21
+ 🤗 Diffusers é uma biblioteca de modelos de difusão de última geração para geração de imagens, áudio e até mesmo estruturas 3D de moléculas. Se você está procurando uma solução de geração simples ou quer treinar seu próprio modelo de difusão, 🤗 Diffusers é uma caixa de ferramentas modular que suporta ambos. Nossa biblioteca é desenhada com foco em [usabilidade em vez de desempenho](conceptual/philosophy#usability-over-performance), [simples em vez de fácil](conceptual/philosophy#simple-over-easy) e [customizável em vez de abstrações](conceptual/philosophy#tweakable-contributorfriendly-over-abstraction).
22
+
23
+ A Biblioteca tem três componentes principais:
24
+
25
+ - Pipelines de última geração para a geração em poucas linhas de código. Há muitos pipelines no 🤗 Diffusers, veja a tabela no pipeline [Visão geral](api/pipelines/overview) para uma lista completa de pipelines disponíveis e as tarefas que eles resolvem.
26
+ - Intercambiáveis [agendadores de ruído](api/schedulers/overview) para balancear as compensações entre velocidade e qualidade de geração.
27
+ - [Modelos](api/models) pré-treinados que podem ser usados como se fossem blocos de construção, e combinados com agendadores, para criar seu próprio sistema de difusão de ponta a ponta.
28
+
29
+ <div class="mt-10">
30
+ <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
31
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorials/tutorial_overview"
32
+ ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutoriais</div>
33
+ <p class="text-gray-700">Aprenda as competências fundamentais que precisa para iniciar a gerar saídas, construa seu próprio sistema de difusão, e treine um modelo de difusão. Nós recomendamos começar por aqui se você está utilizando o 🤗 Diffusers pela primeira vez!</p>
34
+ </a>
35
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./using-diffusers/loading_overview"
36
+ ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Guias de utilização</div>
37
+ <p class="text-gray-700">Guias práticos para ajudar você carregar pipelines, modelos, e agendadores. Você também aprenderá como usar os pipelines para tarefas específicas, controlar como as saídas são geradas, otimizar a velocidade de geração, e outras técnicas diferentes de treinamento.</p>
38
+ </a>
39
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./conceptual/philosophy"
40
+ ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Guias conceituais</div>
41
+ <p class="text-gray-700">Compreenda porque a biblioteca foi desenhada da forma que ela é, e aprenda mais sobre as diretrizes éticas e implementações de segurança para o uso da biblioteca.</p>
42
+ </a>
43
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./api/models/overview"
44
+ ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Referência</div>
45
+ <p class="text-gray-700">Descrições técnicas de como funcionam as classes e métodos do 🤗 Diffusers</p>
46
+ </a>
47
+ </div>
48
+ </div>
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/installation.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Instalação
14
+
15
+ 🤗 Diffusers é testado no Python 3.8+, PyTorch 1.7.0+, e Flax. Siga as instruções de instalação abaixo para a biblioteca de deep learning que você está utilizando:
16
+
17
+ - [PyTorch](https://pytorch.org/get-started/locally/) instruções de instalação
18
+ - [Flax](https://flax.readthedocs.io/en/latest/) instruções de instalação
19
+
20
+ ## Instalação com pip
21
+
22
+ Recomenda-se instalar 🤗 Diffusers em um [ambiente virtual](https://docs.python.org/3/library/venv.html).
23
+ Se você não está familiarizado com ambiente virtuals, veja o [guia](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
24
+ Um ambiente virtual facilita gerenciar diferentes projetos e evitar problemas de compatibilidade entre dependências.
25
+
26
+ Comece criando um ambiente virtual no diretório do projeto:
27
+
28
+ ```bash
29
+ python -m venv .env
30
+ ```
31
+
32
+ Ative o ambiente virtual:
33
+
34
+ ```bash
35
+ source .env/bin/activate
36
+ ```
37
+
38
+ Recomenda-se a instalação do 🤗 Transformers porque 🤗 Diffusers depende de seus modelos:
39
+
40
+ <frameworkcontent>
41
+ <pt>
42
+ ```bash
43
+ pip install diffusers["torch"] transformers
44
+ ```
45
+ </pt>
46
+ <jax>
47
+ ```bash
48
+ pip install diffusers["flax"] transformers
49
+ ```
50
+ </jax>
51
+ </frameworkcontent>
52
+
53
+ ## Instalação a partir do código fonte
54
+
55
+ Antes da instalação do 🤗 Diffusers a partir do código fonte, certifique-se de ter o PyTorch e o 🤗 Accelerate instalados.
56
+
57
+ Para instalar o 🤗 Accelerate:
58
+
59
+ ```bash
60
+ pip install accelerate
61
+ ```
62
+
63
+ então instale o 🤗 Diffusers do código fonte:
64
+
65
+ ```bash
66
+ pip install git+https://github.com/huggingface/diffusers
67
+ ```
68
+
69
+ Esse comando instala a última versão em desenvolvimento `main` em vez da última versão estável `stable`.
70
+ A versão `main` é útil para se manter atualizado com os últimos desenvolvimentos.
71
+ Por exemplo, se um bug foi corrigido desde o último lançamento estável, mas um novo lançamento ainda não foi lançado.
72
+ No entanto, isso significa que a versão `main` pode não ser sempre estável.
73
+ Nós nos esforçamos para manter a versão `main` operacional, e a maioria dos problemas geralmente são resolvidos em algumas horas ou um dia.
74
+ Se você encontrar um problema, por favor abra uma [Issue](https://github.com/huggingface/diffusers/issues/new/choose), assim conseguimos arrumar o quanto antes!
75
+
76
+ ## Instalação editável
77
+
78
+ Você precisará de uma instalação editável se você:
79
+
80
+ - Usar a versão `main` do código fonte.
81
+ - Contribuir para o 🤗 Diffusers e precisa testar mudanças no código.
82
+
83
+ Clone o repositório e instale o 🤗 Diffusers com os seguintes comandos:
84
+
85
+ ```bash
86
+ git clone https://github.com/huggingface/diffusers.git
87
+ cd diffusers
88
+ ```
89
+
90
+ <frameworkcontent>
91
+ <pt>
92
+ ```bash
93
+ pip install -e ".[torch]"
94
+ ```
95
+ </pt>
96
+ <jax>
97
+ ```bash
98
+ pip install -e ".[flax]"
99
+ ```
100
+ </jax>
101
+ </frameworkcontent>
102
+
103
+ Esses comandos irão vincular a pasta que você clonou o repositório e os caminhos das suas bibliotecas Python.
104
+ Python então irá procurar dentro da pasta que você clonou além dos caminhos normais das bibliotecas.
105
+ Por exemplo, se o pacote python for tipicamente instalado no `~/anaconda3/envs/main/lib/python3.10/site-packages/`, o Python também irá procurar na pasta `~/diffusers/` que você clonou.
106
+
107
+ > [!WARNING]
108
+ > Você deve manter a pasta `diffusers` se quiser continuar usando a biblioteca.
109
+
110
+ Agora você pode facilmente atualizar seu clone para a última versão do 🤗 Diffusers com o seguinte comando:
111
+
112
+ ```bash
113
+ cd ~/diffusers/
114
+ git pull
115
+ ```
116
+
117
+ Seu ambiente Python vai encontrar a versão `main` do 🤗 Diffusers na próxima execução.
118
+
119
+ ## Cache
120
+
121
+ Os pesos e os arquivos dos modelos são baixados do Hub para o cache que geralmente é o seu diretório home. Você pode mudar a localização do cache especificando as variáveis de ambiente `HF_HOME` ou `HUGGINFACE_HUB_CACHE` ou configurando o parâmetro `cache_dir` em métodos como [`~DiffusionPipeline.from_pretrained`].
122
+
123
+ Aquivos em cache permitem que você rode 🤗 Diffusers offline. Para prevenir que o 🤗 Diffusers se conecte à internet, defina a variável de ambiente `HF_HUB_OFFLINE` para `True` e o 🤗 Diffusers irá apenas carregar arquivos previamente baixados em cache.
124
+
125
+ ```shell
126
+ export HF_HUB_OFFLINE=True
127
+ ```
128
+
129
+ Para mais detalhes de como gerenciar e limpar o cache, olhe o guia de [caching](https://huggingface.co/docs/huggingface_hub/guides/manage-cache).
130
+
131
+ ## Telemetria
132
+
133
+ Nossa biblioteca coleta informações de telemetria durante as requisições [`~DiffusionPipeline.from_pretrained`].
134
+ O dado coletado inclui a versão do 🤗 Diffusers e PyTorch/Flax, o modelo ou classe de pipeline requisitado,
135
+ e o caminho para um checkpoint pré-treinado se ele estiver hospedado no Hugging Face Hub.
136
+ Esse dado de uso nos ajuda a debugar problemas e priorizar novas funcionalidades.
137
+ Telemetria é enviada apenas quando é carregado modelos e pipelines do Hub,
138
+ e não é coletado se você estiver carregando arquivos locais.
139
+
140
+ Nos entendemos que nem todo mundo quer compartilhar informações adicionais, e nós respeitamos sua privacidade.
141
+ Você pode desabilitar a coleta de telemetria definindo a variável de ambiente `DISABLE_TELEMETRY` do seu terminal:
142
+
143
+ No Linux/MacOS:
144
+
145
+ ```bash
146
+ export DISABLE_TELEMETRY=YES
147
+ ```
148
+
149
+ No Windows:
150
+
151
+ ```bash
152
+ set DISABLE_TELEMETRY=YES
153
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/quicktour.md ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ [[open-in-colab]]
14
+
15
+ # Tour rápido
16
+
17
+ Modelos de difusão são treinados para remover o ruído Gaussiano aleatório passo a passo para gerar uma amostra de interesse, como uma imagem ou áudio. Isso despertou um tremendo interesse em IA generativa, e você provavelmente já viu exemplos de imagens geradas por difusão na internet. 🧨 Diffusers é uma biblioteca que visa tornar os modelos de difusão amplamente acessíveis a todos.
18
+
19
+ Seja você um desenvolvedor ou um usuário, esse tour rápido irá introduzir você ao 🧨 Diffusers e ajudar você a começar a gerar rapidamente! Há três componentes principais da biblioteca para conhecer:
20
+
21
+ - O [`DiffusionPipeline`] é uma classe de alto nível de ponta a ponta desenhada para gerar rapidamente amostras de modelos de difusão pré-treinados para inferência.
22
+ - [Modelos](./api/models) pré-treinados populares e módulos que podem ser usados como blocos de construção para criar sistemas de difusão.
23
+ - Vários [Agendadores](./api/schedulers/overview) diferentes - algoritmos que controlam como o ruído é adicionado para treinamento, e como gerar imagens sem o ruído durante a inferência.
24
+
25
+ Esse tour rápido mostrará como usar o [`DiffusionPipeline`] para inferência, e então mostrará como combinar um modelo e um agendador para replicar o que está acontecendo dentro do [`DiffusionPipeline`].
26
+
27
+ > [!TIP]
28
+ > Esse tour rápido é uma versão simplificada da introdução 🧨 Diffusers [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/diffusers_intro.ipynb) para ajudar você a começar rápido. Se você quer aprender mais sobre o objetivo do 🧨 Diffusers, filosofia de design, e detalhes adicionais sobre a API principal, veja o notebook!
29
+
30
+ Antes de começar, certifique-se de ter todas as bibliotecas necessárias instaladas:
31
+
32
+ ```py
33
+ # uncomment to install the necessary libraries in Colab
34
+ #!pip install --upgrade diffusers accelerate transformers
35
+ ```
36
+
37
+ - [🤗 Accelerate](https://huggingface.co/docs/accelerate/index) acelera o carregamento do modelo para geração e treinamento.
38
+ - [🤗 Transformers](https://huggingface.co/docs/transformers/index) é necessário para executar os modelos mais populares de difusão, como o [Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/overview).
39
+
40
+ ## DiffusionPipeline
41
+
42
+ O [`DiffusionPipeline`] é a forma mais fácil de usar um sistema de difusão pré-treinado para geração. É um sistema de ponta a ponta contendo o modelo e o agendador. Você pode usar o [`DiffusionPipeline`] pronto para muitas tarefas. Dê uma olhada na tabela abaixo para algumas tarefas suportadas, e para uma lista completa de tarefas suportadas, veja a tabela [Resumo do 🧨 Diffusers](./api/pipelines/overview#diffusers-summary).
43
+
44
+ | **Tarefa** | **Descrição** | **Pipeline** |
45
+ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
46
+ | Unconditional Image Generation | gera uma imagem a partir do ruído Gaussiano | [unconditional_image_generation](./using-diffusers/unconditional_image_generation) |
47
+ | Text-Guided Image Generation | gera uma imagem a partir de um prompt de texto | [conditional_image_generation](./using-diffusers/conditional_image_generation) |
48
+ | Text-Guided Image-to-Image Translation | adapta uma imagem guiada por um prompt de texto | [img2img](./using-diffusers/img2img) |
49
+ | Text-Guided Image-Inpainting | preenche a parte da máscara da imagem, dado a imagem, a máscara e o prompt de texto | [inpaint](./using-diffusers/inpaint) |
50
+ | Text-Guided Depth-to-Image Translation | adapta as partes de uma imagem guiada por um prompt de texto enquanto preserva a estrutura por estimativa de profundidade | [depth2img](./using-diffusers/depth2img) |
51
+
52
+ Comece criando uma instância do [`DiffusionPipeline`] e especifique qual checkpoint do pipeline você gostaria de baixar.
53
+ Você pode usar o [`DiffusionPipeline`] para qualquer [checkpoint](https://huggingface.co/models?library=diffusers&sort=downloads) armazenado no Hugging Face Hub.
54
+ Nesse quicktour, você carregará o checkpoint [`stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) para geração de texto para imagem.
55
+
56
+ > [!WARNING]
57
+ > Para os modelos de [Stable Diffusion](https://huggingface.co/CompVis/stable-diffusion), por favor leia cuidadosamente a [licença](https://huggingface.co/spaces/CompVis/stable-diffusion-license) primeiro antes de rodar o modelo. 🧨 Diffusers implementa uma verificação de segurança: [`safety_checker`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py) para prevenir conteúdo ofensivo ou nocivo, mas as capacidades de geração de imagem aprimorada do modelo podem ainda produzir conteúdo potencialmente nocivo.
58
+
59
+ Para carregar o modelo com o método [`~DiffusionPipeline.from_pretrained`]:
60
+
61
+ ```python
62
+ >>> from diffusers import DiffusionPipeline
63
+
64
+ >>> pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", use_safetensors=True)
65
+ ```
66
+
67
+ O [`DiffusionPipeline`] baixa e armazena em cache todos os componentes de modelagem, tokenização, e agendamento. Você verá que o pipeline do Stable Diffusion é composto pelo [`UNet2DConditionModel`] e [`PNDMScheduler`] entre outras coisas:
68
+
69
+ ```py
70
+ >>> pipeline
71
+ StableDiffusionPipeline {
72
+ "_class_name": "StableDiffusionPipeline",
73
+ "_diffusers_version": "0.13.1",
74
+ ...,
75
+ "scheduler": [
76
+ "diffusers",
77
+ "PNDMScheduler"
78
+ ],
79
+ ...,
80
+ "unet": [
81
+ "diffusers",
82
+ "UNet2DConditionModel"
83
+ ],
84
+ "vae": [
85
+ "diffusers",
86
+ "AutoencoderKL"
87
+ ]
88
+ }
89
+ ```
90
+
91
+ Nós fortemente recomendamos rodar o pipeline em uma placa de vídeo, pois o modelo consiste em aproximadamente 1.4 bilhões de parâmetros.
92
+ Você pode mover o objeto gerador para uma placa de vídeo, assim como você faria no PyTorch:
93
+
94
+ ```python
95
+ >>> pipeline.to("cuda")
96
+ ```
97
+
98
+ Agora você pode passar o prompt de texto para o `pipeline` para gerar uma imagem, e então acessar a imagem sem ruído. Por padrão, a saída da imagem é embrulhada em um objeto [`PIL.Image`](https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=image#the-image-class).
99
+
100
+ ```python
101
+ >>> image = pipeline("An image of a squirrel in Picasso style").images[0]
102
+ >>> image
103
+ ```
104
+
105
+ <div class="flex justify-center">
106
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/image_of_squirrel_painting.png"/>
107
+ </div>
108
+
109
+ Salve a imagem chamando o `save`:
110
+
111
+ ```python
112
+ >>> image.save("image_of_squirrel_painting.png")
113
+ ```
114
+
115
+ ### Pipeline local
116
+
117
+ Você também pode utilizar o pipeline localmente. A única diferença é que você precisa baixar os pesos primeiro:
118
+
119
+ ```bash
120
+ !git lfs install
121
+ !git clone https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5
122
+ ```
123
+
124
+ Assim carregue os pesos salvos no pipeline:
125
+
126
+ ```python
127
+ >>> pipeline = DiffusionPipeline.from_pretrained("./stable-diffusion-v1-5", use_safetensors=True)
128
+ ```
129
+
130
+ Agora você pode rodar o pipeline como você faria na seção acima.
131
+
132
+ ### Troca dos agendadores
133
+
134
+ Agendadores diferentes tem diferentes velocidades de retirar o ruído e compensações de qualidade. A melhor forma de descobrir qual funciona melhor para você é testar eles! Uma das principais características do 🧨 Diffusers é permitir que você troque facilmente entre agendadores. Por exemplo, para substituir o [`PNDMScheduler`] padrão com o [`EulerDiscreteScheduler`], carregue ele com o método [`~diffusers.ConfigMixin.from_config`]:
135
+
136
+ ```py
137
+ >>> from diffusers import EulerDiscreteScheduler
138
+
139
+ >>> pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", use_safetensors=True)
140
+ >>> pipeline.scheduler = EulerDiscreteScheduler.from_config(pipeline.scheduler.config)
141
+ ```
142
+
143
+ Tente gerar uma imagem com o novo agendador e veja se você nota alguma diferença!
144
+
145
+ Na próxima seção, você irá dar uma olhada mais de perto nos componentes - o modelo e o agendador - que compõe o [`DiffusionPipeline`] e aprender como usar esses componentes para gerar uma imagem de um gato.
146
+
147
+ ## Modelos
148
+
149
+ A maioria dos modelos recebe uma amostra de ruído, e em cada _timestep_ ele prevê o _noise residual_ (outros modelos aprendem a prever a amostra anterior diretamente ou a velocidade ou [`v-prediction`](https://github.com/huggingface/diffusers/blob/5e5ce13e2f89ac45a0066cb3f369462a3cf1d9ef/src/diffusers/schedulers/scheduling_ddim.py#L110)), a diferença entre uma imagem menos com ruído e a imagem de entrada. Você pode misturar e combinar modelos para criar outros sistemas de difusão.
150
+
151
+ Modelos são inicializados com o método [`~ModelMixin.from_pretrained`] que também armazena em cache localmente os pesos do modelo para que seja mais rápido na próxima vez que você carregar o modelo. Para o tour rápido, você irá carregar o [`UNet2DModel`], um modelo básico de geração de imagem incondicional com um checkpoint treinado em imagens de gato:
152
+
153
+ ```py
154
+ >>> from diffusers import UNet2DModel
155
+
156
+ >>> repo_id = "google/ddpm-cat-256"
157
+ >>> model = UNet2DModel.from_pretrained(repo_id, use_safetensors=True)
158
+ ```
159
+
160
+ Para acessar os parâmetros do modelo, chame `model.config`:
161
+
162
+ ```py
163
+ >>> model.config
164
+ ```
165
+
166
+ A configuração do modelo é um dicionário 🧊 congelado 🧊, o que significa que esses parâmetros não podem ser mudados depois que o modelo é criado. Isso é intencional e garante que os parâmetros usados para definir a arquitetura do modelo no início permaneçam os mesmos, enquanto outros parâmetros ainda podem ser ajustados durante a geração.
167
+
168
+ Um dos parâmetros mais importantes são:
169
+
170
+ - `sample_size`: a dimensão da altura e largura da amostra de entrada.
171
+ - `in_channels`: o número de canais de entrada da amostra de entrada.
172
+ - `down_block_types` e `up_block_types`: o tipo de blocos de downsampling e upsampling usados para criar a arquitetura UNet.
173
+ - `block_out_channels`: o número de canais de saída dos blocos de downsampling; também utilizado como uma order reversa do número de canais de entrada dos blocos de upsampling.
174
+ - `layers_per_block`: o número de blocks ResNet presentes em cada block UNet.
175
+
176
+ Para usar o modelo para geração, crie a forma da imagem com ruído Gaussiano aleatório. Deve ter um eixo `batch` porque o modelo pode receber múltiplos ruídos aleatórios, um eixo `channel` correspondente ao número de canais de entrada, e um eixo `sample_size` para a altura e largura da imagem:
177
+
178
+ ```py
179
+ >>> import torch
180
+
181
+ >>> torch.manual_seed(0)
182
+
183
+ >>> noisy_sample = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
184
+ >>> noisy_sample.shape
185
+ torch.Size([1, 3, 256, 256])
186
+ ```
187
+
188
+ Para geração, passe a imagem com ruído para o modelo e um `timestep`. O `timestep` indica o quão ruidosa a imagem de entrada é, com mais ruído no início e menos no final. Isso ajuda o modelo a determinar sua posição no processo de difusão, se está mais perto do início ou do final. Use o método `sample` para obter a saída do modelo:
189
+
190
+ ```py
191
+ >>> with torch.no_grad():
192
+ ... noisy_residual = model(sample=noisy_sample, timestep=2).sample
193
+ ```
194
+
195
+ Para geração de exemplos reais, você precisará de um agendador para guiar o processo de retirada do ruído. Na próxima seção, você irá aprender como acoplar um modelo com um agendador.
196
+
197
+ ## Agendadores
198
+
199
+ Agendadores gerenciam a retirada do ruído de uma amostra ruidosa para uma amostra menos ruidosa dado a saída do modelo - nesse caso, é o `noisy_residual`.
200
+
201
+ > [!TIP]
202
+ > 🧨 Diffusers é uma caixa de ferramentas para construir sistemas de difusão. Enquanto o [`DiffusionPipeline`] é uma forma conveniente de começar com um sistema de difusão pré-construído, você também pode escolher seus próprios modelos e agendadores separadamente para construir um sistema de difusão personalizado.
203
+
204
+ Para o tour rápido, você irá instanciar o [`DDPMScheduler`] com o método [`~diffusers.ConfigMixin.from_config`]:
205
+
206
+ ```py
207
+ >>> from diffusers import DDPMScheduler
208
+
209
+ >>> scheduler = DDPMScheduler.from_config(repo_id)
210
+ >>> scheduler
211
+ DDPMScheduler {
212
+ "_class_name": "DDPMScheduler",
213
+ "_diffusers_version": "0.13.1",
214
+ "beta_end": 0.02,
215
+ "beta_schedule": "linear",
216
+ "beta_start": 0.0001,
217
+ "clip_sample": true,
218
+ "clip_sample_range": 1.0,
219
+ "num_train_timesteps": 1000,
220
+ "prediction_type": "epsilon",
221
+ "trained_betas": null,
222
+ "variance_type": "fixed_small"
223
+ }
224
+ ```
225
+
226
+ > [!TIP]
227
+ > 💡 Perceba como o agendador é instanciado de uma configuração. Diferentemente de um modelo, um agendador não tem pesos treináveis e é livre de parâmetros!
228
+
229
+ Um dos parâmetros mais importante são:
230
+
231
+ - `num_train_timesteps`: o tamanho do processo de retirar ruído ou em outras palavras, o número de _timesteps_ necessários para o processo de ruídos Gausianos aleatórios dentro de uma amostra de dados.
232
+ - `beta_schedule`: o tipo de agendados de ruído para o uso de geração e treinamento.
233
+ - `beta_start` e `beta_end`: para começar e terminar os valores de ruído para o agendador de ruído.
234
+
235
+ Para predizer uma imagem com um pouco menos de ruído, passe o seguinte para o método do agendador [`~diffusers.DDPMScheduler.step`]: saída do modelo, `timestep`, e a atual `amostra`.
236
+
237
+ ```py
238
+ >>> less_noisy_sample = scheduler.step(model_output=noisy_residual, timestep=2, sample=noisy_sample).prev_sample
239
+ >>> less_noisy_sample.shape
240
+ ```
241
+
242
+ O `less_noisy_sample` pode ser passado para o próximo `timestep` onde ele ficará ainda com menos ruído! Vamos juntar tudo agora e visualizar o processo inteiro de retirada de ruído.
243
+
244
+ Comece, criando a função que faça o pós-processamento e mostre a imagem sem ruído como uma `PIL.Image`:
245
+
246
+ ```py
247
+ >>> import PIL.Image
248
+ >>> import numpy as np
249
+
250
+
251
+ >>> def display_sample(sample, i):
252
+ ... image_processed = sample.cpu().permute(0, 2, 3, 1)
253
+ ... image_processed = (image_processed + 1.0) * 127.5
254
+ ... image_processed = image_processed.numpy().astype(np.uint8)
255
+
256
+ ... image_pil = PIL.Image.fromarray(image_processed[0])
257
+ ... display(f"Image at step {i}")
258
+ ... display(image_pil)
259
+ ```
260
+
261
+ Para acelerar o processo de retirada de ruído, mova a entrada e o modelo para uma GPU:
262
+
263
+ ```py
264
+ >>> model.to("cuda")
265
+ >>> noisy_sample = noisy_sample.to("cuda")
266
+ ```
267
+
268
+ Agora, crie um loop de retirada de ruído que prediz o residual da amostra menos ruidosa, e computa a amostra menos ruidosa com o agendador:
269
+
270
+ ```py
271
+ >>> import tqdm
272
+
273
+ >>> sample = noisy_sample
274
+
275
+ >>> for i, t in enumerate(tqdm.tqdm(scheduler.timesteps)):
276
+ ... # 1. predict noise residual
277
+ ... with torch.no_grad():
278
+ ... residual = model(sample, t).sample
279
+
280
+ ... # 2. compute less noisy image and set x_t -> x_t-1
281
+ ... sample = scheduler.step(residual, t, sample).prev_sample
282
+
283
+ ... # 3. optionally look at image
284
+ ... if (i + 1) % 50 == 0:
285
+ ... display_sample(sample, i + 1)
286
+ ```
287
+
288
+ Sente-se e assista o gato ser gerado do nada além de ruído! 😻
289
+
290
+ <div class="flex justify-center">
291
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/diffusion-quicktour.png"/>
292
+ </div>
293
+
294
+ ## Próximos passos
295
+
296
+ Esperamos que você tenha gerado algumas imagens legais com o 🧨 Diffusers neste tour rápido! Para suas próximas etapas, você pode
297
+
298
+ - Treine ou faça a configuração fina de um modelo para gerar suas próprias imagens no tutorial de [treinamento](./tutorials/basic_training).
299
+ - Veja exemplos oficiais e da comunidade de [scripts de treinamento ou configuração fina](https://github.com/huggingface/diffusers/tree/main/examples#-diffusers-examples) para os mais variados casos de uso.
300
+ - Aprenda sobre como carregar, acessar, mudar e comparar agendadores no guia [Usando diferentes agendadores](./using-diffusers/schedulers).
301
+ - Explore engenharia de prompt, otimizações de velocidade e memória, e dicas e truques para gerar imagens de maior qualidade com o guia [Stable Diffusion](./stable_diffusion).
302
+ - Se aprofunde em acelerar 🧨 Diffusers com guias sobre [PyTorch otimizado em uma GPU](./optimization/fp16), e guias de inferência para rodar [Stable Diffusion em Apple Silicon (M1/M2)](./optimization/mps) e [ONNX Runtime](./optimization/onnx).
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/pt/stable_diffusion.md ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ [[open-in-colab]]
14
+
15
+ # Desempenho básico
16
+
17
+ Difusão é um processo aleatório que demanda muito processamento. Você pode precisar executar o [`DiffusionPipeline`] várias vezes antes de obter o resultado desejado. Por isso é importante equilibrar cuidadosamente a velocidade de geração e o uso de memória para iterar mais rápido.
18
+
19
+ Este guia recomenda algumas dicas básicas de desempenho para usar o [`DiffusionPipeline`]. Consulte a seção de documentação sobre Otimização de Inferência, como [Acelerar inferência](./optimization/fp16) ou [Reduzir uso de memória](./optimization/memory) para guias de desempenho mais detalhados.
20
+
21
+ ## Uso de memória
22
+
23
+ Reduzir a quantidade de memória usada indiretamente acelera a geração e pode ajudar um modelo a caber no dispositivo.
24
+
25
+ O método [`~DiffusionPipeline.enable_model_cpu_offload`] move um modelo para a CPU quando não está em uso para economizar memória da GPU.
26
+
27
+ ```py
28
+ import torch
29
+ from diffusers import DiffusionPipeline
30
+
31
+ pipeline = DiffusionPipeline.from_pretrained(
32
+ "stabilityai/stable-diffusion-xl-base-1.0",
33
+ torch_dtype=torch.bfloat16,
34
+ device_map="cuda"
35
+ )
36
+ pipeline.enable_model_cpu_offload()
37
+
38
+ prompt = """
39
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
40
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
41
+ """
42
+ pipeline(prompt).images[0]
43
+ print(f"Memória máxima reservada: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
44
+ ```
45
+
46
+ ## Velocidade de inferência
47
+
48
+ O processo de remoção de ruído é o mais exigente computacionalmente durante a difusão. Métodos que otimizam este processo aceleram a velocidade de inferência. Experimente os seguintes métodos para acelerar.
49
+
50
+ - Adicione `device_map="cuda"` para colocar o pipeline em uma GPU. Colocar um modelo em um acelerador, como uma GPU, aumenta a velocidade porque realiza computações em paralelo.
51
+ - Defina `torch_dtype=torch.bfloat16` para executar o pipeline em meia-precisão. Reduzir a precisão do tipo de dado aumenta a velocidade porque leva menos tempo para realizar computações em precisão mais baixa.
52
+
53
+ ```py
54
+ import torch
55
+ import time
56
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
57
+
58
+ pipeline = DiffusionPipeline.from_pretrained(
59
+ "stabilityai/stable-diffusion-xl-base-1.0",
60
+ torch_dtype=torch.bfloat16,
61
+ device_map="cuda"
62
+ )
63
+ ```
64
+
65
+ - Use um agendador mais rápido, como [`DPMSolverMultistepScheduler`], que requer apenas ~20-25 passos.
66
+ - Defina `num_inference_steps` para um valor menor. Reduzir o número de passos de inferência reduz o número total de computações. No entanto, isso pode resultar em menor qualidade de geração.
67
+
68
+ ```py
69
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
70
+
71
+ prompt = """
72
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
73
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
74
+ """
75
+
76
+ start_time = time.perf_counter()
77
+ image = pipeline(prompt).images[0]
78
+ end_time = time.perf_counter()
79
+
80
+ print(f"Geração de imagem levou {end_time - start_time:.3f} segundos")
81
+ ```
82
+
83
+ ## Qualidade de geração
84
+
85
+ Muitos modelos de difusão modernos entregam imagens de alta qualidade imediatamente. No entanto, você ainda pode melhorar a qualidade de geração experimentando o seguinte.
86
+
87
+ - Experimente um prompt mais detalhado e descritivo. Inclua detalhes como o meio da imagem, assunto, estilo e estética. Um prompt negativo também pode ajudar, guiando um modelo para longe de características indesejáveis usando palavras como baixa qualidade ou desfocado.
88
+
89
+ ```py
90
+ import torch
91
+ from diffusers import DiffusionPipeline
92
+
93
+ pipeline = DiffusionPipeline.from_pretrained(
94
+ "stabilityai/stable-diffusion-xl-base-1.0",
95
+ torch_dtype=torch.bfloat16,
96
+ device_map="cuda"
97
+ )
98
+
99
+ prompt = """
100
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
101
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
102
+ """
103
+ negative_prompt = "low quality, blurry, ugly, poor details"
104
+ pipeline(prompt, negative_prompt=negative_prompt).images[0]
105
+ ```
106
+
107
+ Para mais detalhes sobre como criar prompts melhores, consulte a documentação sobre [Técnicas de prompt](./using-diffusers/weighted_prompts).
108
+
109
+ - Experimente um agendador diferente, como [`HeunDiscreteScheduler`] ou [`LMSDiscreteScheduler`], que sacrifica velocidade de geração por qualidade.
110
+
111
+ ```py
112
+ import torch
113
+ from diffusers import DiffusionPipeline, HeunDiscreteScheduler
114
+
115
+ pipeline = DiffusionPipeline.from_pretrained(
116
+ "stabilityai/stable-diffusion-xl-base-1.0",
117
+ torch_dtype=torch.bfloat16,
118
+ device_map="cuda"
119
+ )
120
+ pipeline.scheduler = HeunDiscreteScheduler.from_config(pipeline.scheduler.config)
121
+
122
+ prompt = """
123
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
124
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
125
+ """
126
+ negative_prompt = "low quality, blurry, ugly, poor details"
127
+ pipeline(prompt, negative_prompt=negative_prompt).images[0]
128
+ ```
129
+
130
+ ## Próximos passos
131
+
132
+ Diffusers oferece otimizações mais avançadas e poderosas, como [group-offloading](./optimization/memory#group-offloading) e [compilação regional](./optimization/fp16#regional-compilation). Para saber mais sobre como maximizar o desempenho, consulte a seção sobre Otimização de Inferência.
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/_toctree.yml ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - title: 开始Diffusers
2
+ sections:
3
+ - local: index
4
+ title: Diffusers
5
+ - local: installation
6
+ title: 安装
7
+ - local: quicktour
8
+ title: 快速入门
9
+ - local: stable_diffusion
10
+ title: 有效和高效的扩散
11
+
12
+ - title: DiffusionPipeline
13
+ isExpanded: false
14
+ sections:
15
+ - local: using-diffusers/schedulers
16
+ title: Load schedulers and models
17
+ - local: tutorials/autopipeline
18
+ title: AutoPipeline
19
+ - local: using-diffusers/guiders
20
+ title: Guiders
21
+
22
+ - title: Adapters
23
+ isExpanded: false
24
+ sections:
25
+ - local: tutorials/using_peft_for_inference
26
+ title: LoRA
27
+
28
+ - title: Inference
29
+ isExpanded: false
30
+ sections:
31
+ - local: training/distributed_inference
32
+ title: Distributed inference
33
+
34
+ - title: Inference optimization
35
+ isExpanded: false
36
+ sections:
37
+ - local: optimization/fp16
38
+ title: Accelerate inference
39
+ - local: optimization/cache
40
+ title: Caching
41
+ - local: optimization/memory
42
+ title: Reduce memory usage
43
+ - local: optimization/speed-memory-optims
44
+ title: Compile and offloading quantized models
45
+ - title: Community optimizations
46
+ sections:
47
+ - local: optimization/pruna
48
+ title: Pruna
49
+ - local: optimization/xformers
50
+ title: xFormers
51
+ - local: optimization/tome
52
+ title: Token merging
53
+ - local: optimization/deepcache
54
+ title: DeepCache
55
+ - local: optimization/tgate
56
+ title: TGATE
57
+ - local: optimization/xdit
58
+ title: xDiT
59
+ - local: optimization/para_attn
60
+ title: ParaAttention
61
+
62
+ - title: Hybrid Inference
63
+ isExpanded: false
64
+ sections:
65
+ - local: hybrid_inference/overview
66
+ title: Overview
67
+ - local: hybrid_inference/vae_encode
68
+ title: VAE Encode
69
+ - local: hybrid_inference/api_reference
70
+ title: API Reference
71
+
72
+ - title: Modular Diffusers
73
+ isExpanded: false
74
+ sections:
75
+ - local: modular_diffusers/overview
76
+ title: Overview
77
+ - local: modular_diffusers/quickstart
78
+ title: Quickstart
79
+ - local: modular_diffusers/modular_diffusers_states
80
+ title: States
81
+ - local: modular_diffusers/pipeline_block
82
+ title: ModularPipelineBlocks
83
+ - local: modular_diffusers/sequential_pipeline_blocks
84
+ title: SequentialPipelineBlocks
85
+ - local: modular_diffusers/loop_sequential_pipeline_blocks
86
+ title: LoopSequentialPipelineBlocks
87
+ - local: modular_diffusers/auto_pipeline_blocks
88
+ title: AutoPipelineBlocks
89
+ - local: modular_diffusers/modular_pipeline
90
+ title: ModularPipeline
91
+ - local: modular_diffusers/components_manager
92
+ title: ComponentsManager
93
+
94
+ - title: Training
95
+ isExpanded: false
96
+ sections:
97
+ - local: training/overview
98
+ title: Overview
99
+ - local: training/adapt_a_model
100
+ title: Adapt a model to a new task
101
+ - local: tutorials/basic_training
102
+ title: 训练扩散模型
103
+ - title: Models
104
+ sections:
105
+ - local: training/text2image
106
+ title: Text-to-image
107
+ - local: training/kandinsky
108
+ title: Kandinsky 2.2
109
+ - local: training/wuerstchen
110
+ title: Wuerstchen
111
+ - local: training/controlnet
112
+ title: ControlNet
113
+ - local: training/instructpix2pix
114
+ title: InstructPix2Pix
115
+ - title: Methods
116
+ sections:
117
+ - local: training/text_inversion
118
+ title: Textual Inversion
119
+ - local: training/dreambooth
120
+ title: DreamBooth
121
+ - local: training/lora
122
+ title: LoRA
123
+
124
+ - title: Model accelerators and hardware
125
+ isExpanded: false
126
+ sections:
127
+ - local: optimization/onnx
128
+ title: ONNX
129
+ - local: optimization/open_vino
130
+ title: OpenVINO
131
+ - local: optimization/coreml
132
+ title: Core ML
133
+ - local: optimization/mps
134
+ title: Metal Performance Shaders (MPS)
135
+ - local: optimization/habana
136
+ title: Intel Gaudi
137
+ - local: optimization/neuron
138
+ title: AWS Neuron
139
+
140
+ - title: Specific pipeline examples
141
+ isExpanded: false
142
+ sections:
143
+ - local: using-diffusers/anyflow
144
+ title: AnyFlow
145
+ - local: using-diffusers/consisid
146
+ title: ConsisID
147
+ - local: using-diffusers/helios
148
+ title: Helios
149
+
150
+ - title: Resources
151
+ isExpanded: false
152
+ sections:
153
+ - title: Task recipes
154
+ sections:
155
+ - local: community_projects
156
+ title: Projects built with Diffusers
157
+ - local: conceptual/philosophy
158
+ title: Philosophy
159
+ - local: conceptual/contribution
160
+ title: How to contribute?
161
+ - local: conceptual/ethical_guidelines
162
+ title: Diffusers' Ethical Guidelines
163
+ - local: conceptual/evaluation
164
+ title: Evaluating Diffusion Models
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/community_projects.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据Apache许可证,版本2.0("许可证")授权;除非符合许可证,否则不得使用此文件。您可以在
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 获取许可证的副本。
8
+
9
+ 除非适用法律要求或书面同意,根据许可证分发的软件是按"原样"分发的,没有任何形式的明示或暗示的担保或条件。有关许可证的特定语言,请参阅许可证。
10
+ -->
11
+
12
+ # 社区项目
13
+
14
+ 欢迎来到社区项目。这个空间致力于展示我们充满活力的社区使用`diffusers`库创建的令人难以置信的工作和创新应用。
15
+
16
+ 本节旨在:
17
+
18
+ - 突出使用`diffusers`构建的多样化和鼓舞人心的项目
19
+ - 促进我们社区内的知识共享
20
+ - 提供如何利用`diffusers`的实际例子
21
+
22
+ 探索愉快,感谢您成为Diffusers社区的一部分!
23
+
24
+ <table>
25
+ <tr>
26
+ <th>项目名称</th>
27
+ <th>描述</th>
28
+ </tr>
29
+ <tr style="border-top: 2px solid black">
30
+ <td><a href="https://github.com/PKU-YuanGroup/Helios"> helios </a></td>
31
+ <td>Helios:比1.3B更低开销、更快且更强的14B的实时长视频生成模型</td>
32
+ </tr>
33
+ <tr style="border-top: 2px solid black">
34
+ <td><a href="https://github.com/PKU-YuanGroup/ConsisID"> consisid </a></td>
35
+ <td>ConsisID:零样本身份保持的文本到视频生成模型</td>
36
+ </tr>
37
+ <tr style="border-top: 2px solid black">
38
+ <td><a href="https://github.com/carson-katri/dream-textures"> dream-textures </a></td>
39
+ <td>Stable Diffusion内置到Blender</td>
40
+ </tr>
41
+ <tr style="border-top: 2px solid black">
42
+ <td><a href="https://github.com/megvii-research/HiDiffusion"> HiDiffusion </a></td>
43
+ <td>仅通过添加一行代码即可提高扩散模型的分辨率和速度</td>
44
+ </tr>
45
+ <tr style="border-top: 2px solid black">
46
+ <td><a href="https://github.com/lllyasviel/IC-Light"> IC-Light </a></td>
47
+ <td>IC-Light是一个用于操作图像照明的项目</td>
48
+ </tr>
49
+ <tr style="border-top: 2px solid black">
50
+ <td><a href="https://github.com/InstantID/InstantID"> InstantID </a></td>
51
+ <td>InstantID:零样本身份保留生成在几秒钟内</td>
52
+ </tr>
53
+ <tr style="border-top: 2px solid black">
54
+ <td><a href="https://github.com/Sanster/IOPaint"> IOPaint </a></td>
55
+ <td>由SOTA AI模型驱动的图像修复工具。从您的图片中移除任何不需要的物体、缺陷、人物,或擦除并替换(由stable_diffusion驱动)图片上的任何内容。</td>
56
+ </tr>
57
+ <tr style="border-top: 2px solid black">
58
+ <td><a href="https://github.com/bmaltais/kohya_ss"> Kohya </a></td>
59
+ <td>Kohya的Stable Diffusion训练器的Gradio GUI</td>
60
+ </tr>
61
+ <tr style="border-top: 2px solid black">
62
+ <td><a href="https://github.com/magic-research/magic-animate"> MagicAnimate </a></td>
63
+ <td>MagicAnimate:使用扩散模型进行时间一致的人体图像动画</td>
64
+ </tr>
65
+ <tr style="border-top: 2px solid black">
66
+ <td><a href="https://github.com/levihsu/OOTDiffusion"> OOTDiffusion </a></td>
67
+ <td>基于潜在扩散的虚拟试穿控制</td>
68
+ </tr>
69
+ <tr style="border-top: 2px solid black">
70
+ <td><a href="https://github.com/vladmandic/automatic"> SD.Next </a></td>
71
+ <td>SD.Next: Stable Diffusion 和其他基于Diffusion的生成图像模型的高级实现</td>
72
+ </tr>
73
+ <tr style="border-top: 2px solid black">
74
+ <td><a href="https://github.com/ashawkey/stable-dreamfusion"> stable-dreamfusion </a></td>
75
+ <td>使用 NeRF + Diffusion 进行文本到3D & 图像到3D & 网格导出</td>
76
+ </tr>
77
+ <tr style="border-top: 2px solid black">
78
+ <td><a href="https://github.com/HVision-NKU/StoryDiffusion"> StoryDiffusion </a></td>
79
+ <td>StoryDiffusion 可以通过生成一致的图像和视频来创造一个神奇的故事。</td>
80
+ </tr>
81
+ <tr style="border-top: 2px solid black">
82
+ <td><a href="https://github.com/cumulo-autumn/StreamDiffusion"> StreamDiffusion </a></td>
83
+ <td>实时交互生成的管道级解决方案</td>
84
+ </tr>
85
+ <tr style="border-top: 2px solid black">
86
+ <td><a href="https://github.com/Netwrck/stable-diffusion-server"> Stable Diffusion Server </a></td>
87
+ <td>配置用于使用一个 stable diffusion 模型进行修复/生成/img2img 的服务器</td>
88
+ </tr>
89
+ <tr style="border-top: 2px solid black">
90
+ <td><a href="https://github.com/suzukimain/auto_diffusers"> Model Search </a></td>
91
+ <td>在 Civitai 和 Hugging Face 上搜索模型</td>
92
+ </tr>
93
+ <tr style="border-top: 2px solid black">
94
+ <td><a href="https://github.com/beinsezii/skrample"> Skrample </a></td>
95
+ <td>完全模块化的调度器功能,具有一流的 diffusers 集成。</td>
96
+ </tr>
97
+ </table>
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/conceptual/contribution.md ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. 保留所有权利。
2
+
3
+ 根据Apache许可证2.0版("许可证")授权;除非符合许可证要求,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,根据许可证分发的软件均按"原样"分发,不附带任何明示或暗示的担保或条件。有关许可证下特定语言规定的权限和限制,请参阅许可证。
8
+ -->
9
+
10
+ # 如何为Diffusers 🧨做贡献
11
+
12
+ 我们❤️来自开源社区的贡献!欢迎所有人参与,所有类型的贡献——不仅仅是代码——都受到重视和赞赏。回答问题、帮助他人、主动交流以及改进文档对社区都极具价值,所以如果您愿意参与,请不要犹豫!
13
+
14
+ 我们鼓励每个人先在公开Discord频道里打招呼👋。在那里我们讨论扩散模型的最新趋势、提出问题、展示个人项目、互相协助贡献,或者只是闲聊☕。<a href="https://Discord.gg/G7tWnz98XR"><img alt="加入Discord社区" src="https://img.shields.io/discord/823813159592001537?color=5865F2&logo=discord&logoColor=white"></a>
15
+
16
+ 无论您选择以何种方式贡献,我们都致力于成为一个开放、友好、善良的社区。请阅读我们的[行为准则](https://github.com/huggingface/diffusers/blob/main/CODE_OF_CONDUCT.md),并在互动时注意遵守。我们也建议您了解指导本项目的[伦理准则](https://huggingface.co/docs/diffusers/conceptual/ethical_guidelines),并请您遵循同样的透明度和责任原则。
17
+
18
+ 我们高度重视社区的反馈,所以如果您认为自己有能帮助改进库的有价值反馈,请不要犹豫说出来——每条消息、评论、issue和拉取请求(PR)都会被阅读和考虑。
19
+
20
+ ## 概述
21
+
22
+ 您可以通过多种方式做出贡献,从在issue和讨论区回答问题,到向核心库添加新的diffusion模型。
23
+
24
+ 下面我们按难度升序列出不同的贡献方式,所有方式对社区都很有价值:
25
+
26
+ * 1. 在[Diffusers讨论论坛](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers)或[Discord](https://discord.gg/G7tWnz98XR)上提问和回答问题
27
+ * 2. 在[GitHub Issues标签页](https://github.com/huggingface/diffusers/issues/new/choose)提交新issue,或在[GitHub Discussions标签页](https://github.com/huggingface/diffusers/discussions/new/choose)发起新讨论
28
+ * 3. 在[GitHub Issues标签页](https://github.com/huggingface/diffusers/issues)解答issue,或在[GitHub Discussions标签页](https://github.com/huggingface/diffusers/discussions)参与讨论
29
+ * 4. 解决标记为"Good first issue"的简单问题,详见[此处](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
30
+ * 5. 参与[文档](https://github.com/huggingface/diffusers/tree/main/docs/source)建设
31
+ * 6. 贡献[社区Pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3Acommunity-examples)
32
+ * 7. 完善[示例代码](https://github.com/huggingface/diffusers/tree/main/examples)
33
+ * 8. 解决标记为"Good second issue"的中等难度问题,详见[此处](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+second+issue%22)
34
+ * 9. 添加新pipeline/模型/调度器,参见["New Pipeline/Model"](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22)和["New scheduler"](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22)类issue。此类贡献请先阅读[设计哲学](https://huggingface.co/docs/diffusers/main/zh/conceptual/philosophy)
35
+
36
+ 重申:**所有贡献对社区都具有重要价值。**下文将详细说明各类贡献方式。
37
+
38
+ 对于4-9类贡献,您需要提交PR(拉取请求),具体操作详见[如何提交PR](#how-to-open-a-pr)章节。
39
+
40
+ ### 1. 在Diffusers讨论区或Discord提问与解答
41
+
42
+ 任何与Diffusers库相关的问题或讨论都可以发布在[官方论坛](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/)或[Discord频道](https://discord.gg/G7tWnz98XR),包括但不限于:
43
+ - 分享训练/推理实验报告
44
+ - 展示个人项目
45
+ - 咨询非官方训练示例
46
+ - 项目提案
47
+ - 通用反馈
48
+ - 论文解读
49
+ - 基于Diffusers库的个人项目求助
50
+ - 一般性问题
51
+ - 关于diffusion模型的伦理讨论
52
+ - ...
53
+
54
+ 论坛/Discord上的每个问题都能促使社区公开分享知识,很可能帮助未来遇到相同问题的初学者。请务必提出您的疑问。
55
+ 同样地,通过回答问题您也在为社区创造公共知识文档,这种贡献极具价值。
56
+
57
+ **请注意**:提问/回答时投入的精力越多,产生的公共知识质量就越高。精心构建的问题与专业解答能形成高质量知识库,而表述不清的问题则可能降低讨论价值。
58
+
59
+ 低质量的问题或回答会降低公共知识库的整体质量。
60
+ 简而言之,高质量的问题或回答应具备*精确性*、*简洁性*、*相关性*、*易于理解*、*可访问性*和*格式规范/表述清晰*等特质。更多详情请参阅[如何提交优质议题](#how-to-write-a-good-issue)章节。
61
+
62
+ **关于渠道的说明**:
63
+ [*论坛*](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63)的内容能被谷歌等搜索引擎更好地收录,且帖子按热度而非时间排序,便于查找历史问答。此外,论坛内容更容易被直接链接引用。
64
+ 而*Discord*采用即时聊天模式,适合快速交流。虽然在Discord上可能更快获得解答,但信息会随时间淹没,且难以回溯历史讨论。因此我们强烈建议在论坛发布优质问答,以构建可持续的社区知识库。若Discord讨论产生有价值结论,建议将成果整理发布至论坛以惠及更多读者。
65
+
66
+ ### 2. 在GitHub议题页提交新议题
67
+
68
+ 🧨 Diffusers库的稳健性离不开用户的问题反馈,感谢您的报错。
69
+
70
+ 请注意:GitHub议题仅限处理与Diffusers库代码直接相关的技术问题、错误报告、功能请求或库设计反馈。
71
+ 简言之,**与Diffusers库代码(含文档)无关**的内容应发布至[论坛](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63)或[Discord](https://discord.gg/G7tWnz98XR)。
72
+
73
+ **提交新议题时请遵循以下准则**:
74
+ - 确认是否已有类似议题(使用GitHub议题页的搜索栏)
75
+ - 请勿在现有议题下追加新问题。若存在高度关联议题,应新建议题并添加相关链接
76
+ - 确保使用英文提交。非英语用户可通过[DeepL](https://www.deepl.com/translator)等免费工具翻译
77
+ - 检查升级至最新Diffusers版本是否能解决问题。提交前请确认`python -c "import diffusers; print(diffusers.__version__)"`显示的版本号不低于最新版本
78
+ - 记请记住,你在提交新issue时投入的精力越多,得到的回答质量就越高,Diffusers项目的整体issue质量也会越好。
79
+
80
+ 新issue通常包含以下内容:
81
+
82
+ #### 2.1 可复现的最小化错误报告
83
+
84
+ 错误报告应始终包含可复现的代码片段,并尽可能简洁明了。具体而言:
85
+ - 尽量缩小问题范围,**不要直接粘贴整个代码文件**
86
+ - 规范代码格式
87
+ - 除Diffusers依赖库外,不要包含其他外部库
88
+ - **务必**提供环境信息:可在终端运行`diffusers-cli env`命令,然后将显示的信息复制到issue中
89
+ - 详细说明问题。如果读者不清楚问题所在及其影响,就无法解决问题
90
+ - **确保**读者能以最小成本复现问题。如果代码片段因缺少库或未定义变量而无法运行,读者将无法提供帮助。请确保提供的可复现代码尽可能精简,可直接复制到Python shell运行
91
+ - 如需特定模型/数据集复现问题,请确保读者能获取这些资源。可将模型/数据集上传至[Hub](https://huggingface.co)便于下载。尽量保持模型和数据集体积最小化,降低复现难度
92
+
93
+ 更多信息请参阅[如何撰写优质issue](#how-to-write-a-good-issue)章节。
94
+
95
+ 提交错误报告请点击[此处](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&projects=&template=bug-report.yml)。
96
+
97
+ #### 2.2 功能请求
98
+
99
+ 优质的功能请求应包含以下要素:
100
+
101
+ 1. 首先说明动机:
102
+ * 是否与库的使用痛点相关?若是,请解释原因,最好提供演示问题的代码片段
103
+ * 是否因项目需求产生?我们很乐意了解详情!
104
+ * 是否是你已实现且认为对社区有价值的功能?请说明它为你解决了什么问题
105
+ 2. 用**完整段落**描述功能特性
106
+ 3. 提供**代码片段**演示预期用法
107
+ 4. 如涉及论文,请附上链接
108
+ 5. 可补充任何有助于理解的辅助材料(示意图、截图等)
109
+
110
+ 提交功能请求请点击[此处](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feature_request.md&title=)。
111
+
112
+ #### 2.3 设计反馈
113
+
114
+ 关于库设计的反馈(无论正面还是负面)能极大帮助核心维护者打造更友好的库。要了解当前设计理念,请参阅[此文档](https://huggingface.co/docs/diffusers/conceptual/philosophy)如果您认为某个设计选择与当前理念不符,请说明原因及改进建议。如果某个设计选择因过度遵循理念而限制了使用场景,也请解释原因并提出调整方案。
115
+ 若某个设计对您特别实用,请同样留下备注——这对未来的设计决策极具参考价值。
116
+
117
+ 您可通过[此链接](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=)提交设计反馈。
118
+
119
+ #### 2.4 技术问题
120
+
121
+ 技术问题主要涉及库代码的实现逻辑或特定功能模块的作用。提问时请务必:
122
+ - 附上相关代码链接
123
+ - 详细说明难以理解的具体原因
124
+
125
+ 技术问题提交入口:[点击此处](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&template=bug-report.yml)
126
+
127
+ #### 2.5 新模型/调度器/pipeline提案
128
+
129
+ 若diffusion模型社区发布了您希望集成到Diffusers库的新模型、pipeline或调度器,请提供以下信息:
130
+ * 简要说明并附论文或发布链接
131
+ * 开源实现链接(如有)
132
+ * 模型权重下载链接(如已公开)
133
+
134
+ 若您愿意参与开发,请告知我们以便指导。另请尝试通过GitHub账号标记原始组件作者。
135
+
136
+ 提案提交地址:[新建请求](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=New+model%2Fpipeline%2Fscheduler&template=new-model-addition.yml)
137
+
138
+ ### 3. 解答GitHub问题
139
+
140
+ 回答GitHub问题可能需要Diffusers的技术知识,但我们鼓励所有人尝试参与——即使您对答案不完全正确。高质量回答的建议:
141
+ - 保持简洁精炼
142
+ - 严格聚焦问题本身
143
+ - 提供代码/论文等佐证材料
144
+ - 优先用代码说话:若代码片段能解决问题,请提供完整可复现代码
145
+
146
+ 许多问题可能存在离题、重复或无关情况。您可以通过以下方式协助维护者:
147
+ - 引导提问者精确描述问题
148
+ - 标记重复issue并附原链接
149
+ - 推荐用户至[论坛](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63)或[Discord](https://discord.gg/G7tWnz98XR)
150
+
151
+ 在确认提交的Bug报告正确且需要修改源代码后,请继续阅读以下章节内容。
152
+
153
+ 以下所有贡献都需要提交PR(拉取请求)。具体操作步骤详见[如何提交PR](#how-to-open-a-pr)章节。
154
+
155
+ ### 4. 修复"Good first issue"类问题
156
+
157
+ 标有[Good first issue](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)标签的问题通常已说明解决方案建议,便于修复。若该问题尚未关闭且您想尝试解决,只需留言"我想尝试解决这个问题"。通常有三种情况:
158
+ - a.) 问题描述已提出解决方案。若您认可该方案,可直接提交PR或草稿PR进行修复
159
+ - b.) 问题描述未提出解决方案。您可询问修复建议,Diffusers团队会尽快回复。若有成熟解决方案,也可直接提交PR
160
+ - c.) 已有PR但问题未关闭。若原PR停滞,可新开PR并关联原PR(开源社区常见现象)。若PR仍活跃,您可通过建议、审查或协作等方式帮助原作者
161
+
162
+ ### 5. 文档贡献
163
+
164
+ 优秀库**必然**拥有优秀文档!官方文档是新用户的首要接触点,因此文档贡献具有**极高价值**。贡献形式包括:
165
+ - 修正拼写/语法错误
166
+ - 修复文档字符串格式错误(如显示异常或链接失效)
167
+ - 修正文档字符串中张量的形状/维度描述
168
+ - 优化晦涩或错误的说明
169
+ - 更新过时代码示例
170
+ - 文档翻译
171
+
172
+ [官方文档页面](https://huggingface.co/docs/diffusers/index)所有内容均属可修改范围,对应[文档源文件](https://github.com/huggingface/diffusers/tree/main/docs/source)可进行编辑。修改前请查阅[验证说明](https://github.com/huggingface/diffusers/tree/main/docs)。
173
+
174
+ ### 6. 贡献社区流程
175
+
176
+ > [!TIP]
177
+ > 阅读[社区流程](../using-diffusers/custom_pipeline_overview#community-pipelines)指南了解GitHub与Hugging Face Hub社区流程的区别。若想了解我们设立社区流程的原因,请查看GitHub Issue [#841](https://github.com/huggingface/diffusers/issues/841)(简而言之,我们无法维护diffusion模型所有可能的推理使用方式,但也不希望限制社区构建这些流程)。
178
+
179
+ 贡献社区流程是向社区分享创意与成果的绝佳方式。您可以在[`DiffusionPipeline`]基础上构建流程,任何人都能通过设置`custom_pipeline`参数加载使用。本节将指导您创建一个简单的"单步"流程——UNet仅执行单次前向传播并调用调度器一次。
180
+
181
+ 1. 为社区流程创建one_step_unet.py文件。只要用户已安装相关包,该文件可包含任意所需包。确保仅有一个继承自[`DiffusionPipeline`]的流程类,用于从Hub加载模型权重和调度器配置。在`__init__`函数中添加UNet和调度器。
182
+
183
+ 同时添加`register_modules`函数,确保您的流程及其组件可通过[`~DiffusionPipeline.save_pretrained`]保存。
184
+
185
+ ```py
186
+ from diffusers import DiffusionPipeline
187
+ import torch
188
+
189
+ class UnetSchedulerOneForwardPipeline(DiffusionPipeline):
190
+ def __init__(self, unet, scheduler):
191
+ super().__init__()
192
+
193
+ self.register_modules(unet=unet, scheduler=scheduler)
194
+ ```
195
+
196
+ 2. 在前向传播中(建议定义为`__call__`),可添加任意功能。对于"单步"流程,创建随机图像并通过设置`timestep=1`调用UNet和调度器一次。
197
+
198
+ ```py
199
+ from diffusers import DiffusionPipeline
200
+ import torch
201
+
202
+ class UnetSchedulerOneForwardPipeline(DiffusionPipeline):
203
+ def __init__(self, unet, scheduler):
204
+ super().__init__()
205
+
206
+ self.register_modules(unet=unet, scheduler=scheduler)
207
+
208
+ def __call__(self):
209
+ image = torch.randn(
210
+ (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size),
211
+ )
212
+ timestep = 1
213
+
214
+ model_output = self.unet(image, timestep).sample
215
+ scheduler_output = self.scheduler.step(model_output, timestep, image).prev_sample
216
+
217
+ return scheduler_output
218
+ ```
219
+
220
+ 现在您可以通过传入UNet和调度器来运行流程,若流程结构相同也可加载预训练权重。
221
+
222
+ ```python
223
+ from diffusers import DDPMScheduler, UNet2DModel
224
+
225
+ scheduler = DDPMScheduler()
226
+ unet = UNet2DModel()
227
+
228
+ pipeline = UnetSchedulerOneForwardPipeline(unet=unet, scheduler=scheduler)
229
+ output = pipeline()
230
+ # 加载预训练权重
231
+ pipeline = UnetSchedulerOneForwardPipeline.from_pretrained("google/ddpm-cifar10-32", use_safetensors=True)
232
+ output = pipeline()
233
+ ```
234
+
235
+ 您可以选择将pipeline作为GitHub社区pipeline或Hub社区pipeline进行分享。
236
+
237
+ <hfoptions id="pipeline类型">
238
+ <hfoption id="GitHub pipeline">
239
+
240
+ 通过向Diffusers[代码库](https://github.com/huggingface/diffusers)提交拉取请求来分享GitHub pipeline,将one_step_unet.py文件添加到[examples/community](https://github.com/huggingface/diffusers/tree/main/examples/community)子文件夹中。
241
+
242
+ </hfoption>
243
+ <hfoption id="Hub pipeline">
244
+
245
+ 通过在Hub上创建模型仓库并上传one_step_unet.py文件来分享Hub pipeline。
246
+
247
+ </hfoption>
248
+ </hfoptions>
249
+
250
+ ### 7. 贡献训练示例
251
+
252
+ Diffusers训练示例是位于[examples](https://github.com/huggingface/diffusers/tree/main/examples)目录下的训练脚本集合。
253
+
254
+ 我们支持两种类型的训练示例:
255
+
256
+ - 官方训练示例
257
+ - 研究型训练示例
258
+
259
+ 研究型训练示例位于[examples/research_projects](https://github.com/huggingface/diffusers/tree/main/examples/research_projects),而官方训练示例包含[examples](https://github.com/huggingface/diffusers/tree/main/examples)目录下除`research_projects`和`community`外的所有文件夹。
260
+ 官方训练示例由Diffusers核心维护者维护,研究型训练示例则由社区维护。
261
+ 这与[6. 贡献社区pipeline](#6-contribute-a-community-pipeline)中关于官方pipeline与社区pipeline的原因相同:核心维护者不可能维护diffusion模型的所有可能训练方法。
262
+ 如果Diffusers核心维护者和社区认为某种训练范式过于实验性或不够普及,相应训练代码应放入`research_projects`文件夹并由作者维护。
263
+
264
+ 官方训练和研究型示例都包含一个目录,其中含有一个或多个训练脚本、`requirements.txt`文件和`README.md`文件。用户使用时需要先克隆代码库:
265
+
266
+ ```bash
267
+ git clone https://github.com/huggingface/diffusers
268
+ ```
269
+
270
+ 并安装训练所需的所有额外依赖:
271
+
272
+ ```bash
273
+ cd diffusers
274
+ pip install -r examples/<your-example-folder>/requirements.txt
275
+ ```
276
+
277
+ 因此添加示例时,`requirements.txt`文件应定义训练示例所需的所有pip依赖项,安装完成后用户即可运行示例训练脚本。可参考[DreamBooth的requirements.txt文件](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/requirements.txt)。
278
+ - 运行示例所需的所有代码应集中在单个Python文件中
279
+ - 用户应能通过命令行`python <your-example>.py --args`直接运行示例
280
+ - **示例**应保持简洁,主要展示如何使用Diffusers进行训练。示例脚本的目的**不是**创建最先进的diffusion模型,而是复现已知训练方案,避免添加过多自定义逻辑。因此,这些示例也力求成为优质的教学材料。
281
+
282
+ 提交示例时,强烈建议参考现有示例(如[dreambooth](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth.py))来了解规范格式。
283
+ 我们强烈建议贡献者使用[Accelerate库](https://github.com/huggingface/accelerate),因其与Diffusers深度集成。
284
+ 当示例脚本完成后,请确保添加详细的`README.md`说明使用方法,包括:
285
+ - 运行示例的具体命令(示例参见[此处](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth#running-locally-with-pytorch))
286
+ - 训练结果链接(日志/模型等),展示用户可预期的效果(示例参见[此处](https://api.wandb.ai/report/patrickvonplaten/xm6cd5q5))
287
+ - 若添加非官方/研究性训练示例,**必须注明**维护者信息(含Git账号),格式参照[此处](https://github.com/huggingface/diffusers/tree/main/examples/research_projects/intel_opts#diffusers-examples-with-intel-optimizations)
288
+
289
+ 贡献官方训练示例时,还需在对应目录添加测试文件(如[examples/dreambooth/test_dreambooth.py](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/test_dreambooth.py)),非官方示例无需此步骤。
290
+
291
+ ### 8. 处理"Good second issue"类问题
292
+
293
+ 标有[Good second issue](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+second+issue%22)标签的问题通常比[Good first issues](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)更复杂。
294
+ 这类问题的描述通常不会提供详细解决指引,需要贡献者对库有较深理解。
295
+ 若您想解决此类问题,可直接提交PR并关联对应issue。若已有未合并的PR,请分析原因后提交改进版。需注意,Good second issue类PR的合并难度通常高于good first issues。在需要帮助的时候请不要犹豫,大胆的向核心维护者询问。
296
+
297
+ ### 9. 添加管道、模型和调度器
298
+
299
+ 管道(pipelines)、模型(models)和调度器(schedulers)是Diffusers库中最重要的组成部分。它们提供了对最先进diffusion技术的便捷访问,使得社区能够构建强大的生成式AI应用。
300
+
301
+ 通过添加新的模型、管道或调度器,您可能为依赖Diffusers的任何用户界面开启全新的强大用例,这对整个生成式AI生态系统具有巨大价值。
302
+
303
+ Diffusers针对这三类组件都有一些开放的功能请求——如果您还不确定要添加哪个具体组件,可以浏览以下链接:
304
+ - [模型或管道](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22)
305
+ - [调度器](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22)
306
+
307
+ 在添加任何组件之前,强烈建议您阅读[设计哲学指南](philosophy),以更好地理解这三类组件的设计理念。请注意,如果添加的模型、调度器或管道与我们的设计理念存在严重分歧,我们将无法合并,因为这会导致API不一致。如果您从根本上不同意某个设计选择,请改为提交[反馈问题](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=),以便讨论是否应该更改库中的特定设计模式/选择,以及是否更新我们的设计哲学。保持库内的一致性对我们非常重要。
308
+
309
+ 请确保在PR中添加原始代码库/论文的链接,并最好直接在PR中@原始作者,以便他们可以跟踪进展并在有疑问时提供帮助。
310
+
311
+ 如果您在PR过程中遇到不确定或卡住的情况,请随时留言请求初步审查或帮助。
312
+
313
+ #### 复制机制(Copied from)
314
+
315
+ 在添加任何管道、模型或调度器代码时,理解`# Copied from`机制是独特且重要的。您会在整个Diffusers代码库中看到这种机制,我们使用它的原因是为了保持代码库易于理解和维护。用`# Copied from`机制标记代码会强制标记的代码与复制来源的代码完全相同。这使得每当您运行`make fix-copies`时,可以轻松更新并将更改传播到多个文件。
316
+
317
+ 例如,在下面的代码示例中,[`~diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput`]是原始代码,而`AltDiffusionPipelineOutput`使用`# Copied from`机制来复制它。唯一的区别是将类前缀从`Stable`改为`Alt`。
318
+
319
+ ```py
320
+ # 从 diffusers.pipelines.stable_diffusion.pipeline_output.StableDiffusionPipelineOutput 复制并将 Stable 替换为 Alt
321
+ class AltDiffusionPipelineOutput(BaseOutput):
322
+ """
323
+ Output class for Alt Diffusion pipelines.
324
+
325
+ Args:
326
+ images (`List[PIL.Image.Image]` or `np.ndarray`)
327
+ List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
328
+ num_channels)`.
329
+ nsfw_content_detected (`List[bool]`)
330
+ List indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content or
331
+ `None` if safety checking could not be performed.
332
+ """
333
+ ```
334
+
335
+ 要了解更多信息,请阅读[~不要~重复自己*](https://huggingface.co/blog/transformers-design-philosophy#4-machine-learning-models-are-static)博客文章的相应部分。
336
+
337
+ ## 如何撰写优质问题
338
+
339
+ **问题描述越清晰,被快速解决的可能性就越高。**
340
+
341
+ 1. 确保使用了正确的issue模板。您可以选择*错误报告*、*功能请求*、*API设计反馈*、*新模型/流水线/调度器添加*、*论坛*或空白issue。在[新建issue](https://github.com/huggingface/diffusers/issues/new/choose)时务必选择正确的模板。
342
+ 2. **精确描述**:为issue起一个恰当的标题。尽量用最简练的语言描述问题。提交issue时越精确,理解问题和潜在解决方案所需的时间就越少。确保一个issue只针对一个问题,不要将多个问题放在同一个issue中。如果发现多个问题,请分别创建多个issue。如果是错误报告,请尽可能精确描述错误类型——不应只写"diffusers出错"。
343
+ 3. **可复现性**:无法复现的代码片段 == 无法解决问题。如果遇到错误,维护人员必须能够**复现**它。确保包含一个可以复制粘贴到Python解释器中复现问题的代码片段。确保您的代码片段是可运行的,即没有缺少导入或图像链接等问题。issue应包含错误信息和可直接复制粘贴以复现相同错误的代码片段。如果issue涉及本地模型权重或无法被读者访问的本地数据,则问题无法解决。如果无法共享数据或模型,请尝试创建虚拟模型或虚拟数据。
344
+ 4. **最小化原则**:通过尽可能简洁的描述帮助读者快速理解问题。删除所有与问题无关的代码/信息。如果发现错误,请创建最简单的代码示例来演示问题,不要一发现错误就把整个工作流程都转储到issue中。例如,如果在训练模型时某个阶段出现错误或训练过程中遇到问题时,应首先尝试理解训练代码的哪部分导致了错误,并用少量代码尝试复现。建议使用模拟数据替代完整数据集进行测试。
345
+ 5. 添加引用链接。当提及特定命名、方法或模型时,请务必提供引用链接以便读者理解。若涉及具体PR或issue,请确保添加对应链接。不要假设读者了解你所指内容。issue中引用链接越丰富越好。
346
+ 6. 规范格式。请确保规范格式化issue内容:Python代码使用代码语法块,错误信息使用标准代码语法。详见[GitHub官方格式文档](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)。
347
+ 7. 请将issue视为百科全书的精美词条,而非待解决的工单。每个规范撰写的issue不仅是向维护者有效传递问题的方式,更是帮助社区深入理解库特性的公共知识贡献。
348
+
349
+ ## 优质PR编写规范
350
+
351
+ 1. 保持风格统一。理解现有设计模式和语法规范,确保新增代码与代码库现有结构无缝衔接。显著偏离现有设计模式或用户界面的PR将不予合并。
352
+ 2. 聚焦单一问题。每个PR应当只解决一个明确问题,避免"顺手修复其他问题"的陷阱。包含多个无关修改的PR会极大增加审查难度。
353
+ 3. 如适用,建议添加代码片段演示新增功能的使用方法。
354
+ 4. PR标题应准确概括其核心贡献。
355
+ 5. 若PR针对某个issue,请在描述中注明issue编号以建立关联(也让关注该issue的用户知晓有人正在处理);
356
+ 6. 进行中的PR请在标题添加`[WIP]`前缀。这既能避免重复劳动,也可与待合并PR明确区分;
357
+ 7. 文本表述与格式要求请参照[优质issue编写规范](#how-to-write-a-good-issue);
358
+ 8. 确保现有测试用例全部通过;
359
+ 9. 必须添加高覆盖率测试。未经充分测试的代码不予合并。
360
+ - 若新增`@slow`测试,请使用`RUN_SLOW=1 python -m pytest tests/test_my_new_model.py`确保通过。
361
+ CircleCI不执行慢速测试,但GitHub Actions会每日夜间运行!
362
+ 10. 所有公开方法必须包含格式规范、兼容markdown的说明文档。可参考[`pipeline_latent_diffusion.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py)
363
+ 11. 由于代码库快速增长,必须确保不会添加明显增加仓库体积的文件(如图片、视频等非文本文件)。建议优先使用托管在hf.co的`dataset`(例如[`hf-internal-testing`](https://huggingface.co/hf-internal-testing)或[huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images))存放这类文件。若为外部贡献,可将图片添加到PR中并请Hugging Face成员将其迁移至该数据集。
364
+
365
+ ## 提交PR流程
366
+
367
+ 编写代码前,强烈建议先搜索现有PR或issue,确认没有重复工作。如有疑问,建议先创建issue获取反馈。
368
+
369
+ 贡献至🧨 Diffusers需要基本的`git`技能。虽然`git`学习曲线较高,但其拥有最完善的手册。在终端输入`git --help`即可查阅,或参考书籍[Pro Git](https://git-scm.com/book/en/v2)。
370
+
371
+ 请按以下步骤操作([支持的Python版本](https://github.com/huggingface/diffusers/blob/83bc6c94eaeb6f7704a2a428931cf2d9ad973ae9/setup.py#L270)):
372
+
373
+ 1. 在[仓库页面](https://github.com/huggingface/diffusers)点击"Fork"按钮创建代码副本至您的GitHub账户
374
+
375
+ 2. 克隆fork到本地,并添加主仓库为远程源:
376
+ ```bash
377
+ $ git clone git@github.com:<您的GitHub账号>/diffusers.git
378
+ $ cd diffusers
379
+ $ git remote add upstream https://github.com/huggingface/diffusers.git
380
+ ```
381
+
382
+ 3. 创建新分支进行开发:
383
+ ```bash
384
+ $ git checkout -b 您的开发分支名称
385
+ ```
386
+ **禁止**直接在`main`分支上修改
387
+
388
+ 4. 在虚拟环境中运行以下命令配置开发环境:
389
+ ```bash
390
+ $ pip install -e ".[dev]"
391
+ ```
392
+ 若已克隆仓库,可能需要先执行`git pull`获取最新代码
393
+
394
+ 5. 在您的分支上开发功能
395
+
396
+ 开发过程中应确保测试通过。可运行受影响测试:
397
+ ```bash
398
+ $ pytest tests/<待测文件>.py
399
+ ```
400
+ 执行测试前请安装测试依赖:
401
+ ```bash
402
+ $ pip install -e ".[test]"
403
+ ```
404
+ 也可运行完整测试套件(需高性能机器):
405
+ ```bash
406
+ $ make test
407
+ ```
408
+
409
+ 🧨 Diffusers使用`black`和`isort`工具保持代码风格统一。修改后请执行自动化格式校正与代码验证,以下内容无法通过以下命令一次性自动化完成:
410
+
411
+ ```bash
412
+ $ make style
413
+ ```
414
+
415
+ 🧨 Diffusers 还使用 `ruff` 和一些自定义脚本来检查代码错误。虽然质量控制流程会在 CI 中运行,但您也可以通过以下命令手动执行相同的检查:
416
+
417
+ ```bash
418
+ $ make quality
419
+ ```
420
+
421
+ 当您对修改满意后,使用 `git add` 添加更改的文件,并通过 `git commit` 在本地记录这些更改:
422
+
423
+ ```bash
424
+ $ git add modified_file.py
425
+ $ git commit -m "关于您所做更改的描述性信息。"
426
+ ```
427
+
428
+ 定期将您的代码副本与原始仓库同步是一个好习惯。这样可以快速适应上游变更:
429
+
430
+ ```bash
431
+ $ git pull upstream main
432
+ ```
433
+
434
+ 使用以下命令将更改推送到您的账户:
435
+
436
+ ```bash
437
+ $ git push -u origin 此处替换为您的描述性分支名称
438
+ ```
439
+
440
+ 6. 确认无误后,请访问您 GitHub 账户中的派生仓库页面。点击「Pull request」将您的更改提交给项目维护者审核。
441
+
442
+ 7. 如果维护者要求修改,这很正常——核心贡献者也会遇到这种情况!为了让所有人能在 Pull request 中看到变更,请在本地分支继续工作并将修改推送到您的派生仓库,这些变更会自动出现在 Pull request 中。
443
+
444
+ ### 测试
445
+
446
+ 我们提供了全面的测试套件来验证库行为和多个示例。库测试位于 [tests 文件夹](https://github.com/huggingface/diffusers/tree/main/tests)。
447
+
448
+ 我们推荐使用 `pytest` 和 `pytest-xdist`,因为它们速度更快。在仓库根目录下运行以下命令执行库测试:
449
+
450
+ ```bash
451
+ $ python -m pytest -n auto --dist=loadfile -s -v ./tests/
452
+ ```
453
+
454
+ 实际上,这就是 `make test` 的实现方式!
455
+
456
+ 您可以指定更小的测试范围来仅验证您正在开发的功能。
457
+
458
+ 默认情况下会跳过耗时测试。设置 `RUN_SLOW` 环境变量为 `yes` 可运行这些测试。注意:这将下载数十 GB 的模型文件——请确保您有足够的磁盘空间、良好的网络连接或充足的耐心!
459
+
460
+ ```bash
461
+ $ RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/
462
+ ```
463
+
464
+ 我们也完全支持 `unittest`,运行方式如下:
465
+
466
+ ```bash
467
+ $ python -m unittest discover -s tests -t . -v
468
+ $ python -m unittest discover -s examples -t examples -v
469
+ ```
470
+
471
+ ### 将派生仓库的 main 分支与上游(HuggingFace)main 分支同步
472
+
473
+ 为避免向上游仓库发送引用通知(这会给相关 PR 添加注释并向开发者发送不必要的通知),在同步派生仓库的 main 分支时,请遵循以下步骤:
474
+ 1. 尽可能避免通过派生仓库的分支和 PR 来同步上游,而是直接合并到派生仓库的 main 分支
475
+ 2. 如果必须使用 PR,请在检出分支后执行以下操作:
476
+ ```bash
477
+ $ git checkout -b 您的同步分支名称
478
+ $ git pull --squash --no-commit upstream main
479
+ $ git commit -m '提交信息(不要包含 GitHub 引用)'
480
+ $ git push --set-upstream origin 您的分支名称
481
+ ```
482
+
483
+ ### 风格指南
484
+
485
+ 对于文档字符串,🧨 Diffusers 遵循 [Google 风格指南](https://google.github.io/styleguide/pyguide.html)。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/conceptual/ethical_guidelines.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权归2025年HuggingFace团队所有。保留所有权利。
2
+
3
+ 根据Apache许可证2.0版("许可证")授权;除非符合许可证要求,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,本软件按"原样"分发,不附带任何明示或暗示的担保或条件。详见许可证中规定的特定语言权限和限制。
8
+ -->
9
+
10
+ # 🧨 Diffusers伦理准则
11
+
12
+ ## 前言
13
+
14
+ [Diffusers](https://huggingface.co/docs/diffusers/index)不仅提供预训练的diffusion模型,还是一个模块化工具箱,支持推理和训练功能。
15
+
16
+ 鉴于该技术在实际场景中的应用及其可能对社会产生的负面影响,我们认为有必要制定项目伦理准则,以指导Diffusers库的开发、用户贡献和使用规范。
17
+
18
+ 该技术涉及的风险仍在持续评估中,主要包括但不限于:艺术家版权问题、深度伪造滥用、不当情境下的色情内容生成、非自愿的人物模仿、以及加剧边缘群体压迫的有害社会偏见。我们将持续追踪风险,并根据社区反馈动态调整本准则。
19
+
20
+ ## 适用范围
21
+
22
+ Diffusers社区将在项目开发中贯彻以下伦理准则,并协调社区贡献的整合方式,特别是在涉及伦理敏感议题的技术决策时。
23
+
24
+ ## 伦理准则
25
+
26
+ 以下准则具有普遍适用性,但我们主要在处理涉及伦理敏感问题的技术决策时实施。同时,我们承诺将根据技术发展带来的新兴风险持续调整这些原则:
27
+
28
+ - **透明度**:我们承诺以透明方式管理PR(拉取请求),向用户解释决策依据,并公开技术选择过程。
29
+
30
+ - **一致性**:我们承诺为用户提供统一标准的项目管理,保持技术稳定性和连贯性。
31
+
32
+ - **简洁性**:为了让Diffusers库更易使用和开发,我们承诺保持项目目标精简且逻辑自洽。
33
+
34
+ - **可及性**:本项目致力于降低贡献门槛,即使非技术人员也能参与运营,从而使研究资源更广泛地服务于社区。
35
+
36
+ - **可复现性**:对于通过Diffusers库发布的上游代码、模型和数据集,我们将明确说明其可复现性。
37
+
38
+ - **责任性**:作为社区和团队,我们共同承担用户责任,通过风险预判和缓解措施来应对技术潜在危害。
39
+
40
+ ## 实施案例:安全功能与机制
41
+
42
+ 团队持续开发技术和非技术工具,以应对diffusion技术相关的伦理与社会风险。社区反馈对于功能实施和风险意识提升具有不可替代的价值:
43
+
44
+ - [**社区讨论区**](https://huggingface.co/docs/hub/repositories-pull-requests-discussions):促进社区成员就项目开展协作讨论。
45
+
46
+ - **偏见探索与评估**:Hugging Face团队提供[交互空间](https://huggingface.co/spaces/society-ethics/DiffusionBiasExplorer)展示Stable Diffusion中的偏见。我们支持并鼓励此类偏见探索与评估工作。
47
+
48
+ - **部署安全强化**:
49
+
50
+ - [**Safe Stable Diffusion**](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_safe):解决Stable Diffusion等基于未过滤网络爬取数据训练的模型容易产生不当内容的问题。相关论文:[Safe Latent Diffusion:缓解diffusion模型中的不当退化](https://huggingface.co/papers/2211.05105)。
51
+
52
+ - [**安全检测器**](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py):通过比对图像生成后嵌入空间中硬编码有害概念集的类别概率进行检测。有害概念列表经特殊处理以防逆向工程。
53
+
54
+ - **分阶段模型发布**:对于高度敏感的仓库,采用分级访问控制。这种阶段性发布机制让作者能更好地管控使用场景。
55
+
56
+ - **许可证制度**:采用新型[OpenRAILs](https://huggingface.co/blog/open_rail)许可协议,在保障开放访问的同时设置使用限制以确保更负责任的应用。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/conceptual/evaluation.md ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ 根据 Apache License 2.0 版本("许可证")授权,除非符合许可证要求,否则不得使用本文件。
4
+ 您可以在以下网址获取许可证副本:
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ 除非适用法律要求或书面同意,本软件按"原样"分发,不附带任何明示或暗示的担保或条件。详见许可证中规定的特定语言权限和限制。
9
+ -->
10
+
11
+ # Diffusion模型评估指南
12
+
13
+ <a target="_blank" href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/evaluation.ipynb">
14
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="在 Colab 中打开"/>
15
+ </a>
16
+
17
+ > [!TIP]
18
+ > 鉴于当前已出现针对图像生成Diffusion模型的成熟评估框架(如[HEIM](https://crfm.stanford.edu/helm/heim/latest/)、[T2I-Compbench](https://huggingface.co/papers/2307.06350)、[GenEval](https://huggingface.co/papers/2310.11513)),本文档部分内容已过时。
19
+
20
+ 像 [Stable Diffusion](https://huggingface.co/docs/diffusers/stable_diffusion) 这类生成模型的评估本质上是主观的。但作为开发者和研究者,我们经常需要在众多可能性中做出审慎选择。那么当面对不同生成模型(如 GANs、Diffusion 等)时,该如何决策?
21
+
22
+ 定性评估容易产生偏差,可能导致错误结论;而定量指标又未必能准确反映图像质量。因此,通常需要结合定性与定量评估来获得更可靠的模型选择依据。
23
+
24
+ 本文档将系统介绍扩散模型的定性与定量评估方法(非穷尽列举)。对于定量方法,我们将重点演示如何结合 `diffusers` 库实现这些评估。
25
+
26
+ 文档所示方法同样适用于评估不同[噪声调度器](https://huggingface.co/docs/diffusers/main/en/api/schedulers/overview)在固定生成模型下的表现差异。
27
+
28
+ ## 评估场景
29
+
30
+ 我们涵盖以下Diffusion模型管线的评估:
31
+
32
+ - 文本引导图像生成(如 [`StableDiffusionPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/text2img))
33
+ - 基于文本和输入图像的引导生成(如 [`StableDiffusionImg2ImgPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/img2img) 和 [`StableDiffusionInstructPix2PixPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix))
34
+ - 类别条件图像生成模型(如 [`DiTPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipe))
35
+
36
+ ## 定性评估
37
+
38
+ 定性评估通常涉及对生成图像的人工评判。评估维度包括构图质量、图文对齐度和空间关系等方面。标准化的提示词能为这些主观指标提供统一基准。DrawBench和PartiPrompts是常用的定性评估提示词数据集,分别由[Imagen](https://imagen.research.google/)和[Parti](https://parti.research.google/)团队提出。
39
+
40
+ 根据[Parti官方网站](https://parti.research.google/)说明:
41
+
42
+ > PartiPrompts (P2)是我们发布的包含1600多个英文提示词的丰富集合,可用于测量模型在不同类别和挑战维度上的能力。
43
+
44
+ ![parti-prompts](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/parti-prompts.png)
45
+
46
+ PartiPrompts包含以下字段:
47
+ - Prompt(提示词)
48
+ - Category(类别,如"抽象"、"世界知识"等)
49
+ - Challenge(难度等级,如"基础"、"复杂"、"文字与符号"等)
50
+
51
+ 这些基准测试支持对不同图像生成模型进行并排人工对比评估。为此,🧨 Diffusers团队构建了**Open Parti Prompts**——一个基于Parti Prompts的社区驱动型定性评估基准,用于比较顶尖开源diffusion模型:
52
+ - [Open Parti Prompts游戏](https://huggingface.co/spaces/OpenGenAI/open-parti-prompts):展示10个parti提示词对应的4张生成图像,用户选择最符合提示的图片
53
+ - [Open Parti Prompts排行榜](https://huggingface.co/spaces/OpenGenAI/parti-prompts-leaderboard):对比当前最优开源diffusion模型的性能榜单
54
+
55
+ 为进行手动图像对比,我们演示如何使用`diffusers`处理部分PartiPrompts提示词。
56
+
57
+ 以下是从不同挑战维度(基础、复杂、语言结构、想象力、文字与符号)采样的提示词示例(使用[PartiPrompts作为数据集](https://huggingface.co/datasets/nateraw/parti-prompts)):
58
+
59
+ ```python
60
+ from datasets import load_dataset
61
+
62
+ # prompts = load_dataset("nateraw/parti-prompts", split="train")
63
+ # prompts = prompts.shuffle()
64
+ # sample_prompts = [prompts[i]["Prompt"] for i in range(5)]
65
+
66
+ # Fixing these sample prompts in the interest of reproducibility.
67
+ sample_prompts = [
68
+ "a corgi",
69
+ "a hot air balloon with a yin-yang symbol, with the moon visible in the daytime sky",
70
+ "a car with no windows",
71
+ "a cube made of porcupine",
72
+ 'The saying "BE EXCELLENT TO EACH OTHER" written on a red brick wall with a graffiti image of a green alien wearing a tuxedo. A yellow fire hydrant is on a sidewalk in the foreground.',
73
+ ]
74
+ ```
75
+
76
+ 现在我们可以使用Stable Diffusion([v1-4 checkpoint](https://huggingface.co/CompVis/stable-diffusion-v1-4))生成这些提示词对应的图像:
77
+
78
+ ```python
79
+ import torch
80
+
81
+ seed = 0
82
+ generator = torch.manual_seed(seed)
83
+
84
+ images = sd_pipeline(sample_prompts, num_images_per_prompt=1, generator=generator).images
85
+ ```
86
+
87
+ ![parti-prompts-14](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/parti-prompts-14.png)
88
+
89
+ 我们也可以通过设置`num_images_per_prompt`参数来比较同一提示词生成的不同图像。使用不同检查点([v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5))运行相同流程后,结果如下:
90
+
91
+ ![parti-prompts-15](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/parti-prompts-15.png)
92
+
93
+ 当使用多个待评估模型为所有提示词生成若干图像后,这些结果将提交给人类评估员进行打分。有关DrawBench和PartiPrompts基准测试的更多细节,请参阅各自的论文。
94
+
95
+ > [!TIP]
96
+ > 在模型训练过程中查看推理样本有助于评估训练进度。我们的[训练脚本](https://github.com/huggingface/diffusers/tree/main/examples/)支持此功能,并额外提供TensorBoard和Weights & Biases日志记录功能。
97
+
98
+ ## 定量评估
99
+
100
+ 本节将指导您如何评估三种不同的扩散流程,使用以下指标:
101
+ - CLIP分数
102
+ - CLIP方向相似度
103
+ - FID(弗雷歇起始距离)
104
+
105
+ ### 文本引导图像生成
106
+
107
+ [CLIP分数](https://huggingface.co/papers/2104.08718)用于衡量图像-标题对的匹配程度。CLIP分数越高表明匹配度越高🔼。该分数是对"匹配度"这一定性概念的量化测量,也可以理解为图像与标题之间的语义相似度。研究发现CLIP分数与人类判断具有高度相关性。
108
+
109
+ 首先加载[`StableDiffusionPipeline`]:
110
+
111
+ ```python
112
+ from diffusers import StableDiffusionPipeline
113
+ import torch
114
+
115
+ model_ckpt = "CompVis/stable-diffusion-v1-4"
116
+ sd_pipeline = StableDiffusionPipeline.from_pretrained(model_ckpt, torch_dtype=torch.float16).to("cuda")
117
+ ```
118
+
119
+ 使用多个提示词生成图像:
120
+
121
+ ```python
122
+ prompts = [
123
+ "a photo of an astronaut riding a horse on mars",
124
+ "A high tech solarpunk utopia in the Amazon rainforest",
125
+ "A pikachu fine dining with a view to the Eiffel Tower",
126
+ "A mecha robot in a favela in expressionist style",
127
+ "an insect robot preparing a delicious meal",
128
+ "A small cabin on top of a snowy mountain in the style of Disney, artstation",
129
+ ]
130
+
131
+ images = sd_pipeline(prompts, num_images_per_prompt=1, output_type="np").images
132
+
133
+ print(images.shape)
134
+ # (6, 512, 512, 3)
135
+ ```
136
+
137
+ 然后计算CLIP分数:
138
+
139
+ ```python
140
+ from torchmetrics.functional.multimodal import clip_score
141
+ from functools import partial
142
+
143
+ clip_score_fn = partial(clip_score, model_name_or_path="openai/clip-vit-base-patch16")
144
+
145
+ def calculate_clip_score(images, prompts):
146
+ images_int = (images * 255).astype("uint8")
147
+ clip_score = clip_score_fn(torch.from_numpy(images_int).permute(0, 3, 1, 2), prompts).detach()
148
+ return round(float(clip_score), 4)
149
+
150
+ sd_clip_score = calculate_clip_score(images, prompts)
151
+ print(f"CLIP分数: {sd_clip_score}")
152
+ # CLIP分数: 35.7038
153
+ ```
154
+
155
+ 上述示例中,我们为每个提示生成一张图像。如果为每个提示生成多张图像,则需要计算每个提示生成图像的平均分数。
156
+
157
+ 当需要比较两个兼容[`StableDiffusionPipeline`]的检查点时,应在调用管道时传入生成器。首先使用[v1-4 Stable Diffusion检查点](https://huggingface.co/CompVis/stable-diffusion-v1-4)以固定种子生成图像:
158
+
159
+ ```python
160
+ seed = 0
161
+ generator = torch.manual_seed(seed)
162
+
163
+ images = sd_pipeline(prompts, num_images_per_prompt=1, generator=generator, output_type="np").images
164
+ ```
165
+
166
+ 然后加载[v1-5检查点](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)生成图像:
167
+
168
+ ```python
169
+ model_ckpt_1_5 = "stable-diffusion-v1-5/stable-diffusion-v1-5"
170
+ sd_pipeline_1_5 = StableDiffusionPipeline.from_pretrained(model_ckpt_1_5, torch_dtype=torch.float16).to("cuda")
171
+
172
+ images_1_5 = sd_pipeline_1_5(prompts, num_images_per_prompt=1, generator=generator, output_type="np").images
173
+ ```
174
+
175
+ 最后比较两者的CLIP分数:
176
+
177
+ ```python
178
+ sd_clip_score_1_4 = calculate_clip_score(images, prompts)
179
+ print(f"v-1-4版本的CLIP分数: {sd_clip_score_1_4}")
180
+ # v-1-4版本的CLIP分数: 34.9102
181
+
182
+ sd_clip_score_1_5 = calculate_clip_score(images_1_5, prompts)
183
+ print(f"v-1-5版本的CLIP分数: {sd_clip_score_1_5}")
184
+ # v-1-5版本的CLIP分数: 36.2137
185
+ ```
186
+
187
+ 结果表明[v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)检查点性能优于前代。但需注意,我们用于计算CLIP分数的提示词数量较少。实际评估时应使用更多样化且数量更大的提示词集。
188
+
189
+ > [!WARNING]
190
+ > 该分数存在固有局限性:训练数据中的标题是从网络爬取,并提取自图片关联的`alt`等标签。这些描述未必符合人类描述图像的方式���因此我们需要人工"设计"部分提示词。
191
+
192
+ ### 图像条件式文本生成图像
193
+
194
+ 这种情况下,生成管道同时接受输入图像和文本提示作为条件。以[`StableDiffusionInstructPix2PixPipeline`]为例,该管道接收编辑指令作为输入提示,并接受待编辑的输入图像。
195
+
196
+ 示例图示:
197
+
198
+ ![编辑指令](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/edit-instruction.png)
199
+
200
+ 评估此类模型的策略之一是测量两幅图像间变化的连贯性(通过[CLIP](https://huggingface.co/docs/transformers/model_doc/clip)定义)中两个图像之间的变化与两个图像描述之间的变化的一致性(如论文[《CLIP-Guided Domain Adaptation of Image Generators》](https://huggingface.co/papers/2108.00946)所示)。这被称为“**CLIP方向相似度**”。
201
+
202
+ - **描述1**对应输入图像(图像1),即待编辑的图像。
203
+ - **描述2**对应编辑后的图像(图像2),应反映编辑指令。
204
+
205
+ 以下是示意图:
206
+
207
+ ![edit-consistency](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/edit-consistency.png)
208
+
209
+ 我们准备了一个小型数据集来实现该指标。首先加载数据集:
210
+
211
+ ```python
212
+ from datasets import load_dataset
213
+
214
+ dataset = load_dataset("sayakpaul/instructpix2pix-demo", split="train")
215
+ dataset.features
216
+ ```
217
+
218
+ ```bash
219
+ {'input': Value(dtype='string', id=None),
220
+ 'edit': Value(dtype='string', id=None),
221
+ 'output': Value(dtype='string', id=None),
222
+ 'image': Image(decode=True, id=None)}
223
+ ```
224
+
225
+ 数据字段说明:
226
+
227
+ - `input`:与`image`对应的原始描述。
228
+ - `edit`:编辑指令。
229
+ - `output`:反映`edit`指令的修改后描述。
230
+
231
+ 查看一个样本:
232
+
233
+ ```python
234
+ idx = 0
235
+ print(f"Original caption: {dataset[idx]['input']}")
236
+ print(f"Edit instruction: {dataset[idx]['edit']}")
237
+ print(f"Modified caption: {dataset[idx]['output']}")
238
+ ```
239
+
240
+ ```bash
241
+ Original caption: 2. FAROE ISLANDS: An archipelago of 18 mountainous isles in the North Atlantic Ocean between Norway and Iceland, the Faroe Islands has 'everything you could hope for', according to Big 7 Travel. It boasts 'crystal clear waterfalls, rocky cliffs that seem to jut out of nowhere and velvety green hills'
242
+ Edit instruction: make the isles all white marble
243
+ Modified caption: 2. WHITE MARBLE ISLANDS: An archipelago of 18 mountainous white marble isles in the North Atlantic Ocean between Norway and Iceland, the White Marble Islands has 'everything you could hope for', according to Big 7 Travel. It boasts 'crystal clear waterfalls, rocky cliffs that seem to jut out of nowhere and velvety green hills'
244
+ ```
245
+
246
+ 对应的图像:
247
+
248
+ ```python
249
+ dataset[idx]["image"]
250
+ ```
251
+
252
+ ![edit-dataset](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/edit-dataset.png)
253
+
254
+ 我们将根据编辑指令修改数据集中的图像,并计算方向相似度。
255
+
256
+ 首先加载[`StableDiffusionInstructPix2PixPipeline`]:
257
+
258
+ ```python
259
+ from diffusers import StableDiffusionInstructPix2PixPipeline
260
+
261
+ instruct_pix2pix_pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(
262
+ "timbrooks/instruct-pix2pix", torch_dtype=torch.float16
263
+ ).to("cuda")
264
+ ```
265
+
266
+ 执行编辑操作:
267
+
268
+ ```python
269
+ import numpy as np
270
+
271
+
272
+ def edit_image(input_image, instruction):
273
+ image = instruct_pix2pix_pipeline(
274
+ instruction,
275
+ image=input_image,
276
+ output_type="np",
277
+ generator=generator,
278
+ ).images[0]
279
+ return image
280
+
281
+ input_images = []
282
+ original_captions = []
283
+ modified_captions = []
284
+ edited_images = []
285
+
286
+ for idx in range(len(dataset)):
287
+ input_image = dataset[idx]["image"]
288
+ edit_instruction = dataset[idx]["edit"]
289
+ edited_image = edit_image(input_image, edit_instruction)
290
+
291
+ input_images.append(np.array(input_image))
292
+ original_captions.append(dataset[idx]["input"])
293
+ modified_captions.append(dataset[idx]["output"])
294
+ edited_images.append(edited_image)
295
+ ```
296
+
297
+ 为测量方向相似度,我们首先加载CLIP的图像和文本编码器:
298
+
299
+ ```python
300
+ from transformers import (
301
+ CLIPTokenizer,
302
+ CLIPTextModelWithProjection,
303
+ CLIPVisionModelWithProjection,
304
+ CLIPImageProcessor,
305
+ )
306
+
307
+ clip_id = "openai/clip-vit-large-patch14"
308
+ tokenizer = CLIPTokenizer.from_pretrained(clip_id)
309
+ text_encoder = CLIPTextModelWithProjection.from_pretrained(clip_id).to("cuda")
310
+ image_processor = CLIPImageProcessor.from_pretrained(clip_id)
311
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(clip_id).to("cuda")
312
+ ```
313
+
314
+ 注意我们使用的是特定CLIP检查点——`openai/clip-vit-large-patch14`,因为Stable Diffusion预训练正是基于此CLIP变体。详见[文档](https://huggingface.co/docs/transformers/model_doc/clip)。
315
+
316
+ 接着准备计算方向相似度的PyTorch `nn.Module`:
317
+
318
+ ```python
319
+ import torch.nn as nn
320
+ import torch.nn.functional as F
321
+
322
+
323
+ class DirectionalSimilarity(nn.Module):
324
+ def __init__(self, tokenizer, text_encoder, image_processor, image_encoder):
325
+ super().__init__()
326
+ self.tokenizer = tokenizer
327
+ self.text_encoder = text_encoder
328
+ self.image_processor = image_processor
329
+ self.image_encoder = image_encoder
330
+
331
+ def preprocess_image(self, image):
332
+ image = self.image_processor(image, return_tensors="pt")["pixel_values"]
333
+ return {"pixel_values": image.to("cuda")}
334
+
335
+ def tokenize_text(self, text):
336
+ inputs = self.tokenizer(
337
+ text,
338
+ max_length=self.tokenizer.model_max_length,
339
+ padding="max_length",
340
+ truncation=True,
341
+ return_tensors="pt",
342
+ )
343
+ return {"input_ids": inputs.input_ids.to("cuda")}
344
+
345
+ def encode_image(self, image):
346
+ preprocessed_image = self.preprocess_image(image)
347
+ image_features = self.image_encoder(**preprocessed_image).image_embeds
348
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
349
+ return image_features
350
+
351
+ def encode_text(self, text):
352
+ tokenized_text = self.tokenize_text(text)
353
+ text_features = self.text_encoder(**tokenized_text).text_embeds
354
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
355
+ return text_features
356
+
357
+ def compute_directional_similarity(self, img_feat_one, img_feat_two, text_feat_one, text_feat_two):
358
+ sim_direction = F.cosine_similarity(img_feat_two - img_feat_one, text_feat_two - text_feat_one)
359
+ return sim_direction
360
+
361
+ def forward(self, image_one, image_two, caption_one, caption_two):
362
+ img_feat_one = self.encode_image(image_one)
363
+ img_feat_two = self.encode_image(image_two)
364
+ text_feat_one = self.encode_text(caption_one)
365
+ text_feat_two = self.encode_text(caption_two)
366
+ directional_similarity = self.compute_directional_similarity(
367
+ img_feat_one, img_feat_two, text_feat_one, text_feat_two
368
+ )
369
+ return directional_similarity
370
+ ```
371
+
372
+ 现在让我们使用`DirectionalSimilarity`模块:
373
+
374
+ ```python
375
+ dir_similarity = DirectionalSimilarity(tokenizer, text_encoder, image_processor, image_encoder)
376
+ scores = []
377
+
378
+ for i in range(len(input_images)):
379
+ original_image = input_images[i]
380
+ original_caption = original_captions[i]
381
+ edited_image = edited_images[i]
382
+ modified_caption = modified_captions[i]
383
+
384
+ similarity_score = dir_similarity(original_image, edited_image, original_caption, modified_caption)
385
+ scores.append(float(similarity_score.detach().cpu()))
386
+
387
+ print(f"CLIP方向相似度: {np.mean(scores)}")
388
+ # CLIP方向相似度: 0.0797976553440094
389
+ ```
390
+
391
+ 与CLIP分数类似,CLIP方向相似度数值越高越好。
392
+
393
+ 需要注意的是,`StableDiffusionInstructPix2PixPipeline`提供了两个控制参数`image_guidance_scale`和`guidance_scale`来调节最终编辑图像的质量。建议您尝试调整这两个参数,观察它们对方向相似度的影响。
394
+
395
+ 我们可以扩展这个度量标准来评估原始图像与编辑版本的相似度,只需计算`F.cosine_similarity(img_feat_two, img_feat_one)`。对于这类编辑任务,我们仍希望尽可能保留图像的主要语义特征(即保持较高的相似度分数)。
396
+
397
+ 该度量方法同样适用于类似流程,例如[`StableDiffusionPix2PixZeroPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix_zero#diffusers.StableDiffusionPix2PixZeroPipeline)。
398
+
399
+ > [!TIP]
400
+ > CLIP分数和CLIP方向相似度都依赖CLIP模型,可能导致评估结果存在偏差。
401
+
402
+ ***扩展IS、FID(后文讨论)或KID等指标存在困难***,当被评估模型是在大型图文数据集(如[LAION-5B数据集](https://laion.ai/blog/laion-5b/))上预训练时。因为这些指标的底层都使用了在ImageNet-1k数据集上预训练的InceptionNet来提取图像特征。Stable Diffusion的预训练数据集与InceptionNet的预训练数据集可能重叠有限,因此不适合作为特征提取器。
403
+
404
+ ***上述指标更适合评估类别条件模型***,例如[DiT](https://huggingface.co/docs/diffusers/main/en/api/pipelines/dit)。该模型是在ImageNet-1k类别条件下预训练的。
405
+ 这是9篇文档中的第8部分。
406
+
407
+ ### 基于类别的图像生成
408
+
409
+ 基于类别的生成模型通常是在带有类别标签的数据集(如[ImageNet-1k](https://huggingface.co/datasets/imagenet-1k))上进行预训练的。评估这些模型的常用指标包括Fréchet Inception Distance(FID)、Kernel Inception Distance(KID)和Inception Score(IS)。本文档重点介绍FID([Heusel等人](https://huggingface.co/papers/1706.08500)),并展示如何使用[`DiTPipeline`](https://huggingface.co/docs/diffusers/api/pipelines/dit)计算该指标,该管道底层使用了[DiT模型](https://huggingface.co/papers/2212.09748)。
410
+
411
+ FID旨在衡量两组图像数据集的相似程度。根据[此资源](https://mmgeneration.readthedocs.io/en/latest/quick_run.html#fid):
412
+
413
+ > Fréchet Inception Distance是衡量两组图像数据集相似度的指标。研究表明其与人类对视觉质量的主观判断高度相关,因此最常用于评估生成对抗网络(GAN)生成样本的质量。FID通过计算Inception网络特征表示所拟合的两个高斯分布之间的Fréchet距离来实现。
414
+
415
+ 这两个数据集本质上是真实图像数据集和生成图像数据集(本例中为人工生成的图像)。FID通常基于两个大型数据集计算,但本文档将使用两个小型数据集进行演示。
416
+
417
+ 首先下载ImageNet-1k训练集中的部分图像:
418
+
419
+ ```python
420
+ from zipfile import ZipFile
421
+ import requests
422
+
423
+
424
+ def download(url, local_filepath):
425
+ r = requests.get(url)
426
+ with open(local_filepath, "wb") as f:
427
+ f.write(r.content)
428
+ return local_filepath
429
+
430
+ dummy_dataset_url = "https://hf.co/datasets/sayakpaul/sample-datasets/resolve/main/sample-imagenet-images.zip"
431
+ local_filepath = download(dummy_dataset_url, dummy_dataset_url.split("/")[-1])
432
+
433
+ with ZipFile(local_filepath, "r") as zipper:
434
+ zipper.extractall(".")
435
+ ```
436
+
437
+ ```python
438
+ from PIL import Image
439
+ import os
440
+ import numpy as np
441
+
442
+ dataset_path = "sample-imagenet-images"
443
+ image_paths = sorted([os.path.join(dataset_path, x) for x in os.listdir(dataset_path)])
444
+
445
+ real_images = [np.array(Image.open(path).convert("RGB")) for path in image_paths]
446
+ ```
447
+
448
+ 这些是来自以下ImageNet-1k类别的10张图像:"cassette_player"、"chain_saw"(2张)、"church"、"gas_pump"(3张)、"parachute"(2张)和"tench"。
449
+
450
+ <p align="center">
451
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/real-images.png" alt="真实图像"><br>
452
+ <em>真实图像</em>
453
+ </p>
454
+
455
+ 加载图像后,我们对其进行轻量级预处理以便用于FID计算:
456
+
457
+ ```python
458
+ from torchvision.transforms import functional as F
459
+ import torch
460
+
461
+
462
+ def preprocess_image(image):
463
+ image = torch.tensor(image).unsqueeze(0)
464
+ image = image.permute(0, 3, 1, 2) / 255.0
465
+ return F.center_crop(image, (256, 256))
466
+
467
+ real_images = torch.stack([dit_pipeline.preprocess_image(image) for image in real_images])
468
+ print(real_images.shape)
469
+ # torch.Size([10, 3, 256, 256])
470
+ ```
471
+
472
+ 我们现在加载[`DiTPipeline`](https://huggingface.co/docs/diffusers/api/pipelines/dit)来生成基于上述类别的条件图像。
473
+
474
+ ```python
475
+ from diffusers import DiTPipeline, DPMSolverMultistepScheduler
476
+
477
+ dit_pipeline = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256", torch_dtype=torch.float16)
478
+ dit_pipeline.scheduler = DPMSolverMultistepScheduler.from_config(dit_pipeline.scheduler.config)
479
+ dit_pipeline = dit_pipeline.to("cuda")
480
+
481
+ seed = 0
482
+ generator = torch.manual_seed(seed)
483
+
484
+
485
+ words = [
486
+ "cassette player",
487
+ "chainsaw",
488
+ "chainsaw",
489
+ "church",
490
+ "gas pump",
491
+ "gas pump",
492
+ "gas pump",
493
+ "parachute",
494
+ "parachute",
495
+ "tench",
496
+ ]
497
+
498
+ class_ids = dit_pipeline.get_label_ids(words)
499
+ output = dit_pipeline(class_labels=class_ids, generator=generator, output_type="np")
500
+
501
+ fake_images = output.images
502
+ fake_images = torch.tensor(fake_images)
503
+ fake_images = fake_images.permute(0, 3, 1, 2)
504
+ print(fake_images.shape)
505
+ # torch.Size([10, 3, 256, 256])
506
+ ```
507
+
508
+ 现在,我们可以使用[`torchmetrics`](https://torchmetrics.readthedocs.io/)计算FID分数。
509
+
510
+ ```python
511
+ from torchmetrics.image.fid import FrechetInceptionDistance
512
+
513
+ fid = FrechetInceptionDistance(normalize=True)
514
+ fid.update(real_images, real=True)
515
+ fid.update(fake_images, real=False)
516
+
517
+ print(f"FID分数: {float(fid.compute())}")
518
+ # FID分数: 177.7147216796875
519
+ ```
520
+
521
+ FID分数越低越好。以下因素会影响FID结果:
522
+
523
+ - 图像数量(包括真实图像和生成图像)
524
+ - 扩散过程中引入的随机性
525
+ - 扩散过程的推理步数
526
+ - 扩散过程中使用的调度器
527
+
528
+ 对于最后两点,最佳实践是使用不同的随机种子和推理步数进行多次评估,然后报告平均结果。
529
+
530
+ > [!WARNING]
531
+ > FID结果往往具有脆弱性,因为它依赖于许多因素:
532
+ >
533
+ > * 计算过程中使用的特定Inception模型
534
+ > * 计算实现的准确性
535
+ > * 图像格式(PNG和JPG的起点不同)
536
+ >
537
+ > 需要注意的是,FID通常在比较相似实验时最有用,但除非作者仔细公开FID测量代码,否则很难复现论文结果。
538
+ >
539
+ > 这些注意事项同样适用于其他相关指标,如KID和IS。
540
+
541
+ 最后,让我们可视化检查这些`fake_images`。
542
+
543
+ <p align="center">
544
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/fake-images.png" alt="生成图像"><br>
545
+ <em>生成图像示例</em>
546
+ </p>
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/conceptual/philosophy.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权 2025 HuggingFace 团队。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版本("许可证")授权;
4
+ 除非符合许可证要求,否则不得使用本文件。
5
+ 您可以在以下网址获取许可证副本:
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ 除非适用法律要求或书面同意,本软件按"原样"分发,
10
+ 无任何明示或暗示的担保或条件。详见许可证中
11
+ 的特定语言规定和限制。
12
+ -->
13
+
14
+ # 设计哲学
15
+
16
+ 🧨 Diffusers 提供**最先进**的预训练扩散模型支持多模态任务。
17
+ 其目标是成为推理和训练通用的**模块化工具箱**。
18
+
19
+ 我们致力于构建一个经得起时间考验的库,因此对API设计极为重视。
20
+
21
+ 简而言之,Diffusers 被设计为 PyTorch 的自然延伸。因此,我们的多数设计决策都基于 [PyTorch 设计原则](https://pytorch.org/docs/stable/community/design.html#pytorch-design-philosophy)。以下是核心原则:
22
+
23
+ ## 可用性优先于性能
24
+
25
+ - 尽管 Diffusers 包含众多性能优化特性(参见[内存与速度优化](https://huggingface.co/docs/diffusers/optimization/fp16)),模型默认总是以最高精度和最低优化级别加载。因此除非用户指定,扩散流程(pipeline)默认在CPU上以float32精度初始化。这确保了跨平台和加速器的可用性,意味着运行本库无需复杂安装。
26
+ - Diffusers 追求**轻量化**,仅有少量必需依赖,但提供诸多可选依赖以提升性能(如`accelerate`、`safetensors`、`onnx`等)。我们竭力保持库的轻量级特性,使其能轻松作为其他包的依赖项。
27
+ - Diffusers 偏好简单、自解释的代码而非浓缩的"魔法"代码。这意味着lambda函数等简写语法和高级PyTorch操作符通常不被采用。
28
+
29
+ ## 简洁优于简易
30
+
31
+ 正如PyTorch所言:**显式优于隐式**,**简洁优于复杂**。这一哲学体现在库的多个方面:
32
+ - 我们遵循PyTorch的API设计,例如使用[`DiffusionPipeline.to`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.to)让用户自主管理设备。
33
+ - 明确的错误提示优于静默纠正错误输入。Diffusers 旨在教育用户,而非单纯降低使用难度。
34
+ - 暴露复杂的模型与调度器(scheduler)交互逻辑而非内部魔法处理。调度器/采样器与扩散模型分离且相互依赖最小化,迫使用户编写展开的去噪循环。但这种分离便于调试,并赋予用户更多控制权来调整去噪过程或切换模型/调度器。
35
+ - 扩散流程中独立训练的组件(如文本编码器、UNet、变分自编码器)各有专属模型类。这要求用户处理组件间交互,且序列化格式将组件分存不同文件。但此举便于调试和定制,得益于组件分离,DreamBooth或Textual Inversion训练变得极为简单。
36
+
37
+ ## 可定制与贡献友好优于抽象
38
+
39
+ 库的大部分沿用了[Transformers库](https://github.com/huggingface/transformers)的重要设计原则:宁要重复代码,勿要仓促抽象。这一原则与[DRY原则](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)形成鲜明对比。
40
+
41
+ 简言之,正如Transformers对建模文件的做法,Diffusers对流程(pipeline)和调度器(scheduler)保持极低抽象度与高度自包含代码。函数、长代码块甚至类可能在多文件中重复,初看像是糟糕的松散设计。但该设计已被Transformers证明极其成功,对社区驱动的开源机器学习库意义重大:
42
+ - 机器学习领域发展迅猛,范式、模型架构和算法快速迭代,难以定义长效代码抽象。
43
+ - ML从业者常需快速修改现有代码进行研究,因此偏好自包含代码而非多重抽象。
44
+ - 开源库依赖社区贡献,必须构建易于参与的代码库。抽象度越高、依赖越复杂、可读性越差,贡献难度越大。过度抽象的库会吓退贡献者。若贡献不会破坏核心功能,不仅吸引新贡献者,也更便于并行审查和修改。
45
+
46
+ Hugging Face称此设计为**单文件政策**——即某个类的几乎所有代码都应写在单一自包含文件中。更多哲学探讨可参阅[此博文](https://huggingface.co/blog/transformers-design-philosophy)。
47
+
48
+ Diffusers对流程和调度器完全遵循该哲学,但对diffusion模型仅部分适用。原因在于多数扩散流程(如[DDPM](https://huggingface.co/docs/diffusers/api/pipelines/ddpm)、[Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/overview#stable-diffusion-pipelines)、[unCLIP (DALL·E 2)](https://huggingface.co/docs/diffusers/api/pipelines/unclip)和[Imagen](https://imagen.research.google/))都基于相同扩散模型——[UNet](https://huggingface.co/docs/diffusers/api/models/unet2d-cond)。
49
+
50
+ 现在您应已理解🧨 Diffusers的设计理念🤗。我们力求在全库贯彻这些原则,但仍存在少数例外或欠佳设计。如有反馈,我们❤️欢迎在[GitHub提交](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=)。
51
+
52
+ ## 设计哲学细节
53
+
54
+ 现在深入探讨设计细节。Diffusers主要包含三类:[流程(pipeline)](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines)、[模型](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models)和[调度器(scheduler)](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers)。以下是各类的具体设计决策。
55
+
56
+ ### 流程(Pipelines)
57
+
58
+ 流程设计追求易用性(因此不完全遵循[*简洁优于简易*](#简洁优于简易)),不要求功能完备,应视为使用[模型](#模型)和[调度器](#调度器schedulers)进行推理的示例。
59
+
60
+ 遵循原则:
61
+ - 采用单文件政策。所有流程位于src/diffusers/pipelines下的独立目录。一个流程文件夹对应一篇扩散论文/项目/发布。如[`src/diffusers/pipelines/stable-diffusion`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/stable_diffusion)可包含多个流程文件。若流程功能相似,可使用[# Copied from机制](https://github.com/huggingface/diffusers/blob/125d783076e5bd9785beb05367a2d2566843a271/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L251)。
62
+ - 所有流程继承[`DiffusionPipeline`]。
63
+ - 每个流程由不同模型和调度器组件构成,这些组件记录于[`model_index.json`文件](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/model_index.json),可通过同名属性访问,并可用[`DiffusionPipeline.components`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.components)在流程间共享。
64
+ - 所有流程应能通过[`DiffusionPipeline.from_pretrained`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.from_pretrained)加载。
65
+ - 流程**仅**用于推理。
66
+ - 流程代码应具备高可读性、自解释性和易修改性。
67
+ - 流程应设计为可相互构建,便于集成到高层API。
68
+ - 流程**非**功能完备的用户界面。完整UI推荐[InvokeAI](https://github.com/invoke-ai/InvokeAI)、[Diffuzers](https://github.com/abhishekkrthakur/diffuzers)或[lama-cleaner](https://github.com/Sanster/lama-cleaner)。
69
+ - 每个流程应通过唯一的`__call__`方法运行,且参数命名应跨流程统一。
70
+ - 流程应以其解决的任务命名。
71
+ - 几乎所有新diffusion流程都应在新文件夹/文件中实现。
72
+
73
+ ### 模型
74
+
75
+ 模型设计为可配置的工具箱,是[PyTorch Module类](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)的自然延伸,仅部分遵循**单文件政策**。
76
+
77
+ 遵循原则:
78
+ - 模型对应**特定架构类型**。如[`UNet2DConditionModel`]类适用于所有需要2D图像输入且受上下文调节的UNet变体。
79
+ - 所有模型位于[`src/diffusers/models`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models),每种架构应有独立文件,如[`unets/unet_2d_condition.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unets/unet_2d_condition.py)、[`transformers/transformer_2d.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_2d.py)等。
80
+ - 模型**不**采用单文件政策,应使用小型建模模块如[`attention.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py)、[`resnet.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py)、[`embeddings.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/embeddings.py)等。**注意**:这与Transformers的建模文件截然不同,表明模型未完全遵循单文件政策。
81
+ - 模型意图暴露复杂度(类似PyTorch的`Module`类),并提供明确错误提示。
82
+ - 所有模型继承`ModelMixin`和`ConfigMixin`。
83
+ - 当不涉及重大代码变更、保持向后兼容性且显著提升内存/计算效率时,可对模型进行性能优化。
84
+ - 模型默认应具备最高精度和最低性能设置。
85
+ - 若新模型检查点可归类为现有架构,应适配现有架构而非新建文件。仅当架构根本性不同时才创建新文件。
86
+ - 模型设计应便于未来扩展。可通过限制公开函数参数、配置参数和"预见"变更实现。例如:优先采用可扩展的`string`类型参数而非布尔型`is_..._type`参数。对现有架构的修改应保持最小化。
87
+ - 模型设计需在代码可读性与多检查点支持间权衡。多数情况下应适配现有类,但某些例外(如[UNet块](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unets/unet_2d_blocks.py)和[注意力处理器](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py))需新建类以保证长期可读性。
88
+
89
+ ### 调度器(Schedulers)
90
+
91
+ 调度器负责引导推理去噪过程及定义训练噪声计划。它们设计为独立的可加载配置类,严格遵循**单文件政��**。
92
+
93
+ 遵循原则:
94
+ - 所有调度器位于[`src/diffusers/schedulers`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers)。
95
+ - 调度器**禁止**从大型工具文件导入,必须保持高度自包含。
96
+ - 一个调度器Python文件对应一种算法(如论文定义的算法)。
97
+ - 若调度器功能相似,可使用`# Copied from`机制。
98
+ - 所有调度器继承`SchedulerMixin`和`ConfigMixin`。
99
+ - 调度器可通过[`ConfigMixin.from_config`](https://huggingface.co/docs/diffusers/main/en/api/configuration#diffusers.ConfigMixin.from_config)轻松切换(详见[此处](../using-diffusers/schedulers))。
100
+ - 每个调度器必须包含`set_num_inference_steps`和`step`函数。在每次去噪过程前(即调用`step(...)`前)必须调用`set_num_inference_steps(...)`。
101
+ - 每个调度器通过`timesteps`属性暴露需要"循环"的时间步,这是模型将被调用的时间步数组。
102
+ - `step(...)`函数接收模型预测输出和"当前"样本(x_t),返回"前一个"略去噪的样本(x_t-1)。
103
+ - 鉴于扩散调度器的复杂性,`step`函数不暴露全部细节,可视为"黑盒"。
104
+ - 几乎所有新调度器都应在新文件中实现。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/hybrid_inference/api_reference.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # 混合推理 API 参考
2
+
3
+ ## 远程解码
4
+
5
+ [[autodoc]] utils.remote_utils.remote_decode
6
+
7
+ ## 远程编码
8
+
9
+ [[autodoc]] utils.remote_utils.remote_encode
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/hybrid_inference/overview.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权 2025 HuggingFace 团队。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版本("许可证")授权;除非遵守许可证,否则不得使用此文件。
4
+ 您可以在以下网址获取许可证副本:
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ 除非适用法律要求或书面同意,否则根据许可证分发的软件按"原样"分发,不附带任何明示或暗示的担保或条件。请参阅许可证以了解具体的语言管理权限和限制。
9
+ -->
10
+
11
+ # 混合推理
12
+
13
+ **通过混合推理赋能本地 AI 构建者**
14
+
15
+ > [!TIP]
16
+ > 混合推理是一项[实验性功能](https://huggingface.co/blog/remote_vae)。
17
+ > 可以在此处提供反馈[此处](https://github.com/huggingface/diffusers/issues/new?template=remote-vae-pilot-feedback.yml)。
18
+
19
+ ## 为什么使用混合推理?
20
+
21
+ 混合推理提供了一种快速简单的方式来卸载本地生成需求。
22
+
23
+ - 🚀 **降低要求:** 无需昂贵硬件即可访问强大模型。
24
+ - 💎 **无妥协:** 在不牺牲性能的情况下实现最高质量。
25
+ - 💰 **成本效益高:** 它是免费的!🤑
26
+ - 🎯 **多样化用例:** 与 Diffusers � 和更广泛的社区完全兼容。
27
+ - 🔧 **开发者友好:** 简单请求,快速响应。
28
+
29
+ ---
30
+
31
+ ## 可用模型
32
+
33
+ * **VAE 解码 🖼️:** 快速将潜在表示解码为高质量图像,不影响性能或工作流速度。
34
+ * **VAE 编码 🔢:** 高效将图像编码为潜在表示,用于生成和训练。
35
+ * **文本编码器 📃(即将推出):** 快速准确地计算提示的文本嵌入,确保流畅高质量的工作流。
36
+
37
+ ---
38
+
39
+ ## 集成
40
+
41
+ * **[SD.Next](https://github.com/vladmandic/sdnext):** 一体化 UI,直接支持混合推理。
42
+ * **[ComfyUI-HFRemoteVae](https://github.com/kijai/ComfyUI-HFRemoteVae):** 用于混合推理的 ComfyUI 节点。
43
+
44
+ ## 更新日志
45
+
46
+ - 2025 年 3 月 10 日:添加了 VAE 编码
47
+ - 2025 年 3 月 2 日:初始发布,包含 VAE 解码
48
+
49
+ ## 内容
50
+
51
+ 文档分为三个部分:
52
+
53
+ * **VAE 解码** 学习如何使用混合推理进行 VAE 解码的基础知识。
54
+ * **VAE 编码** 学习如何使用混合推理进行 VAE 编码的基础知识。
55
+ * **API 参考** 深入了解任务特定设置和参数。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/hybrid_inference/vae_encode.md ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 入门:使用混合推理进行 VAE 编码
2
+
3
+ VAE 编码用于训练、图像到图像和图像到视频——将图像或视频转换为潜在表示。
4
+
5
+ ## 内存
6
+
7
+ 这些表格展示了在不同 GPU 上使用 SD v1 和 SD XL 进行 VAE 编码的 VRAM 需求。
8
+
9
+ 对于这些 GPU 中的大多数,内存使用百分比决定了其他模型(文本编码器、UNet/Transformer)必须被卸载,或者必须使用分块编码,这会增加时间并影响质量。
10
+
11
+ <details><summary>SD v1.5</summary>
12
+
13
+ | GPU | 分辨率 | 时间(秒) | 内存(%) | 分块时间(秒) | 分块内存(%) |
14
+ |:------------------------------|:-------------|-----------------:|-------------:|--------------------:|-------------------:|
15
+ | NVIDIA GeForce RTX 4090 | 512x512 | 0.015 | 3.51901 | 0.015 | 3.51901 |
16
+ | NVIDIA GeForce RTX 4090 | 256x256 | 0.004 | 1.3154 | 0.005 | 1.3154 |
17
+ | NVIDIA GeForce RTX 4090 | 2048x2048 | 0.402 | 47.1852 | 0.496 | 3.51901 |
18
+ | NVIDIA GeForce RTX 4090 | 1024x1024 | 0.078 | 12.2658 | 0.094 | 3.51901 |
19
+ | NVIDIA GeForce RTX 4080 SUPER | 512x512 | 0.023 | 5.30105 | 0.023 | 5.30105 |
20
+ | NVIDIA GeForce RTX 4080 SUPER | 256x256 | 0.006 | 1.98152 | 0.006 | 1.98152 |
21
+ | NVIDIA GeForce RTX 4080 SUPER | 2048x2048 | 0.574 | 71.08 | 0.656 | 5.30105 |
22
+ | NVIDIA GeForce RTX 4080 SUPER | 1024x1024 | 0.111 | 18.4772 | 0.14 | 5.30105 |
23
+ | NVIDIA GeForce RTX 3090 | 512x512 | 0.032 | 3.52782 | 0.032 | 3.52782 |
24
+ | NVIDIA GeForce RTX 3090 | 256x256 | 0.01 | 1.31869 | 0.009 | 1.31869 |
25
+ | NVIDIA GeForce RTX 3090 | 2048x2048 | 0.742 | 47.3033 | 0.954 | 3.52782 |
26
+ | NVIDIA GeForce RTX 3090 | 1024x1024 | 0.136 | 12.2965 | 0.207 | 3.52782 |
27
+ | NVIDIA GeForce RTX 3080 | 512x512 | 0.036 | 8.51761 | 0.036 | 8.51761 |
28
+ | NVIDIA GeForce RTX 3080 | 256x256 | 0.01 | 3.18387 | 0.01 | 3.18387 |
29
+ | NVIDIA GeForce RTX 3080 | 2048x2048 | 0.863 | 86.7424 | 1.191 | 8.51761 |
30
+ | NVIDIA GeForce RTX 3080 | 1024x1024 | 0.157 | 29.6888 | 0.227 | 8.51761 |
31
+ | NVIDIA GeForce RTX 3070 | 512x512 | 0.051 | 10.6941 | 0.051 | 10.6941 |
32
+ | NVIDIA GeForce RTX 3070 | 256x256 | 0.015 |
33
+ | 3.99743 | 0.015 | 3.99743 |
34
+ | NVIDIA GeForce RTX 3070 | 2048x2048 | 1.217 | 96.054 | 1.482 | 10.6941 |
35
+ | NVIDIA GeForce RTX 3070 | 1024x1024 | 0.223 | 37.2751 | 0.327 | 10.6941 |
36
+
37
+ </details>
38
+
39
+ <details><summary>SDXL</summary>
40
+
41
+ | GPU | Resolution | Time (seconds) | Memory Consumed (%) | Tiled Time (seconds) | Tiled Memory (%) |
42
+ |:------------------------------|:-------------|-----------------:|----------------------:|-----------------------:|-------------------:|
43
+ | NVIDIA GeForce RTX 4090 | 512x512 | 0.029 | 4.95707 | 0.029 | 4.95707 |
44
+ | NVIDIA GeForce RTX 4090 | 256x256 | 0.007 | 2.29666 | 0.007 | 2.29666 |
45
+ | NVIDIA GeForce RTX 4090 | 2048x2048 | 0.873 | 66.3452 | 0.863 | 15.5649 |
46
+ | NVIDIA GeForce RTX 4090 | 1024x1024 | 0.142 | 15.5479 | 0.143 | 15.5479 |
47
+ | NVIDIA GeForce RTX 4080 SUPER | 512x512 | 0.044 | 7.46735 | 0.044 | 7.46735 |
48
+ | NVIDIA GeForce RTX 4080 SUPER | 256x256 | 0.01 | 3.4597 | 0.01 | 3.4597 |
49
+ | NVIDIA GeForce RTX 4080 SUPER | 2048x2048 | 1.317 | 87.1615 | 1.291 | 23.447 |
50
+ | NVIDIA GeForce RTX 4080 SUPER | 1024x1024 | 0.213 | 23.4215 | 0.214 | 23.4215 |
51
+ | NVIDIA GeForce RTX 3090 | 512x512 | 0.058 | 5.65638 | 0.058 | 5.65638 |
52
+ | NVIDIA GeForce RTX 3090 | 256x256 | 0.016 | 2.45081 | 0.016 | 2.45081 |
53
+ | NVIDIA GeForce RTX 3090 | 2048x2048 | 1.755 | 77.8239 | 1.614 | 18.4193 |
54
+ | NVIDIA GeForce RTX 3090 | 1024x1024 | 0.265 | 18.4023 | 0.265 | 18.4023 |
55
+ | NVIDIA GeForce RTX 3080 | 512x512 | 0.064 | 13.6568 | 0.064 | 13.6568 |
56
+ | NVIDIA GeForce RTX 3080 | 256x256 | 0.018 | 5.91728 | 0.018 | 5.91728 |
57
+ | NVIDIA GeForce RTX 3080 | 2048x2048 | 内存不足 (OOM) | 内存不足 (OOM) | 1.866 | 44.4717 |
58
+ | NVIDIA GeForce RTX 3080 | 1024x1024 | 0.302 | 44.4308 | 0.302 | 44.4308 |
59
+ | NVIDIA GeForce RTX 3070 | 512x512 | 0.093 | 17.1465 | 0.093 | 17.1465 |
60
+ | NVIDIA GeForce R
61
+ | NVIDIA GeForce RTX 3070 | 256x256 | 0.025 | 7.42931 | 0.026 | 7.42931 |
62
+ | NVIDIA GeForce RTX 3070 | 2048x2048 | OOM | OOM | 2.674 | 55.8355 |
63
+ | NVIDIA GeForce RTX 3070 | 1024x1024 | 0.443 | 55.7841 | 0.443 | 55.7841 |
64
+
65
+ </details>
66
+
67
+ ## 可用 VAE
68
+
69
+ | | **端点** | **模型** |
70
+ |:-:|:-----------:|:--------:|
71
+ | **Stable Diffusion v1** | [https://qc6479g0aac6qwy9.us-east-1.aws.endpoints.huggingface.cloud](https://qc6479g0aac6qwy9.us-east-1.aws.endpoints.huggingface.cloud) | [`stabilityai/sd-vae-ft-mse`](https://hf.co/stabilityai/sd-vae-ft-mse) |
72
+ | **Stable Diffusion XL** | [https://xjqqhmyn62rog84g.us-east-1.aws.endpoints.huggingface.cloud](https://xjqqhmyn62rog84g.us-east-1.aws.endpoints.huggingface.cloud) | [`madebyollin/sdxl-vae-fp16-fix`](https://hf.co/madebyollin/sdxl-vae-fp16-fix) |
73
+ | **Flux** | [https://ptccx55jz97f9zgo.us-east-1.aws.endpoints.huggingface.cloud](https://ptccx55jz97f9zgo.us-east-1.aws.endpoints.huggingface.cloud) | [`black-forest-labs/FLUX.1-schnell`](https://hf.co/black-forest-labs/FLUX.1-schnell) |
74
+
75
+
76
+ > [!TIP]
77
+ > 模型支持可以在此处请求:[这里](https://github.com/huggingface/diffusers/issues/new?template=remote-vae-pilot-feedback.yml)。
78
+
79
+
80
+ ## 代码
81
+
82
+ > [!TIP]
83
+ > 从 `main` 安装 `diffusers` 以运行代码:`pip install git+https://github.com/huggingface/diffusers@main`
84
+
85
+
86
+ 一个辅助方法简化了与混合推理的交互。
87
+
88
+ ```python
89
+ from diffusers.utils.remote_utils import remote_encode
90
+ ```
91
+
92
+ ### 基本示例
93
+
94
+ 让我们编码一张图像,然后解码以演示。
95
+
96
+ <figure class="image flex flex-col items-center justify-center text-center m-0 w-full">
97
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"/>
98
+ </figure>
99
+
100
+ <details><summary>代码</summary>
101
+
102
+ ```python
103
+ from diffusers.utils import load_image
104
+ from diffusers.utils.remote_utils import remote_decode
105
+
106
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg?download=true")
107
+
108
+ latent = remote_encode(
109
+ endpoint="https://ptccx55jz97f9zgo.us-east-1.aws.endpoints.huggingface.cloud/",
110
+ scaling_factor=0.3611,
111
+ shift_factor=0.1159,
112
+ )
113
+
114
+ decoded = remote_decode(
115
+ endpoint="https://whhx50ex1aryqvw6.us-east-1.aws.endpoints.huggingface.cloud/",
116
+ tensor=latent,
117
+ scaling_factor=0.3611,
118
+ shift_factor=0.1159,
119
+ )
120
+ ```
121
+
122
+ </details>
123
+
124
+ <figure class="image flex flex-col items-center justify-center text-center m-0 w-full">
125
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/remote_vae/decoded.png"/>
126
+ </figure>
127
+
128
+
129
+ ### 生成
130
+
131
+ 现在让我们看一个生成示例,我们将编码图像,生成,然后远程解码!
132
+
133
+ <details><summary>代码</summary>
134
+
135
+ ```python
136
+ import torch
137
+ from diffusers import StableDiffusionImg2ImgPip
138
+ from diffusers.utils import load_image
139
+ from diffusers.utils.remote_utils import remote_decode, remote_encode
140
+
141
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
142
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
143
+ torch_dtype=torch.float16,
144
+ variant="fp16",
145
+ vae=None,
146
+ ).to("cuda")
147
+
148
+ init_image = load_image(
149
+ "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
150
+ )
151
+ init_image = init_image.resize((768, 512))
152
+
153
+ init_latent = remote_encode(
154
+ endpoint="https://qc6479g0aac6qwy9.us-east-1.aws.endpoints.huggingface.cloud/",
155
+ image=init_image,
156
+ scaling_factor=0.18215,
157
+ )
158
+
159
+ prompt = "A fantasy landscape, trending on artstation"
160
+ latent = pipe(
161
+ prompt=prompt,
162
+ image=init_latent,
163
+ strength=0.75,
164
+ output_type="latent",
165
+ ).images
166
+
167
+ image = remote_decode(
168
+ endpoint="https://q1bj3bpq6kzilnsu.us-east-1.aws.endpoints.huggingface.cloud/",
169
+ tensor=latent,
170
+ scaling_factor=0.18215,
171
+ )
172
+ image.save("fantasy_landscape.jpg")
173
+ ```
174
+
175
+ </details>
176
+
177
+ <figure class="image flex flex-col items-center justify-center text-center m-0 w-full">
178
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/remote_vae/fantasy_landscape.png"/>
179
+ </figure>
180
+
181
+ ## 集成
182
+
183
+ * **[SD.Next](https://github.com/vladmandic/sdnext):** 具有直接支持混合推理功能的一体化用户界面。
184
+ * **[ComfyUI-HFRemoteVae](https://github.com/kijai/ComfyUI-HFRemoteVae):** 用于混合推理的 ComfyUI 节点。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/index.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ <p align="center">
14
+ <br>
15
+ <img src="https://raw.githubusercontent.com/huggingface/diffusers/77aadfee6a891ab9fcfb780f87c693f7a5beeb8e/docs/source/imgs/diffusers_library.jpg" width="400"/>
16
+ <br>
17
+ </p>
18
+
19
+ # 🧨 Diffusers
20
+
21
+ 🤗 Diffusers 是一个值得首选用于生成图像、音频甚至 3D 分子结构的,最先进的预训练扩散模型库。
22
+ 无论您是在寻找简单的推理解决方案,还是想训练自己的扩散模型,🤗 Diffusers 这一模块化工具箱都能对其提供支持。
23
+ 本库的设计更偏重于[可用而非高性能](conceptual/philosophy#usability-over-performance)、[简明而非简单](conceptual/philosophy#simple-over-easy)以及[易用而非抽象](conceptual/philosophy#tweakable-contributorfriendly-over-abstraction)。
24
+
25
+
26
+ 本库包含三个主要组件:
27
+
28
+ - 最先进的扩散管道 [diffusion pipelines](api/pipelines/overview),只需几行代码即可进行推理。
29
+ - 可交替使用的各种噪声调度器 [noise schedulers](api/schedulers/overview),用于平衡生成速度和质量。
30
+ - 预训练模型 [models](api/models),可作为构建模块,并与调度程序结合使用,来创建您自己的端到端扩散系统。
31
+
32
+ <div class="mt-10">
33
+ <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
34
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorials/tutorial_overview"
35
+ ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutorials</div>
36
+ <p class="text-gray-700">Learn the fundamental skills you need to start generating outputs, build your own diffusion system, and train a diffusion model. We recommend starting here if you're using 🤗 Diffusers for the first time!</p>
37
+ </a>
38
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./using-diffusers/loading_overview"
39
+ ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">How-to guides</div>
40
+ <p class="text-gray-700">Practical guides for helping you load pipelines, models, and schedulers. You'll also learn how to use pipelines for specific tasks, control how outputs are generated, optimize for inference speed, and different training techniques.</p>
41
+ </a>
42
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./conceptual/philosophy"
43
+ ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Conceptual guides</div>
44
+ <p class="text-gray-700">Understand why the library was designed the way it was, and learn more about the ethical guidelines and safety implementations for using the library.</p>
45
+ </a>
46
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./api/models"
47
+ ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Reference</div>
48
+ <p class="text-gray-700">Technical descriptions of how 🤗 Diffusers classes and methods work.</p>
49
+ </a>
50
+ </div>
51
+ </div>
52
+
53
+ ## 🧨 Diffusers pipelines
54
+
55
+ 下表汇总了当前所有官方支持的pipelines及其对应的论文.
56
+
57
+ | 管道 | 论文/仓库 | 任务 |
58
+ |---|---|:---:|
59
+ | [alt_diffusion](./api/pipelines/alt_diffusion) | [AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://huggingface.co/papers/2211.06679) | Image-to-Image Text-Guided Generation |
60
+ | [audio_diffusion](./api/pipelines/audio_diffusion) | [Audio Diffusion](https://github.com/teticio/audio-diffusion.git) | Unconditional Audio Generation |
61
+ | [controlnet](./api/pipelines/stable_diffusion/controlnet) | [Adding Conditional Control to Text-to-Image Diffusion Models](https://huggingface.co/papers/2302.05543) | Image-to-Image Text-Guided Generation |
62
+ | [cycle_diffusion](./api/pipelines/cycle_diffusion) | [Unifying Diffusion Models' Latent Space, with Applications to CycleDiffusion and Guidance](https://huggingface.co/papers/2210.05559) | Image-to-Image Text-Guided Generation |
63
+ | [dance_diffusion](./api/pipelines/dance_diffusion) | [Dance Diffusion](https://github.com/williamberman/diffusers.git) | Unconditional Audio Generation |
64
+ | [ddpm](./api/pipelines/ddpm) | [Denoising Diffusion Probabilistic Models](https://huggingface.co/papers/2006.11239) | Unconditional Image Generation |
65
+ | [ddim](./api/pipelines/ddim) | [Denoising Diffusion Implicit Models](https://huggingface.co/papers/2010.02502) | Unconditional Image Generation |
66
+ | [if](./if) | [**IF**](./api/pipelines/if) | Image Generation |
67
+ | [if_img2img](./if) | [**IF**](./api/pipelines/if) | Image-to-Image Generation |
68
+ | [if_inpainting](./if) | [**IF**](./api/pipelines/if) | Image-to-Image Generation |
69
+ | [latent_diffusion](./api/pipelines/latent_diffusion) | [High-Resolution Image Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752)| Text-to-Image Generation |
70
+ | [latent_diffusion](./api/pipelines/latent_diffusion) | [High-Resolution Image Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752)| Super Resolution Image-to-Image |
71
+ | [latent_diffusion_uncond](./api/pipelines/latent_diffusion_uncond) | [High-Resolution Image Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) | Unconditional Image Generation |
72
+ | [paint_by_example](./api/pipelines/paint_by_example) | [Paint by Example: Exemplar-based Image Editing with Diffusion Models](https://huggingface.co/papers/2211.13227) | Image-Guided Image Inpainting |
73
+ | [pndm](./api/pipelines/pndm) | [Pseudo Numerical Methods for Diffusion Models on Manifolds](https://huggingface.co/papers/2202.09778) | Unconditional Image Generation |
74
+ | [score_sde_ve](./api/pipelines/score_sde_ve) | [Score-Based Generative Modeling through Stochastic Differential Equations](https://openreview.net/forum?id=PxTIG12RRHS) | Unconditional Image Generation |
75
+ | [score_sde_vp](./api/pipelines/score_sde_vp) | [Score-Based Generative Modeling through Stochastic Differential Equations](https://openreview.net/forum?id=PxTIG12RRHS) | Unconditional Image Generation |
76
+ | [semantic_stable_diffusion](./api/pipelines/semantic_stable_diffusion) | [Semantic Guidance](https://huggingface.co/papers/2301.12247) | Text-Guided Generation |
77
+ | [stable_diffusion_text2img](./api/pipelines/stable_diffusion/text2img) | [Stable Diffusion](https://stability.ai/blog/stable-diffusion-public-release) | Text-to-Image Generation |
78
+ | [stable_diffusion_img2img](./api/pipelines/stable_diffusion/img2img) | [Stable Diffusion](https://stability.ai/blog/stable-diffusion-public-release) | Image-to-Image Text-Guided Generation |
79
+ | [stable_diffusion_inpaint](./api/pipelines/stable_diffusion/inpaint) | [Stable Diffusion](https://stability.ai/blog/stable-diffusion-public-release) | Text-Guided Image Inpainting |
80
+ | [stable_diffusion_panorama](./api/pipelines/stable_diffusion/panorama) | [MultiDiffusion](https://multidiffusion.github.io/) | Text-to-Panorama Generation |
81
+ | [stable_diffusion_pix2pix](./api/pipelines/stable_diffusion/pix2pix) | [InstructPix2Pix: Learning to Follow Image Editing Instructions](https://huggingface.co/papers/2211.09800) | Text-Guided Image Editing|
82
+ | [stable_diffusion_pix2pix_zero](./api/pipelines/stable_diffusion/pix2pix_zero) | [Zero-shot Image-to-Image Translation](https://pix2pixzero.github.io/) | Text-Guided Image Editing |
83
+ | [stable_diffusion_attend_and_excite](./api/pipelines/stable_diffusion/attend_and_excite) | [Attend-and-Excite: Attention-Based Semantic Guidance for Text-to-Image Diffusion Models](https://huggingface.co/papers/2301.13826) | Text-to-Image Generation |
84
+ | [stable_diffusion_self_attention_guidance](./api/pipelines/stable_diffusion/self_attention_guidance) | [Improving Sample Quality of Diffusion Models Using Self-Attention Guidance](https://huggingface.co/papers/2210.00939) | Text-to-Image Generation Unconditional Image Generation |
85
+ | [stable_diffusion_image_variation](./stable_diffusion/image_variation) | [Stable Diffusion Image Variations](https://github.com/LambdaLabsML/lambda-diffusers#stable-diffusion-image-variations) | Image-to-Image Generation |
86
+ | [stable_diffusion_latent_upscale](./stable_diffusion/latent_upscale) | [Stable Diffusion Latent Upscaler](https://twitter.com/StabilityAI/status/1590531958815064065) | Text-Guided Super Resolution Image-to-Image |
87
+ | [stable_diffusion_model_editing](./api/pipelines/stable_diffusion/model_editing) | [Editing Implicit Assumptions in Text-to-Image Diffusion Models](https://time-diffusion.github.io/) | Text-to-Image Model Editing |
88
+ | [stable_diffusion_2](./api/pipelines/stable_diffusion_2) | [Stable Diffusion 2](https://stability.ai/blog/stable-diffusion-v2-release) | Text-to-Image Generation |
89
+ | [stable_diffusion_2](./api/pipelines/stable_diffusion_2) | [Stable Diffusion 2](https://stability.ai/blog/stable-diffusion-v2-release) | Text-Guided Image Inpainting |
90
+ | [stable_diffusion_2](./api/pipelines/stable_diffusion_2) | [Depth-Conditional Stable Diffusion](https://github.com/Stability-AI/stablediffusion#depth-conditional-stable-diffusion) | Depth-to-Image Generation |
91
+ | [stable_diffusion_2](./api/pipelines/stable_diffusion_2) | [Stable Diffusion 2](https://stability.ai/blog/stable-diffusion-v2-release) | Text-Guided Super Resolution Image-to-Image |
92
+ | [stable_diffusion_safe](./api/pipelines/stable_diffusion_safe) | [Safe Stable Diffusion](https://huggingface.co/papers/2211.05105) | Text-Guided Generation |
93
+ | [stable_unclip](./stable_unclip) | Stable unCLIP | Text-to-Image Generation |
94
+ | [stable_unclip](./stable_unclip) | Stable unCLIP | Image-to-Image Text-Guided Generation |
95
+ | [stochastic_karras_ve](./api/pipelines/stochastic_karras_ve) | [Elucidating the Design Space of Diffusion-Based Generative Models](https://huggingface.co/papers/2206.00364) | Unconditional Image Generation |
96
+ | [text_to_video_sd](./api/pipelines/text_to_video) | [Modelscope's Text-to-video-synthesis Model in Open Domain](https://modelscope.cn/models/damo/text-to-video-synthesis/summary) | Text-to-Video Generation |
97
+ | [unclip](./api/pipelines/unclip) | [Hierarchical Text-Conditional Image Generation with CLIP Latents](https://huggingface.co/papers/2204.06125)(implementation by [kakaobrain](https://github.com/kakaobrain/karlo)) | Text-to-Image Generation |
98
+ | [versatile_diffusion](./api/pipelines/versatile_diffusion) | [Versatile Diffusion: Text, Images and Variations All in One Diffusion Model](https://huggingface.co/papers/2211.08332) | Text-to-Image Generation |
99
+ | [versatile_diffusion](./api/pipelines/versatile_diffusion) | [Versatile Diffusion: Text, Images and Variations All in One Diffusion Model](https://huggingface.co/papers/2211.08332) | Image Variations Generation |
100
+ | [versatile_diffusion](./api/pipelines/versatile_diffusion) | [Versatile Diffusion: Text, Images and Variations All in One Diffusion Model](https://huggingface.co/papers/2211.08332) | Dual Image and Text Guided Generation |
101
+ | [vq_diffusion](./api/pipelines/vq_diffusion) | [Vector Quantized Diffusion Model for Text-to-Image Synthesis](https://huggingface.co/papers/2111.14822) | Text-to-Image Generation |
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/installation.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # 安装
14
+
15
+ 在你正在使用的任意深度学习框架中安装 🤗 Diffusers 。
16
+
17
+ 🤗 Diffusers已在Python 3.8+、PyTorch 1.7.0+和Flax上进行了测试。按照下面的安装说明,针对你正在使用的深度学习框架进行安装:
18
+
19
+ - [PyTorch](https://pytorch.org/get-started/locally/) installation instructions.
20
+ - [Flax](https://flax.readthedocs.io/en/latest/) installation instructions.
21
+
22
+ ## 使用pip安装
23
+
24
+ 你需要在[虚拟环境](https://docs.python.org/3/library/venv.html)中安装 🤗 Diffusers 。
25
+
26
+ 如果你对 Python 虚拟环境不熟悉,可以看看这个[教程](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
27
+
28
+ 在虚拟环境中,你可以轻松管理不同的项目,避免依赖项之间的兼容性问题。
29
+
30
+ 首先,在你的项目目录下创建一个虚拟环境:
31
+
32
+ ```bash
33
+ python -m venv .env
34
+ ```
35
+
36
+ 激活虚拟环境:
37
+
38
+ ```bash
39
+ source .env/bin/activate
40
+ ```
41
+
42
+ 现在,你就可以安装 🤗 Diffusers了!使用下边这个命令:
43
+
44
+ **PyTorch**
45
+
46
+ ```bash
47
+ pip install diffusers["torch"]
48
+ ```
49
+
50
+ **Flax**
51
+
52
+ ```bash
53
+ pip install diffusers["flax"]
54
+ ```
55
+
56
+ ## 从源代码安装
57
+
58
+ 在从源代码安装 `diffusers` 之前,确保你已经安装了 `torch` 和 `accelerate`。
59
+
60
+ `torch`的安装教程可以看 `torch` [文档](https://pytorch.org/get-started/locally/#start-locally).
61
+
62
+ 安装 `accelerate`
63
+
64
+ ```bash
65
+ pip install accelerate
66
+ ```
67
+
68
+ 从源码安装 🤗 Diffusers 需要使用以下命令:
69
+
70
+ ```bash
71
+ pip install git+https://github.com/huggingface/diffusers
72
+ ```
73
+
74
+ 这个命令安装的是最新的 `main`版本,而不是最近的`stable`版。
75
+ `main`是一直和最新进展保持一致的。比如,上次发布的正式版中有bug,在`main`中可以看到这个bug被修复了,但是新的正式版此时尚未推出。
76
+ 但是这也意味着 `main`版本不保证是稳定的。
77
+
78
+ 我们努力保持`main`版本正常运行,大多数问题都能在几个小时或一天之内解决
79
+
80
+ 如果你遇到了问题,可以提 [Issue](https://github.com/huggingface/transformers/issues),这样我们就能更快修复问题了。
81
+
82
+ ## 可修改安装
83
+
84
+ 如果你想做以下两件事,那你可能需要一个可修改代码的安装方式:
85
+
86
+ * 使用 `main`版本的源代码。
87
+ * 为 🤗 Diffusers 贡献,需要测试代码中的变化。
88
+
89
+ 使用以下命令克隆并安装 🤗 Diffusers:
90
+
91
+ ```bash
92
+ git clone https://github.com/huggingface/diffusers.git
93
+ cd diffusers
94
+ ```
95
+
96
+ **PyTorch**
97
+
98
+ ```sh
99
+ pip install -e ".[torch]"
100
+ ```
101
+
102
+ **Flax**
103
+
104
+ ```sh
105
+ pip install -e ".[flax]"
106
+ ```
107
+
108
+ 这些命令将连接到你克隆的版本库和你的 Python 库路径。
109
+ 现在,不只是在通常的库路径,Python 还会在你克隆的文件夹内寻找包。
110
+ 例如,如果你的 Python 包通常安装在 `~/anaconda3/envs/main/lib/python3.10/Site-packages/`,Python 也会搜索你克隆到的文件夹。`~/diffusers/`。
111
+
112
+ > [!WARNING]
113
+ > 如果你想继续使用这个库,你必须保留 `diffusers` 文件夹。
114
+
115
+
116
+ 现在你可以用下面的命令轻松地将你克隆的 🤗 Diffusers 库更新到最新版本。
117
+
118
+ ```bash
119
+ cd ~/diffusers/
120
+ git pull
121
+ ```
122
+
123
+ 你的Python环境将在下次运行时找到`main`版本的 🤗 Diffusers。
124
+
125
+ ## 注意 Telemetry 日志
126
+
127
+ 我们的库会在使用`from_pretrained()`请求期间收集 telemetry 信息。这些数据包括Diffusers和PyTorch/Flax的版本,请求的模型或管道类,以及预训练检查点的路径(如果它被托管在Hub上的话)。
128
+ 这些使用数据有助于我们调试问题并确定新功能的开发优先级。
129
+ Telemetry 数据仅在从 HuggingFace Hub 中加载模型和管道时发送,而不会在本地使用期间收集。
130
+
131
+ 我们知道,并不是每个人都想分享这些的信息,我们尊重您的隐私,
132
+ 因此您可以通过在终端中设置 `DISABLE_TELEMETRY` 环境变量从而禁用 Telemetry 数据收集:
133
+
134
+
135
+ Linux/MacOS :
136
+ ```bash
137
+ export DISABLE_TELEMETRY=YES
138
+ ```
139
+
140
+ Windows :
141
+ ```bash
142
+ set DISABLE_TELEMETRY=YES
143
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/auto_pipeline_blocks.md ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据Apache许可证2.0版("许可证")授权;除非符合许可证,否则不得使用此文件。您可以在
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 获取许可证的副本。
8
+
9
+ 除非适用法律要求或书面同意,根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。有关许可证的特定语言管理权限和限制,请参阅许可证。
10
+ -->
11
+
12
+ # AutoPipelineBlocks
13
+
14
+ [`~modular_pipelines.AutoPipelineBlocks`] 是一种包含支持不同工作流程的块的多块类型。它根据运行时提供的输入自动选择要运行的子块。这通常用于将多个工作流程(文本到图像、图像到图像、修复)打包到一个管道中以便利。
15
+
16
+ 本指南展示如何创建 [`~modular_pipelines.AutoPipelineBlocks`]。
17
+
18
+ 创建三个 [`~modular_pipelines.ModularPipelineBlocks`] 用于文本到图像、图像到图像和修复。这些代表了管道中可用的不同工作流程。
19
+
20
+ <hfoptions id="auto">
21
+ <hfoption id="text-to-image">
22
+
23
+ ```py
24
+ import torch
25
+ from diffusers.modular_pipelines import ModularPipelineBlocks, InputParam, OutputParam
26
+
27
+ class TextToImageBlock(ModularPipelineBlocks):
28
+ model_name = "text2img"
29
+
30
+ @property
31
+ def inputs(self):
32
+ return [InputParam(name="prompt")]
33
+
34
+ @property
35
+ def intermediate_outputs(self):
36
+ return []
37
+
38
+ @property
39
+ def description(self):
40
+ return "我是一个文本到图像的工作流程!"
41
+
42
+ def __call__(self, components, state):
43
+ block_state = self.get_block_state(state)
44
+ print("运行文本到图像工作流程")
45
+ # 在这里添加你的文本到图像逻辑
46
+ # 例如:根据提示生成图像
47
+ self.set_block_state(state, block_state)
48
+ return components, state
49
+ ```
50
+
51
+
52
+ </hfoption>
53
+ <hfoption id="image-to-image">
54
+
55
+ ```py
56
+ class ImageToImageBlock(ModularPipelineBlocks):
57
+ model_name = "img2img"
58
+
59
+ @property
60
+ def inputs(self):
61
+ return [InputParam(name="prompt"), InputParam(name="image")]
62
+
63
+ @property
64
+ def intermediate_outputs(self):
65
+ return []
66
+
67
+ @property
68
+ def description(self):
69
+ return "我是一个图像到图像的工作流程!"
70
+
71
+ def __call__(self, components, state):
72
+ block_state = self.get_block_state(state)
73
+ print("运行图像到图像工作流程")
74
+ # 在这里添加你的图像到图像逻辑
75
+ # 例如:根据提示转换输入图像
76
+ self.set_block_state(state, block_state)
77
+ return components, state
78
+ ```
79
+
80
+
81
+ </hfoption>
82
+ <hfoption id="inpaint">
83
+
84
+ ```py
85
+ class InpaintBlock(ModularPipelineBlocks):
86
+ model_name = "inpaint"
87
+
88
+ @property
89
+ def inputs(self):
90
+ return [InputParam(name="prompt"), InputParam(name="image"), InputParam(name="mask")]
91
+
92
+ @property
93
+
94
+ def intermediate_outputs(self):
95
+ return []
96
+
97
+ @property
98
+ def description(self):
99
+ return "我是一个修复工作流!"
100
+
101
+ def __call__(self, components, state):
102
+ block_state = self.get_block_state(state)
103
+ print("运行修复工作流")
104
+ # 在这里添加你的修复逻辑
105
+ # 例如:根据提示填充被遮罩的区域
106
+ self.set_block_state(state, block_state)
107
+ return components, state
108
+ ```
109
+
110
+ </hfoption>
111
+ </hfoptions>
112
+
113
+ 创建一个包含子块类及其对应块名称列表的[`~modular_pipelines.AutoPipelineBlocks`]类。
114
+
115
+ 你还需要包括`block_trigger_inputs`,一个触发相应块的输入名称列表。如果在运行时提供了触发输入,则选择该块运行。使用`None`来指定如果未检测到触发输入时运行的默认块。
116
+
117
+ 最后,重要的是包括一个`description`,清楚地解释哪些输入触发哪些工作流。这有助于用户理解如何运行特定的工作流。
118
+
119
+ ```py
120
+ from diffusers.modular_pipelines import AutoPipelineBlocks
121
+
122
+ class AutoImageBlocks(AutoPipelineBlocks):
123
+ # 选择子块类的列表
124
+ block_classes = [block_inpaint_cls, block_i2i_cls, block_t2i_cls]
125
+ # 每个块的名称,顺序相同
126
+ block_names = ["inpaint", "img2img", "text2img"]
127
+ # 决定运行哪个块的触发输入
128
+ # - "mask" 触发修复工作流
129
+ # - "image" 触发img2img工作流(但仅在未提供mask时)
130
+ # - 如果以上都没有,运行text2img工作流(默认)
131
+ block_trigger_inputs = ["mask", "image", None]
132
+ # 对于AutoPipelineBlocks来说,描述极其重要
133
+
134
+ def description(self):
135
+ return (
136
+ "Pipeline generates images given different types of conditions!\n"
137
+ + "This is an auto pipeline block that works for text2img, img2img and inpainting tasks.\n"
138
+ + " - inpaint workflow is run when `mask` is provided.\n"
139
+ + " - img2img workflow is run when `image` is provided (but only when `mask` is not provided).\n"
140
+ + " - text2img workflow is run when neither `image` nor `mask` is provided.\n"
141
+ )
142
+ ```
143
+
144
+ 包含`description`以避免任何关于如何运行块和需要什么输入的混淆**非常**重要。虽然[`~modular_pipelines.AutoPipelineBlocks`]很方便,但如果它没有正确解释,其条件逻辑可能难以理解。
145
+
146
+ 创建`AutoImageBlocks`的一个实例。
147
+
148
+ ```py
149
+ auto_blocks = AutoImageBlocks()
150
+ ```
151
+
152
+ 对于更复杂的组合,例如在更大的管道中作为子块使用的嵌套[`~modular_pipelines.AutoPipelineBlocks`]块,使用[`~modular_pipelines.SequentialPipelineBlocks.get_execution_blocks`]方法根据你的输入提取实际运行的块。
153
+
154
+ ```py
155
+ auto_blocks.get_execution_blocks("mask")
156
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/components_manager.md ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 HuggingFace 团队。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版("许可证")授权;除非遵守许可证,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。请参阅许可证以了解特定语言管理权限和限制。
8
+ -->
9
+
10
+ # 组件管理器
11
+
12
+ [`ComponentsManager`] 是 Modular Diffusers 的模型注册和管理系统。它添加和跟踪模型,存储有用的元数据(模型大小、设备放置、适配器),防止重复模型实例,并支持卸载。
13
+
14
+ 本指南将展示如何使用 [`ComponentsManager`] 来管理组件和设备内存。
15
+
16
+ ## 添加组件
17
+
18
+ [`ComponentsManager`] 应与 [`ModularPipeline`] 一起创建,在 [`~ModularPipeline.from_pretrained`] 或 [`~ModularPipelineBlocks.init_pipeline`] 中。
19
+
20
+ > [!TIP]
21
+ > `collection` 参数是可选的,但可以更轻松地组织和管理组件。
22
+
23
+ <hfoptions id="create">
24
+ <hfoption id="from_pretrained">
25
+
26
+ ```py
27
+ from diffusers import ModularPipeline, ComponentsManager
28
+
29
+ comp = ComponentsManager()
30
+ pipe = ModularPipeline.from_pretrained("YiYiXu/modular-demo-auto", components_manager=comp, collection="test1")
31
+ ```
32
+
33
+ </hfoption>
34
+ <hfoption id="init_pipeline">
35
+
36
+ ```py
37
+ from diffusers import ComponentsManager
38
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
39
+ from diffusers.modular_pipelines.stable_diffusion_xl import TEXT2IMAGE_BLOCKS
40
+
41
+ t2i_blocks = SequentialPipelineBlocks.from_blocks_dict(TEXT2IMAGE_BLOCKS)
42
+
43
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
44
+ components = ComponentsManager()
45
+ t2i_pipeline = t2i_blocks.init_pipeline(modular_repo_id, components_manager=components)
46
+ ```
47
+
48
+ </hfoption>
49
+ </hfoptions>
50
+
51
+ 组件仅在调用 [`~ModularPipeline.load_components`] 或 [`~ModularPipeline.load_components`] 时加载和注册。以下示例使用 [`~ModularPipeline.load_components`] 创建第二个管道,重用第一个管道的所有组件,并将其分配到不同的集合。
52
+
53
+ ```py
54
+ pipe.load_components()
55
+ pipe2 = ModularPipeline.from_pretrained("YiYiXu/modular-demo-auto", components_manager=comp, collection="test2")
56
+ ```
57
+
58
+ 使用 [`~ModularPipeline.null_component_names`] 属性来识别需要加载的任何组件,使用 [`~ComponentsManager.get_components_by_names`] 检索它们,然后调用 [`~ModularPipeline.update_components`] 来添加缺失的组件。
59
+
60
+ ```py
61
+ pipe2.null_component_names
62
+ ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'image_encoder', 'unet', 'vae', 'scheduler', 'controlnet']
63
+
64
+ comp_dict = comp.get_components_by_names(names=pipe2.null_component_names)
65
+ pipe2.update_components(**comp_dict)
66
+ ```
67
+
68
+ 要添加单个组件,请使用 [`~ComponentsManager.add`] 方法。这会使用唯一 id 注册一个组件。
69
+
70
+ ```py
71
+ from diffusers import AutoModel
72
+
73
+ text_encoder = AutoModel.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="text_encoder")
74
+ component_id = comp.add("text_encoder", text_encoder)
75
+ comp
76
+ ```
77
+
78
+ 使用 [`~ComponentsManager.remove`] 通过其 id 移除一个组件。
79
+
80
+ ```py
81
+ comp.remove("text_encoder_139917733042864")
82
+ ```
83
+
84
+ ## 检索组件
85
+
86
+ [`ComponentsManager`] 提供了几种方法来检索已注册的组件。
87
+
88
+ ### get_one
89
+
90
+ [`~ComponentsManager.get_one`] 方法返回单个组件,并支持对 `name` 参数进行模式匹配。如果多个组件匹配,[`~ComponentsManager.get_one`] 会返回错误。
91
+
92
+ | 模式 | 示例 | 描述 |
93
+ |-------------|----------------------------------|-------------------------------------------|
94
+ | exact | `comp.get_one(name="unet")` | 精确名称匹配 |
95
+ | wildcard | `comp.get_one(name="unet*")` | 名称以 "unet" 开头 |
96
+ | exclusion | `comp.get_one(name="!unet")` | 排除名为 "unet" 的组件 |
97
+ | or | `comp.get_one(name="unet&#124;vae")` | 名称为 "unet" 或 "vae" |
98
+
99
+ [`~ComponentsManager.get_one`] 还通过 `collection` 参数或 `load_id` 参数过滤组件。
100
+
101
+ ```py
102
+ comp.get_one(name="unet", collection="sdxl")
103
+ ```
104
+
105
+ ### get_components_by_names
106
+
107
+ [`~ComponentsManager.get_components_by_names`] 方法接受一个名称列表,并返回一个将名称映射到组件的字典。这在 [`ModularPipeline`] 中特别有用,因为它们提供了所需组件名称的列表,并且返回的字典可以直接传递给 [`~ModularPipeline.update_components`]。
108
+
109
+ ```py
110
+ component_dict = comp.get_components_by_names(names=["text_encoder", "unet", "vae"])
111
+ {"text_encoder": component1, "unet": component2, "vae": component3}
112
+ ```
113
+
114
+ ## 重复检测
115
+
116
+ 建议使用 [`ComponentSpec`] 加载模型组件,以分配具有唯一 id 的组件,该 id 编码了它们的加载参数。这允许 [`ComponentsManager`] 自动检测并防止重复的模型实例,即使不同的对象代表相同的底层检查点。
117
+
118
+ ```py
119
+ from diffusers import ComponentSpec, ComponentsManager
120
+ from transformers import CLIPTextModel
121
+
122
+ comp = ComponentsManager()
123
+
124
+ # 为第一个文本编码器创建 ComponentSpec
125
+ spec = ComponentSpec(name="text_encoder", repo="stabilityai/stable-diffusion-xl-base-1.0", subfolder="text_encoder", type_hint=AutoModel)
126
+ # 为重复的文本编码器创建 ComponentSpec(它是相同的检查点,来自相同的仓库/子文件夹)
127
+ spec_duplicated = ComponentSpec(name="text_encoder_duplicated", repo="stabilityai/stable-diffusion-xl-base-1.0", subfolder="text_encoder", ty
128
+ pe_hint=CLIPTextModel)
129
+
130
+ # 加载并添加两个组件 - 管理器会检测到它们是同一个模型
131
+ comp.add("text_encoder", spec.load())
132
+ comp.add("text_encoder_duplicated", spec_duplicated.load())
133
+ ```
134
+
135
+ 这会返回一个警告,附带移除重复项的说明。
136
+
137
+ ```py
138
+ ComponentsManager: adding component 'text_encoder_duplicated_139917580682672', but it has duplicate load_id 'stabilityai/stable-diffusion-xl-base-1.0|text_encoder|null|null' with existing components: text_encoder_139918506246832. To remove a duplicate, call `components_manager.remove('<component_id>')`.
139
+ 'text_encoder_duplicated_139917580682672'
140
+ ```
141
+
142
+ 您也可以不使用 [`ComponentSpec`] 添加组件,并且在大多数情况下,即使您以不同名称添加相同组件,重复检测仍然有效。
143
+
144
+ 然而,当您将相同组件加载到不同对象时,[`ComponentManager`] 无法检测重复项。在这种情况下,您应该使用 [`ComponentSpec`] 加载模型。
145
+
146
+ ```py
147
+ text_encoder_2 = AutoModel.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="text_encoder")
148
+ comp.add("text_encoder", text_encoder_2)
149
+ 'text_encoder_139917732983664'
150
+ ```
151
+
152
+ ## 集合
153
+
154
+ 集合是为组件分配的标签,用于更好的组织和管理。使用 [`~ComponentsManager.add`] 中的 `collection` 参数将组件添加到集合中。
155
+
156
+ 每个集合中只允许每个名称有一个组件。添加第二个同名组件会自动移除第一个组件。
157
+
158
+ ```py
159
+ from diffusers import ComponentSpec, ComponentsManager
160
+
161
+ comp = ComponentsManager()
162
+ # 为第一个 UNet 创建 ComponentSpec
163
+ spec = ComponentSpec(name="unet", repo="stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", type_hint=AutoModel)
164
+ # 为另一个 UNet 创建 ComponentSpec
165
+ spec2 = ComponentSpec(name="unet", repo="RunDiffusion/Juggernaut-XL-v9", subfolder="unet", type_hint=AutoModel, variant="fp16")
166
+
167
+ # 将两个 UNet 添加到同一个集合 - 第二个将替换第一个
168
+ comp.add("unet", spec.load(), collection="sdxl")
169
+ comp.add("unet", spec2.load(), collection="sdxl")
170
+ ```
171
+
172
+ 这使得在基于节点的系统中工作变得方便,因为您可以:
173
+
174
+ - 使用 `collection` 标签标记所有从一个节点加载的模型。
175
+ - 当新检查点以相同名称加载时自动替换模型。
176
+ - 当节点被移除时批量删除集合中的所有模型。
177
+
178
+ ## 卸载
179
+
180
+ [`~ComponentsManager.enable_auto_cpu_offload`] 方法是一种全局卸载策略,适用于所有模型,无论哪个管道在使用它们。一旦启用,您无需担心设备放置,如果您添加或移除组件。
181
+
182
+ ```py
183
+ comp.enable_auto_cpu_offload(device="cuda")
184
+ ```
185
+
186
+ 所有模型开始时都在 CPU 上,[`ComponentsManager`] 在需要它们之前将它们移动到适当的设备,并在 GPU 内存不足时将其他模型移回 CPU。
187
+
188
+ 您可以设置自己的规则来决定哪些模型要卸载。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/loop_sequential_pipeline_blocks.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版("许可证")授权;除非符合许可证,否则不得使用此文件。您可以在
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 获取许可证的副本。
8
+
9
+ 除非适用法律要求或书面同意,根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。请参阅许可证了解
10
+ 特定语言下的权限和限制。
11
+ -->
12
+
13
+ # LoopSequentialPipelineBlocks
14
+
15
+ [`~modular_pipelines.LoopSequentialPipelineBlocks`] 是一种多块类型,它将其他 [`~modular_pipelines.ModularPipelineBlocks`] 以循环方式组合在一起。数据循环流动,使用 `intermediate_inputs` 和 `intermediate_outputs`,并且每个块都是迭代运行的。这通常用于创建一个默认是迭代的去噪循环。
16
+
17
+ 本指南向您展示如何创建 [`~modular_pipelines.LoopSequentialPipelineBlocks`]。
18
+
19
+ ## 循环包装器
20
+
21
+ [`~modular_pipelines.LoopSequentialPipelineBlocks`],也被称为 *循环包装器*,因为它定义了循环结构、迭代变量和配置。在循环包装器内,您需要以下变量。
22
+
23
+ - `loop_inputs` 是用户提供的值,等同于 [`~modular_pipelines.ModularPipelineBlocks.inputs`]。
24
+ - `loop_intermediate_inputs` 是来自 [`~modular_pipelines.PipelineState`] 的中间变量,等同于 [`~modular_pipelines.ModularPipelineBlocks.intermediate_inputs`]。
25
+ - `loop_intermediate_outputs` 是由块创建并添加到 [`~modular_pipelines.PipelineState`] 的新中间变量。它等同于 [`~modular_pipelines.ModularPipelineBlocks.intermediate_outputs`]。
26
+ - `__call__` 方法定义了循环结构和迭代逻辑。
27
+
28
+ ```py
29
+ import torch
30
+ from diffusers.modular_pipelines import LoopSequentialPipelineBlocks, ModularPipelineBlocks, InputParam, OutputParam
31
+
32
+ class LoopWrapper(LoopSequentialPipelineBlocks):
33
+ model_name = "test"
34
+ @property
35
+ def description(self):
36
+ return "I'm a loop!!"
37
+ @property
38
+ def loop_inputs(self):
39
+ return [InputParam(name="num_steps")]
40
+ @torch.no_grad()
41
+ def __call__(self, components, state):
42
+ block_state = self.get_block_state(state)
43
+ # 循环结构 - 可以根据您的需求定制
44
+ for i in range(block_state.num_steps):
45
+ # loop_step 按顺序执行所有注册的块
46
+ components, block_state = self.loop_step(components, block_state, i=i)
47
+ self.set_block_state(state, block_state)
48
+ return components, state
49
+ ```
50
+
51
+ 循环包装器可以传递额外的参数,如当前迭代索引,到循环块。
52
+
53
+ ## 循环块
54
+
55
+ 循环块是一个 [`~modular_pipelines.ModularPipelineBlocks`],但 `__call__` 方法的行为不同。
56
+
57
+ - 它从循环包装器。
58
+ - 它直接与[`~modular_pipelines.BlockState`]一起工作,而不是[`~modular_pipelines.PipelineState`]。
59
+ - 它不需要检索或更新[`~modular_pipelines.BlockState`]。
60
+
61
+ 循环块共享相同的[`~modular_pipelines.BlockState`],以允许值在循环的每次迭代中累积和变化。
62
+
63
+ ```py
64
+ class LoopBlock(ModularPipelineBlocks):
65
+ model_name = "test"
66
+ @property
67
+ def inputs(self):
68
+ return [InputParam(name="x")]
69
+ @property
70
+ def intermediate_outputs(self):
71
+ # 这个块产生的输出
72
+ return [OutputParam(name="x")]
73
+ @property
74
+ def description(self):
75
+ return "我是一个在`LoopWrapper`类内部使用的块"
76
+ def __call__(self, components, block_state, i: int):
77
+ block_state.x += 1
78
+ return components, block_state
79
+ ```
80
+
81
+ ## LoopSequentialPipelineBlocks
82
+
83
+ 使用[`~modular_pipelines.LoopSequentialPipelineBlocks.from_blocks_dict`]方法将循环块添加到循环包装器中,以创建[`~modular_pipelines.LoopSequentialPipelineBlocks`]。
84
+
85
+ ```py
86
+ loop = LoopWrapper.from_blocks_dict({"block1": LoopBlock})
87
+ ```
88
+
89
+ 添加更多的循环块以在每次迭代中运行,使用[`~modular_pipelines.LoopSequentialPipelineBlocks.from_blocks_dict`]。这允许您在不改变循环逻辑本身的情况下修改块。
90
+
91
+ ```py
92
+ loop = LoopWrapper.from_blocks_dict({"block1": LoopBlock(), "block2": LoopBlock})
93
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/modular_diffusers_states.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据Apache许可证2.0版("许可证")授权;除非符合许可证的规定,否则不得使用此文件。
4
+ 您可以在以下网址获取许可证的副本
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ 除非适用法律要求或书面同意,根据许可证分发的软件是基于"按原样"分发的,没有任何形式的明示或暗示的担保或条件。有关许可证下特定的语言管理权限和限制,请参阅许可证。
9
+ -->
10
+
11
+ # 状态
12
+
13
+ 块依赖于[`~modular_pipelines.PipelineState`]和[`~modular_pipelines.BlockState`]数据结构进行通信和数据共享。
14
+
15
+ | 状态 | 描述 |
16
+ |-------|-------------|
17
+ | [`~modular_pipelines.PipelineState`] | 维护管道执行所需的整体数据,并允许块读取和更新其数据。 |
18
+ | [`~modular_pipelines.BlockState`] | 允许每个块使用来自`inputs`的必要数据执行其计算 |
19
+
20
+ 本指南解释了状态如何工作以及它们如何连接块。
21
+
22
+ ## PipelineState
23
+
24
+ [`~modular_pipelines.PipelineState`]是所有块的全局状态容器。它维护管道的完整运行时状态,并为块提供了一种结构化的方式来读取和写入共享数据。
25
+
26
+ [`~modular_pipelines.PipelineState`]中有两个字典用于结构化数据。
27
+
28
+ - `values`字典是一个**可变**状态,包含用户提供的输入值的副本和由块生成的中间输出值。如果一个块修改了一个`input`,它将在调用`set_block_state`后反映在`values`字典中。
29
+
30
+ ```py
31
+ PipelineState(
32
+ values={
33
+ 'prompt': 'a cat'
34
+ 'guidance_scale': 7.0
35
+ 'num_inference_steps': 25
36
+ 'prompt_embeds': Tensor(dtype=torch.float32, shape=torch.Size([1, 1, 1, 1]))
37
+ 'negative_prompt_embeds': None
38
+ },
39
+ )
40
+ ```
41
+
42
+ ## BlockState
43
+
44
+ [`~modular_pipelines.BlockState`]是[`~modular_pipelines.PipelineState`]中相关变量的局部视图,单个块需要这些变量来执行其计算。
45
+
46
+ 直接作为属性访问这些变量,如`block_state.image`。
47
+
48
+ ```py
49
+ BlockState(
50
+ image: <PIL.Image.Image image mode=RGB size=512x512 at 0x7F3ECC494640>
51
+ )
52
+ ```
53
+
54
+ 当一个块的`__call__`方法被执行时,它用`self.get_block_state(state)`检索[`BlockState`],执行其操作,并用`self.set_block_state(state, block_state)`更新[`~modular_pipelines.PipelineState`]。
55
+
56
+ ```py
57
+ def __call__(self, components, state):
58
+ # 检索BlockState
59
+ block_state = self.get_block_state(state)
60
+
61
+ # 对输入进行计算的逻辑
62
+
63
+ # 更新PipelineState
64
+ self.set_block_state(state, block_state)
65
+ return components, state
66
+ ```
67
+
68
+ ## 状态交互
69
+
70
+ [`~modular_pipelines.PipelineState`]和[`~modular_pipelines.BlockState`]的交互由块的`inputs`和`intermediate_outputs`定义。
71
+
72
+ - `inputs`,
73
+ 一个块可以修改输入 - 比如 `block_state.image` - 并且这个改变可以通过调用 `set_block_state` 全局传播到 [`~modular_pipelines.PipelineState`]。
74
+ - `intermediate_outputs`,是一个块创建的新变量。它被添加到 [`~modular_pipelines.PipelineState`] 的 `values` 字典中,并且可以作为后续块的可用变量,或者由用户作为管道的最终输出访问。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/modular_pipeline.md ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权 2025 HuggingFace 团队。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版(“许可证”)授权;除非符合许可证的规定,否则不得使用此文件。您可以在
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 获取许可证的副本。
8
+
9
+ 除非适用法律要求或书面同意,根据许可证分发的软件是基于“按原样”分发的,没有任何形式的明示或暗示的保证或条件。有关许可证的特定语言,请参阅许可证。
10
+ -->
11
+
12
+ # 模块化管道
13
+
14
+ [`ModularPipeline`] 将 [`~modular_pipelines.ModularPipelineBlocks`] 转换为可执行的管道,加载模型并执行块中定义的计算步骤。它是运行管道的主要接口,与 [`DiffusionPipeline`] API 非常相似。
15
+
16
+ 主要区别在于在管道中包含了一个预期的 `output` 参数。
17
+
18
+ <hfoptions id="example">
19
+ <hfoption id="text-to-image">
20
+
21
+ ```py
22
+ import torch
23
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
24
+ from diffusers.modular_pipelines.stable_diffusion_xl import TEXT2IMAGE_BLOCKS
25
+
26
+ blocks = SequentialPipelineBlocks.from_blocks_dict(TEXT2IMAGE_BLOCKS)
27
+
28
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
29
+ pipeline = blocks.init_pipeline(modular_repo_id)
30
+
31
+ pipeline.load_components(torch_dtype=torch.float16)
32
+ pipeline.to("cuda")
33
+
34
+ image = pipeline(prompt="Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", output="images")[0]
35
+ image.save("modular_t2i_out.png")
36
+ ```
37
+
38
+ </hfoption>
39
+ <hfoption id="image-to-image">
40
+
41
+ ```py
42
+ import torch
43
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
44
+ from diffusers.modular_pipelines.stable_diffusion_xl import IMAGE2IMAGE_BLOCKS
45
+
46
+ blocks = SequentialPipelineBlocks.from_blocks_dict(IMAGE2IMAGE_BLOCKS)
47
+
48
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
49
+ pipeline = blocks.init_pipeline(modular_repo_id)
50
+
51
+ pipeline.load_components(torch_dtype=torch.float16)
52
+ pipeline.to("cuda")
53
+
54
+ url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png"
55
+ init_image = load_image(url)
56
+ prompt = "a dog catching a frisbee in the jungle"
57
+ image = pipeline(prompt=prompt, image=init_image, strength=0.8, output="images")[0]
58
+ image.save("modular_i2i_out.png")
59
+ ```
60
+
61
+ </hfoption>
62
+ <hfoption id="inpainting">
63
+
64
+ ```py
65
+ import torch
66
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
67
+ from diffusers.modular_pipelines.stable_diffusion_xl import INPAINT_BLOCKS
68
+ from diffusers.utils import load_image
69
+
70
+ blocks = SequentialPipelineBlocks.from_blocks_dict(INPAINT_BLOCKS)
71
+
72
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
73
+ pipeline = blocks.init_pipeline(modular_repo_id)
74
+
75
+ pipeline.load_components(torch_dtype=torch.float16)
76
+ pipeline.to("cuda")
77
+
78
+ img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png"
79
+ mask_url = "h
80
+ ttps://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-inpaint-mask.png"
81
+
82
+ init_image = load_image(img_url)
83
+ mask_image = load_image(mask_url)
84
+
85
+ prompt = "A deep sea diver floating"
86
+ image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, strength=0.85, output="images")[0]
87
+ image.save("moduar_inpaint_out.png")
88
+ ```
89
+
90
+ </hfoption>
91
+ </hfoptions>
92
+
93
+ 本指南将向您展示如何创建一个[`ModularPipeline`]并管理其中的组件。
94
+
95
+ ## 添加块
96
+
97
+ 块是[`InsertableDict`]对象,可以在特定位置插入,提供了一种灵活的方式来混合和匹配块。
98
+
99
+ 使用[`~modular_pipelines.modular_pipeline_utils.InsertableDict.insert`]在块类或`sub_blocks`属性上添加一个块。
100
+
101
+ ```py
102
+ # BLOCKS是块类的字典,您需要向其中添加类
103
+ BLOCKS.insert("block_name", BlockClass, index)
104
+ # sub_blocks属性包含实例,向该属性添加一个块实例
105
+ t2i_blocks.sub_blocks.insert("block_name", block_instance, index)
106
+ ```
107
+
108
+ 使用[`~modular_pipelines.modular_pipeline_utils.InsertableDict.pop`]在块类或`sub_blocks`属性上移除一个块。
109
+
110
+ ```py
111
+ # 从预设中移除一个块类
112
+ BLOCKS.pop("text_encoder")
113
+ # 分离出一个块实例
114
+ text_encoder_block = t2i_blocks.sub_blocks.pop("text_encoder")
115
+ ```
116
+
117
+ 通过将现有块设置为新块来交换块。
118
+
119
+ ```py
120
+ # 在预设中替换块类
121
+ BLOCKS["prepare_latents"] = CustomPrepareLatents
122
+ # 使用块实例在sub_blocks属性中替换
123
+ t2i_blocks.sub_blocks["prepare_latents"] = CustomPrepareLatents()
124
+ ```
125
+
126
+ ## 创建管道
127
+
128
+ 有两种方法可以创建一个[`ModularPipeline`]。从[`ModularPipelineBlocks`]组装并创建管道,或使用[`~ModularPipeline.from_pretrained`]加载现有管道。
129
+
130
+ 您还应该初始化一个[`ComponentsManager`]来处理设备放置和内存以及组件管理。
131
+
132
+ > [!TIP]
133
+ > 有关它如何帮助管理不同工作流中的组件的更多详细信息,请参阅[ComponentsManager](./components_manager)文档。
134
+
135
+ <hfoptions id="create">
136
+ <hfoption id="ModularPipelineBlocks">
137
+
138
+ 使用[`~ModularPipelineBlocks.init_pipeline`]方法从组件和配置规范创建一个[`ModularPipeline`]。此方法从`modular_model_index.json`文件加载*规范*,但尚未加载*模型*。
139
+
140
+ ```py
141
+ from diffusers import ComponentsManager
142
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
143
+ from diffusers.modular_pipelines.stable_diffusion_xl import TEXT2IMAGE_BLOCKS
144
+
145
+ t2i_blocks = SequentialPipelineBlocks.from_blocks_dict(TEXT2IMAGE_BLOCKS)
146
+
147
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
148
+ components = ComponentsManager()
149
+ t2i_pipeline = t2i_blocks.init_pipeline(modular_repo_id, components_manager=components)
150
+ ```
151
+
152
+ </hfoption>
153
+ <hfoption id="from_pretrained">
154
+
155
+ [`~ModularPipeline.from_pretrained`]方法创建一个[`ModularPipeline`]从Hub上的模块化仓库加载。
156
+
157
+ ```py
158
+ from diffusers import ModularPipeline, ComponentsManager
159
+
160
+ components = ComponentsManager()
161
+ pipeline = ModularPipeline.from_pretrained("YiYiXu/modular-loader-t2i-0704", components_manager=components)
162
+ ```
163
+
164
+ 添加`trust_remote_code`参数以加载自定义的[`ModularPipeline`]。
165
+
166
+ ```py
167
+ from diffusers import ModularPipeline, ComponentsManager
168
+
169
+ components = ComponentsManager()
170
+ modular_repo_id = "YiYiXu/modular-diffdiff-0704"
171
+ diffdiff_pipeline = ModularPipeline.from_pretrained(modular_repo_id, trust_remote_code=True, components_manager=components)
172
+ ```
173
+
174
+ </hfoption>
175
+ </hfoptions>
176
+
177
+ ## 加载组件
178
+
179
+ 一个[`ModularPipeline`]不会自动实例化组件。它只加载配置和组件规范。您可以使用[`~ModularPipeline.load_components`]加载所有组件,或仅使用[`~ModularPipeline.load_components`]加载特定组件。
180
+
181
+ <hfoptions id="load">
182
+ <hfoption id="load_components">
183
+
184
+ ```py
185
+ import torch
186
+
187
+ t2i_pipeline.load_components(torch_dtype=torch.float16)
188
+ t2i_pipeline.to("cuda")
189
+ ```
190
+
191
+ </hfoption>
192
+ <hfoption id="load_components">
193
+
194
+ 下面的例子仅加载UNet和VAE。
195
+
196
+ ```py
197
+ import torch
198
+
199
+ t2i_pipeline.load_components(names=["unet", "vae"], torch_dtype=torch.float16)
200
+ ```
201
+
202
+ </hfoption>
203
+ </hfoptions>
204
+
205
+ 打印管道以检查加载的预训练组件。
206
+
207
+ ```py
208
+ t2i_pipeline
209
+ ```
210
+
211
+ 这应该与管道初始化自的模块化仓库中的`modular_model_index.json`文件匹配。如果管道不需要某个组件,即使它在模块化仓库中存在,也不会被包含。
212
+
213
+ 要修改组件加载的来源,编辑仓库中的`modular_model_index.json`文件,并将其更改为您希望的加载路径。下面的例子从不同的仓库加载UNet。
214
+
215
+ ```json
216
+ # 原始
217
+ "unet": [
218
+ null, null,
219
+ {
220
+ "repo": "stabilityai/stable-diffusion-xl-base-1.0",
221
+ "subfolder": "unet",
222
+ "variant": "fp16"
223
+ }
224
+ ]
225
+
226
+ # 修改后
227
+ "unet": [
228
+ null, null,
229
+ {
230
+ "repo": "RunDiffusion/Juggernaut-XL-v9",
231
+ "subfolder": "unet",
232
+ "variant": "fp16"
233
+ }
234
+ ]
235
+ ```
236
+
237
+ ### 组件加载状态
238
+
239
+ 下面的管道属性提供了关于哪些组件被加载的更多信息。
240
+
241
+ 使用`component_names`返回所有预期的组件。
242
+
243
+ ```py
244
+ t2i_pipeline.component_names
245
+ ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'guider', 'scheduler', 'unet', 'vae', 'image_processor']
246
+ ```
247
+
248
+ 使用`null_component_names`返回尚未加载的组件。使用[`~ModularPipeline.from_pretrained`]加载这些组件。
249
+
250
+ ```py
251
+ t2i_pipeline.null_component_names
252
+ ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'scheduler']
253
+ ```
254
+
255
+ 使用`pretrained_component_names`返回将从预训练模型加载的组件。
256
+
257
+ ```py
258
+ t2i_pipeline.pretrained_component_names
259
+ ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'scheduler', 'unet', 'vae']
260
+ ```
261
+
262
+ 使用 `config_component_names` 返回那些使用默认配置创建的组件(不是从模块化仓库加载的)。来自配置的组件不包括在内,因为它们已经在管道创建期间初始化。这就是为什么它们没有列在 `null_component_names` 中。
263
+
264
+ ```py
265
+ t2i_pipeline.config_component_names
266
+ ['guider', 'image_processor']
267
+ ```
268
+
269
+ ## 更新组件
270
+
271
+ 根据组件是*预训练组件*还是*配置组件*,组件可能会被更新。
272
+
273
+ > [!WARNING]
274
+ > 在更新组件时,组件可能会从预训练变为配置。组件类型最初是在块的 `expected_components` 字段中定义的。
275
+
276
+ 预训练组件通过 [`ComponentSpec`] 更新,而配置组件则通过直接传递对象或使用 [`ComponentSpec`] 更新。
277
+
278
+ [`ComponentSpec`] 对于预训练组件显示 `default_creation_method="from_pretrained"`,对于配置组件显示 `default_creation_method="from_config`。
279
+
280
+ 要更新预训练组件,创建一个 [`ComponentSpec`],指定组件的名称和从哪里加载它。使用 [`~ComponentSpec.load`] 方法来加载组件。
281
+
282
+ ```py
283
+ from diffusers import ComponentSpec, UNet2DConditionModel
284
+
285
+ unet_spec = ComponentSpec(name="unet",type_hint=UNet2DConditionModel, repo="stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", variant="fp16")
286
+ unet = unet_spec.load(torch_dtype=torch.float16)
287
+ ```
288
+
289
+ [`~ModularPipeline.update_components`] 方法用一个新的组件替换原来的组件。
290
+
291
+ ```py
292
+ t2i_pipeline.update_components(unet=unet2)
293
+ ```
294
+
295
+ 当组件被更新时,加载规范也会在管道配置���更新。
296
+
297
+ ### 组件提取和修改
298
+
299
+ 当你使用 [`~ComponentSpec.load`] 时,新组件保持其加载规范。这使得提取规范并重新创建组件成为可能。
300
+
301
+ ```py
302
+ spec = ComponentSpec.from_component("unet", unet2)
303
+ spec
304
+ ComponentSpec(name='unet', type_hint=<class 'diffusers.models.unets.unet_2d_condition.UNet2DConditionModel'>, description=None, config=None, repo='stabilityai/stable-diffusion-xl-base-1.0', subfolder='unet', variant='fp16', revision=None, default_creation_method='from_pretrained')
305
+ unet2_recreated = spec.load(torch_dtype=torch.float16)
306
+ ```
307
+
308
+ [`~ModularPipeline.get_component_spec`] 方法获取当前组件规范的副本以进行修改或更新。
309
+
310
+ ```py
311
+ unet_spec = t2i_pipeline.get_component_spec("unet")
312
+ unet_spec
313
+ ComponentSpec(
314
+ name='unet',
315
+ type_hint=<class 'diffusers.models.unets.unet_2d_condition.UNet2DConditionModel'>,
316
+ pretrained_model_name_or_path='RunDiffusion/Juggernaut-XL-v9',
317
+ subfolder='unet',
318
+ variant='fp16',
319
+ default_creation_method='from_pretrained'
320
+ )
321
+
322
+ # 修改以从不同的仓库加载
323
+ unet_spec.pretrained_model_name_or_path = "stabilityai/stable-diffusion-xl-base-1.0"
324
+
325
+ # 使用修改后的规范加载组件
326
+ unet = unet_spec.load(torch_dtype=torch.float16)
327
+ ```
328
+
329
+ ## 模块化仓库
330
+ 一个仓库
331
+ 如果管道块使用*预训练组件*,则需要y。该存储库提供了加载规范和元数据。
332
+
333
+ [`ModularPipeline`]特别需要*模块化存储库*(参见[示例存储库](https://huggingface.co/YiYiXu/modular-diffdiff)),这比典型的存储库更灵活。它包含一个`modular_model_index.json`文件,包含以下3个元素。
334
+
335
+ - `library`和`class`显示组件是从哪个库加载的及其类。如果是`null`,则表示组件尚未加载。
336
+ - `loading_specs_dict`包含加载组件所需的信息,例如从中加载的存储库和子文件夹。
337
+
338
+ 与标准存储库不同,模块化存储库可以根据`loading_specs_dict`从不同的存储库获取组件。组件不需要存在于同一个存储库中。
339
+
340
+ 模块化存储库可能包含用于加载[`ModularPipeline`]的自定义代码。这允许您使用不是Diffusers原生的专用块。
341
+
342
+ ```
343
+ modular-diffdiff-0704/
344
+ ├── block.py # 自定义管道块实现
345
+ ├── config.json # 管道配置和auto_map
346
+ └── modular_model_index.json # 组件加载规范
347
+ ```
348
+
349
+ [config.json](https://huggingface.co/YiYiXu/modular-diffdiff-0704/blob/main/config.json)文件包含一个`auto_map`键,指向`block.py`中定义自定义块的位置。
350
+
351
+ ```json
352
+ {
353
+ "_class_name": "DiffDiffBlocks",
354
+ "auto_map": {
355
+ "ModularPipelineBlocks": "block.DiffDiffBlocks"
356
+ }
357
+ }
358
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/overview.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据Apache许可证2.0版("许可证")授权;除非符合许可证,否则不得使用此文件。您可以在以下位置获取许可证的副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。有关许可证下特定语言的权限和限制,请参阅许可证。
8
+ -->
9
+
10
+ # 概述
11
+
12
+ > [!WARNING]
13
+ > 模块化Diffusers正在积极开发中,其API可能会发生变化。
14
+
15
+ 模块化Diffusers是一个统一的管道系统,通过*管道块*简化您的工作流程。
16
+
17
+ - 块是可重用的,您只需要为您的管道创建独特的块。
18
+ - 块可以混合搭配,以适应或为特定工作流程或多个工作流程创建管道。
19
+
20
+ 模块化Diffusers文档的组织如下所示。
21
+
22
+ ## 快速开始
23
+
24
+ - 一个[快速开始](./quickstart)演示了如何使用模块化Diffusers实现一个示例工作流程。
25
+
26
+ ## ModularPipelineBlocks
27
+
28
+ - [States](./modular_diffusers_states)解释了数据如何在块和[`ModularPipeline`]之间共享和通信。
29
+ - [ModularPipelineBlocks](./pipeline_block)是[`ModularPipeline`]最基本的单位,本指南向您展示如何创建一个。
30
+ - [SequentialPipelineBlocks](./sequential_pipeline_blocks)是一种类型的块,它将多个块链接起来,使它们一个接一个地运行,沿着链传递数据。本指南向您展示如何创建[`~modular_pipelines.SequentialPipelineBlocks`]以及它们如何连接和一起工作。
31
+ - [LoopSequentialPipelineBlocks](./loop_sequential_pipeline_blocks)是一种类型的块,它在循环中运行一系列块。本指南向您展示如何创建[`~modular_pipelines.LoopSequentialPipelineBlocks`]。
32
+ - [AutoPipelineBlocks](./auto_pipeline_blocks)是一种类型的块,它根据输入自动选择要运行的块。本指南向您展示如何创建[`~modular_pipelines.AutoPipelineBlocks`]。
33
+
34
+ ## ModularPipeline
35
+
36
+ - [ModularPipeline](./modular_pipeline)向您展示如何创建并将管道块转换为可执行的[`ModularPipeline`]。
37
+ - [ComponentsManager](./components_manager)向您展示如何跨多个管道管理和重用组件。
38
+ - [Guiders](./guiders)向您展示如何在管道中使用不同的指导方法。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/pipeline_block.md ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据Apache许可证2.0版(“许可证”)授权;除非符合许可证,否则不得使用此文件。您可以在
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 获取许可证的副本。
8
+
9
+ 除非适用法律要求或书面同意,根据许可证分发的软件是基于“按原样”基础分发的,没有任何明示或暗示的保证或条件。请参阅许可证了解特定语言管理权限和限制。
10
+ -->
11
+
12
+ # ModularPipelineBlocks
13
+
14
+ [`~modular_pipelines.ModularPipelineBlocks`] 是构建 [`ModularPipeline`] 的基本块。它定义了管道中特定步骤应执行的组件、输入/输出和计算。一个 [`~modular_pipelines.ModularPipelineBlocks`] 与其他块连接,使用 [状态](./modular_diffusers_states),以实现工作流的模块化构建。
15
+
16
+ 单独的 [`~modular_pipelines.ModularPipelineBlocks`] 无法执行。它是管道中步骤应执行的操作的蓝图。要实际运行和执行管道,需要将 [`~modular_pipelines.ModularPipelineBlocks`] 转换为 [`ModularPipeline`]。
17
+
18
+ 本指南将向您展示如何创建 [`~modular_pipelines.ModularPipelineBlocks`]。
19
+
20
+ ## 输入和输出
21
+
22
+ > [!TIP]
23
+ > 如果您不熟悉Modular Diffusers中状态的工作原理,请参考 [States](./modular_diffusers_states) 指南。
24
+
25
+ 一个 [`~modular_pipelines.ModularPipelineBlocks`] 需要 `inputs` 和 `intermediate_outputs`。
26
+
27
+ - `inputs` 是由用户提供并从 [`~modular_pipelines.PipelineState`] 中检索的值。这很有用,因为某些工作流会调整图像大小,但仍需要原始图像。 [`~modular_pipelines.PipelineState`] 维护原始图像。
28
+
29
+ 使用 `InputParam` 定义 `inputs`。
30
+
31
+ ```py
32
+ from diffusers.modular_pipelines import InputParam
33
+
34
+ user_inputs = [
35
+ InputParam(name="image", type_hint="PIL.Image", description="要处理的原始输入图像")
36
+ ]
37
+ ```
38
+
39
+ - `intermediate_inputs` 通常由前一个块创建的值,但如果前面的块没有生成它们,也可以直接提供。与 `inputs` 不同,`intermediate_inputs` 可以被修改。
40
+
41
+ 使用 `InputParam` 定义 `intermediate_inputs`。
42
+
43
+ ```py
44
+ user_intermediate_inputs = [
45
+ InputParam(name="processed_image", type_hint="torch.Tensor", description="image that has been preprocessed and normalized"),
46
+ ]
47
+ ```
48
+
49
+ - `intermediate_outputs` 是由块创建并添加到 [`~modular_pipelines.PipelineState`] 的新值。`intermediate_outputs` 可作为后续块的 `intermediate_inputs` 使用,或作为运行管道的最终输出使用。
50
+
51
+ 使用 `OutputParam` 定义 `intermediate_outputs`。
52
+
53
+ ```py
54
+ from diffusers.modular_pipelines import OutputParam
55
+
56
+ user_intermediate_outputs = [
57
+ OutputParam(name="image_latents", description="latents representing the image")
58
+ ]
59
+ ```
60
+
61
+ 中间输入和输出共享数据以连接块。它们可以在任何时候访问,允许你跟踪工作流的进度。
62
+
63
+ ## 计算逻辑
64
+
65
+ 一个块执行的计算在`__call__`方法中定义,它遵循特定的结构。
66
+
67
+ 1. 检索[`~modular_pipelines.BlockState`]以获取`inputs`和`intermediate_inputs`的局部视图。
68
+ 2. 在`inputs`和`intermediate_inputs`上实现计算逻辑。
69
+ 3. 更新[`~modular_pipelines.PipelineState`]以将局部[`~modular_pipelines.BlockState`]的更改推送回全局[`~modular_pipelines.PipelineState`]。
70
+ 4. 返回对下一个块可用的组件和状态。
71
+
72
+ ```py
73
+ def __call__(self, components, state):
74
+ # 获取该块需要的状态变量的局部视图
75
+ block_state = self.get_block_state(state)
76
+
77
+ # 你的计算逻辑在这里
78
+ # block_state包含你所有的inputs和intermediate_inputs
79
+ # 像这样访问它们: block_state.image, block_state.processed_image
80
+
81
+ # 用你更新的block_states更新管道状态
82
+ self.set_block_state(state, block_state)
83
+ return components, state
84
+ ```
85
+
86
+ ### 组件和配置
87
+
88
+ 块需要的组件和管道级别的配置在[`ComponentSpec`]和[`~modular_pipelines.ConfigSpec`]中指定。
89
+
90
+ - [`ComponentSpec`]包含块使用的预期组件。你需要组件的`name`和理想情况下指定组件确切是什么的`type_hint`。
91
+ - [`~modular_pipelines.ConfigSpec`]包含控制所有块行为的管道级别设置。
92
+
93
+ ```py
94
+ from diffusers import ComponentSpec, ConfigSpec
95
+
96
+ expected_components = [
97
+ ComponentSpec(name="unet", type_hint=UNet2DConditionModel),
98
+ ComponentSpec(name="scheduler", type_hint=EulerDiscreteScheduler)
99
+ ]
100
+
101
+ expected_config = [
102
+ ConfigSpec("force_zeros_for_empty_prompt", True)
103
+ ]
104
+ ```
105
+
106
+ 当块被转换为管道时,组件作为`__call__`中的第一个参数对块可用。
107
+
108
+ ```py
109
+ def __call__(self, components, state):
110
+ # 使用点符号访问组件
111
+ unet = components.unet
112
+ vae = components.vae
113
+ scheduler = components.scheduler
114
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/quickstart.md ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据Apache许可证2.0版("许可证")授权;除非符合许可证,否则不得使用此文件。您可以在
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 获取许可证的副本。
8
+
9
+ 除非适用法律要求或书面同意,根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。有关许可证下特定语言的管理权限和限制,请参阅许可证。
10
+ -->
11
+
12
+ # 快速入门
13
+
14
+ 模块化Diffusers是一个快速构建灵活和可定制管道的框架。模块化Diffusers的核心是[`ModularPipelineBlocks`],可以与其他块组合以适应新的工作流程。这些块被转换为[`ModularPipeline`],一个开发者可以使用的友好用户界面。
15
+
16
+ 本文档将向您展示如何使用模块化框架实现[Differential Diffusion](https://differential-diffusion.github.io/)管道。
17
+
18
+ ## ModularPipelineBlocks
19
+
20
+ [`ModularPipelineBlocks`]是*定义*,指定管道中单个步骤的组件、输入、输出和计算逻辑。有四种类型的块。
21
+
22
+ - [`ModularPipelineBlocks`]是最基本的单一步骤块。
23
+ - [`SequentialPipelineBlocks`]是一个多块,线性组合其他块。一个块的输出是下一个块的输入。
24
+ - [`LoopSequentialPipelineBlocks`]是一个多块,迭代运行,专为迭代工作流程设计。
25
+ - [`AutoPipelineBlocks`]是一个针对不同工作流程的块集合,它根据输入选择运行哪个块。它旨在方便地将多个工作流程打包到单个管道中。
26
+
27
+ [Differential Diffusion](https://differential-diffusion.github.io/)是一个图像到图像的工作流程。从`IMAGE2IMAGE_BLOCKS`预设开始,这是一个用于图像到图像生成的`ModularPipelineBlocks`集合。
28
+
29
+ ```py
30
+ from diffusers.modular_pipelines.stable_diffusion_xl import IMAGE2IMAGE_BLOCKS
31
+ IMAGE2IMAGE_BLOCKS = InsertableDict([
32
+ ("text_encoder", StableDiffusionXLTextEncoderStep),
33
+ ("image_encoder", StableDiffusionXLVaeEncoderStep),
34
+ ("input", StableDiffusionXLInputStep),
35
+ ("set_timesteps", StableDiffusionXLImg2ImgSetTimestepsStep),
36
+ ("prepare_latents", StableDiffusionXLImg2ImgPrepareLatentsStep),
37
+ ("prepare_add_cond", StableDiffusionXLImg2ImgPrepareAdditionalConditioningStep),
38
+ ("denoise", StableDiffusionXLDenoiseStep),
39
+ ("decode", StableDiffusionXLDecodeStep)
40
+ ])
41
+ ```
42
+
43
+ ## 管道和块状态
44
+
45
+ 模块化Diffusers使用*状态*在块之间通信数据。有两种类型的状态。
46
+
47
+ - [`PipelineState`]是一个全局状态,可用于跟踪所有块的所有输入和输出。
48
+ - [`BlockState`]是[`PipelineState`]中相关变量的局部视图,用于单个块。
49
+
50
+ ## 自定义块
51
+
52
+ [Differential Diffusion](https://differential-diffusion.github.io/) 与标准的图像到图像转换在其 `prepare_latents` 和 `denoise` 块上有所不同。所有其他块都可以重用,但你需要修改这两个。
53
+
54
+ 通过复制和修改现有的块,为 `prepare_latents` 和 `denoise` 创建占位符 `ModularPipelineBlocks`。
55
+
56
+ 打印 `denoise` 块,可以看到它由 [`LoopSequentialPipelineBlocks`] 组成,包含三个子块,`before_denoiser`、`denoiser` 和 `after_denoiser`。只需要修改 `before_denoiser` 子块,根据变化图为去噪器准备潜在输入。
57
+
58
+ ```py
59
+ denoise_blocks = IMAGE2IMAGE_BLOCKS["denoise"]()
60
+ print(denoise_blocks)
61
+ ```
62
+
63
+ 用新的 `SDXLDiffDiffLoopBeforeDenoiser` 块替换 `StableDiffusionXLLoopBeforeDenoiser` 子块。
64
+
65
+ ```py
66
+ # 复制现有块作为占位符
67
+ class SDXLDiffDiffPrepareLatentsStep(ModularPipelineBlocks):
68
+ """Copied from StableDiffusionXLImg2ImgPrepareLatentsStep - will modify later"""
69
+ # ... 与 StableDiffusionXLImg2ImgPrepareLatentsStep 相同的实现
70
+
71
+ class SDXLDiffDiffDenoiseStep(StableDiffusionXLDenoiseLoopWrapper):
72
+ block_classes = [SDXLDiffDiffLoopBeforeDenoiser, StableDiffusionXLLoopDenoiser, StableDiffusionXLLoopAfterDenoiser]
73
+ block_names = ["before_denoiser", "denoiser", "after_denoiser"]
74
+ ```
75
+
76
+ ### prepare_latents
77
+
78
+ `prepare_latents` 块需要进行以下更改。
79
+
80
+ - 一个处理器来处理变化图
81
+ - 一个新的 `inputs` 来接受用户提供的变化图,`timestep` 用于预计算所有潜在变量和 `num_inference_steps` 来创建更新图像区域的掩码
82
+ - 更新 `__call__` 方法中的计算,用于处理变化图和创建掩码,并将其存储在 [`BlockState`] 中
83
+
84
+ ```diff
85
+ class SDXLDiffDiffPrepareLatentsStep(ModularPipelineBlocks):
86
+ @property
87
+ def expected_components(self) -> List[ComponentSpec]:
88
+ return [
89
+ ComponentSpec("vae", AutoencoderKL),
90
+ ComponentSpec("scheduler", EulerDiscreteScheduler),
91
+ + ComponentSpec("mask_processor", VaeImageProcessor, config=FrozenDict({"do_normalize": False, "do_convert_grayscale": True}))
92
+ ]
93
+ @property
94
+ def inputs(self) -> List[Tuple[str, Any]]:
95
+ return [
96
+ InputParam("generator"),
97
+ + InputParam("diffdiff_map", required=True),
98
+ - InputParam("latent_timestep", required=True, type_hint=torch.Tensor),
99
+ + InputParam("timesteps", type_hint=torch.Tensor),
100
+ + InputParam("num_inference_steps", type_hint=int),
101
+ ]
102
+
103
+ @property
104
+ def intermediate_outputs(self) -> List[OutputParam]:
105
+ return [
106
+ + OutputParam("original_latents", type_hint=torch.Tensor),
107
+ + OutputParam("diffdiff_masks", type_hint=torch.Tensor),
108
+ ]
109
+ def __call__(self, components, state: PipelineState):
110
+ # ... existing logic ...
111
+ + # Process change map and create masks
112
+ + diffdiff_map = components.mask_processor.preprocess(block_state.diffdiff_map, height=latent_height, width=latent_width)
113
+ + thresholds = torch.arange(block_state.num_inference_steps, dtype=diffdiff_map.dtype) / block_state.num_inference_steps
114
+ + block_state.diffdiff_masks = diffdiff_map > (thresholds + (block_state.denoising_start or 0))
115
+ + block_state.original_latents = block_state.latents
116
+ ```
117
+
118
+ ### 去噪
119
+
120
+ `before_denoiser` 子块需要进行以下更改。
121
+
122
+ - 新的 `inputs` 以接受 `denoising_start` 参数,`original_latents` 和 `diffdiff_masks` 来自 `prepare_latents` 块
123
+ - 更新 `__call__` 方法中的计算以应用 Differential Diffusion
124
+
125
+ ```diff
126
+ class SDXLDiffDiffLoopBeforeDenoiser(ModularPipelineBlocks):
127
+ @property
128
+ def description(self) -> str:
129
+ return (
130
+ "Step within the denoising loop for differential diffusion that prepare the latent input for the denoiser"
131
+ )
132
+
133
+ @property
134
+ def inputs(self) -> List[str]:
135
+ return [
136
+ InputParam("latents", required=True, type_hint=torch.Tensor),
137
+ + InputParam("denoising_start"),
138
+ + InputParam("original_latents", type_hint=torch.Tensor),
139
+ + InputParam("diffdiff_masks", type_hint=torch.Tensor),
140
+ ]
141
+
142
+ def __call__(self, components, block_state, i, t):
143
+ + # Apply differential diffusion logic
144
+ + if i == 0 and block_state.denoising_start is None:
145
+ + block_state.latents = block_state.original_latents[:1]
146
+ + else:
147
+ + block_state.mask = block_state.diffdiff_masks[i].unsqueeze(0).unsqueeze(1)
148
+ + block_state.latents = block_state.original_latents[i] * block_state.mask + block_state.latents * (1 - block_state.mask)
149
+
150
+ # ... rest of existing logic ...
151
+ ```
152
+
153
+ ## 组装块
154
+
155
+ 此时,您应该拥有创建 [`ModularPipeline`] 所需的所有块。
156
+
157
+ 复制现有的 `IMAGE2IMAGE_BLOCKS` 预设,对于 `set_timesteps` 块,使用 `TEXT2IMAGE_BLOCKS` 中的 `set_timesteps`,因为 Differential Diffusion 不需要 `strength` 参数。
158
+
159
+ 将 `prepare_latents` 和 `denoise` 块设置为您刚刚修改的 `SDXLDiffDiffPrepareLatentsStep` 和 `SDXLDiffDiffDenoiseStep` 块。
160
+
161
+ 调用 [`SequentialPipelineBlocks.from_blocks_dict`] 在块上创建一个 `SequentialPipelineBlocks`。
162
+
163
+ ```py
164
+ DIFFDIFF_BLOCKS = IMAGE2IMAGE_BLOCKS.copy()
165
+ DIFFDIFF_BLOCKS["set_timesteps"] = TEXT2IMAGE_BLOCKS["set_timesteps"]
166
+ DIFFDIFF_BLOCKS["prepare_latents"] = SDXLDiffDiffPrepareLatentsStep
167
+ DIFFDIFF_BLOCKS["denoise"] = SDXLDiffDiffDenoiseStep
168
+
169
+ dd_blocks = SequentialPipelineBlocks.from_blocks_dict(DIFFDIFF_BLOCKS)
170
+ print(dd_blocks)
171
+ ```
172
+
173
+ ## ModularPipeline
174
+
175
+ 将 [`SequentialPipelineBlocks`] 转换为 [`ModularPipeline`],使用 [`ModularPipeline.init_pipeline`] 方法。这会初始化从 `modular_model_index.json` 文件加载的预期组件。通过调用 [`ModularPipeline.load_defau
176
+ lt_components`]。
177
+
178
+ 初始化[`ComponentManager`]时传入pipeline是一个好主意,以帮助管理不同的组件。一旦调用[`~ModularPipeline.load_components`],组件就会被注册到[`ComponentManager`]中,并且可以在工作流之间共享。下面的例子使用`collection`参数为组件分配了一个`"diffdiff"`标签,以便更好地组织。
179
+
180
+ ```py
181
+ from diffusers.modular_pipelines import ComponentsManager
182
+
183
+ components = ComponentManager()
184
+
185
+ dd_pipeline = dd_blocks.init_pipeline("YiYiXu/modular-demo-auto", components_manager=components, collection="diffdiff")
186
+ dd_pipeline.load_default_componenets(torch_dtype=torch.float16)
187
+ dd_pipeline.to("cuda")
188
+ ```
189
+
190
+ ## 添加工作流
191
+
192
+ 可以向[`ModularPipeline`]添加其他工作流以支持更多功能,而无需从头重写整个pipeline。
193
+
194
+ 本节演示如何添加IP-Adapter或ControlNet。
195
+
196
+ ### IP-Adapter
197
+
198
+ Stable Diffusion XL已经有一个预设的IP-Adapter块,你可以使用,并且不需要对现有的Differential Diffusion pipeline进行任何更改。
199
+
200
+ ```py
201
+ from diffusers.modular_pipelines.stable_diffusion_xl.encoders import StableDiffusionXLAutoIPAdapterStep
202
+
203
+ ip_adapter_block = StableDiffusionXLAutoIPAdapterStep()
204
+ ```
205
+
206
+ 使用[`sub_blocks.insert`]方法将其插入到[`ModularPipeline`]中。下面的例子在位置`0`插入了`ip_adapter_block`。打印pipeline可以看到`ip_adapter_block`被添加了,并且它需要一个`ip_adapter_image`。这也向pipeline添加了两个组件,`image_encoder`和`feature_extractor`。
207
+
208
+ ```py
209
+ dd_blocks.sub_blocks.insert("ip_adapter", ip_adapter_block, 0)
210
+ ```
211
+
212
+ 调用[`~ModularPipeline.init_pipeline`]来初始化一个[`ModularPipeline`],并使用[`~ModularPipeline.load_components`]加载模型组件。加载并设置IP-Adapter以运行pipeline。
213
+
214
+ ```py
215
+ dd_pipeline = dd_blocks.init_pipeline("YiYiXu/modular-demo-auto", collection="diffdiff")
216
+ dd_pipeline.load_components(torch_dtype=torch.float16)
217
+ dd_pipeline.loader.load_ip_adapter("h94/IP-Adapter", subfolder="sdxl_models", weight_name="ip-adapter_sdxl.bin")
218
+ dd_pipeline.loader.set_ip_adapter_scale(0.6)
219
+ dd_pipeline = dd_pipeline.to(device)
220
+
221
+ ip_adapter_image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/diffdiff_orange.jpeg")
222
+ image = load_image("https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/20240329211129_4024911930.png?download=true")
223
+ mask = load_image("https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/gradient_mask.png?download=true")
224
+
225
+ prompt = "a green pear"
226
+ negative_prompt = "blurry"
227
+ generator = torch.Generator(device=device).manual_seed(42)
228
+
229
+ image = dd_pipeline(
230
+ prompt=prompt,
231
+ negative_prompt=negative_prompt,
232
+ num_inference_steps=25,
233
+ generator=generator,
234
+ ip_adapter_image=ip_adapter_image,
235
+ diffdiff_map=mask,
236
+ image=image,
237
+
238
+ output="images"
239
+ )[0]
240
+ ```
241
+
242
+ ### ControlNet
243
+
244
+ Stable Diffusion XL 已经预设了一个可以立即使用的 ControlNet 块。
245
+
246
+ ```py
247
+ from diffusers.modular_pipelines.stable_diffusion_xl.modular_blocks import StableDiffusionXLAutoControlNetInputStep
248
+
249
+ control_input_block = StableDiffusionXLAutoControlNetInputStep()
250
+ ```
251
+
252
+ 然而,它需要修改 `denoise` 块,因为那是 ControlNet 将控制信息注入到 UNet 的地方。
253
+
254
+ 通过将 `StableDiffusionXLLoopDenoiser` 子块替换为 `StableDiffusionXLControlNetLoopDenoiser` 来修改 `denoise` 块。
255
+
256
+ ```py
257
+ class SDXLDiffDiffControlNetDenoiseStep(StableDiffusionXLDenoiseLoopWrapper):
258
+ block_classes = [SDXLDiffDiffLoopBeforeDenoiser, StableDiffusionXLControlNetLoopDenoiser, StableDiffusionXLDenoiseLoopAfterDenoiser]
259
+ block_names = ["before_denoiser", "denoiser", "after_denoiser"]
260
+
261
+ controlnet_denoise_block = SDXLDiffDiffControlNetDenoiseStep()
262
+ ```
263
+
264
+ 插入 `controlnet_input` 块并用新的 `controlnet_denoise_block` 替换 `denoise` 块。初始化一个 [`ModularPipeline`] 并将 [`~ModularPipeline.load_components`] 加载到其中。
265
+
266
+ ```py
267
+ dd_blocks.sub_blocks.insert("controlnet_input", control_input_block, 7)
268
+ dd_blocks.sub_blocks["denoise"] = controlnet_denoise_block
269
+
270
+ dd_pipeline = dd_blocks.init_pipeline("YiYiXu/modular-demo-auto", collection="diffdiff")
271
+ dd_pipeline.load_components(torch_dtype=torch.float16)
272
+ dd_pipeline = dd_pipeline.to(device)
273
+
274
+ control_image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/diffdiff_tomato_canny.jpeg")
275
+ image = load_image("https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/20240329211129_4024911930.png?download=true")
276
+ mask = load_image("https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/gradient_mask.png?download=true")
277
+
278
+ prompt = "a green pear"
279
+ negative_prompt = "blurry"
280
+ generator = torch.Generator(device=device).manual_seed(42)
281
+
282
+ image = dd_pipeline(
283
+ prompt=prompt,
284
+ negative_prompt=negative_prompt,
285
+ num_inference_steps=25,
286
+ generator=generator,
287
+ control_image=control_image,
288
+ controlnet_conditioning_scale=0.5,
289
+ diffdiff_map=mask,
290
+ image=image,
291
+ output="images"
292
+ )[0]
293
+ ```
294
+
295
+ ### AutoPipelineBlocks
296
+
297
+ 差分扩散、IP-Adapter 和 ControlNet 工作流可以通过使用 [`AutoPipelineBlocks`] 捆绑到一个单一的 [`ModularPipeline`] 中。这允许根据输入如 `control_image` 或 `ip_adapter_image` 自动选择要运行的子块。如果没有传递这些输入,则默认为差分扩散。
298
+
299
+ 使用 `block_trigger_inputs` 仅在提供 `control_image` 输入时运行 `SDXLDiffDiffControlNetDenoiseStep` 块。否则,使用 `SDXLDiffDiffDenoiseStep`。
300
+
301
+ ```py
302
+ class SDXLDiffDiffAutoDenoiseStep(AutoPipelineBlocks):
303
+ block_classes = [SDXLDiffDiffControlNetDenoiseStep, SDXLDiffDiffDenoiseStep]
304
+ block_names = ["contr
305
+ olnet_denoise", "denoise"]
306
+ block_trigger_inputs = ["controlnet_cond", None]
307
+ ```
308
+
309
+ 添加 `ip_adapter` 和 `controlnet_input` 块。
310
+
311
+ ```py
312
+ DIFFDIFF_AUTO_BLOCKS = IMAGE2IMAGE_BLOCKS.copy()
313
+ DIFFDIFF_AUTO_BLOCKS["prepare_latents"] = SDXLDiffDiffPrepareLatentsStep
314
+ DIFFDIFF_AUTO_BLOCKS["set_timesteps"] = TEXT2IMAGE_BLOCKS["set_timesteps"]
315
+ DIFFDIFF_AUTO_BLOCKS["denoise"] = SDXLDiffDiffAutoDenoiseStep
316
+ DIFFDIFF_AUTO_BLOCKS.insert("ip_adapter", StableDiffusionXLAutoIPAdapterStep, 0)
317
+ DIFFDIFF_AUTO_BLOCKS.insert("controlnet_input",StableDiffusionXLControlNetAutoInput, 7)
318
+ ```
319
+
320
+ 调用 [`SequentialPipelineBlocks.from_blocks_dict`] 来创建一个 [`SequentialPipelineBlocks`] 并创建一个 [`ModularPipeline`] 并加载模型组件以运行。
321
+
322
+ ```py
323
+ dd_auto_blocks = SequentialPipelineBlocks.from_blocks_dict(DIFFDIFF_AUTO_BLOCKS)
324
+ dd_pipeline = dd_auto_blocks.init_pipeline("YiYiXu/modular-demo-auto", collection="diffdiff")
325
+ dd_pipeline.load_components(torch_dtype=torch.float16)
326
+ ```
327
+
328
+ ## 分享
329
+
330
+ 使用 [`~ModularPipeline.save_pretrained`] 将您的 [`ModularPipeline`] 添加到 Hub,并将 `push_to_hub` 参数设置为 `True`。
331
+
332
+ ```py
333
+ dd_pipeline.save_pretrained("YiYiXu/test_modular_doc", push_to_hub=True)
334
+ ```
335
+
336
+ 其他用户可以使用 [`~ModularPipeline.from_pretrained`] 加载 [`ModularPipeline`]。
337
+
338
+ ```py
339
+ import torch
340
+ from diffusers.modular_pipelines import ModularPipeline, ComponentsManager
341
+
342
+ components = ComponentsManager()
343
+
344
+ diffdiff_pipeline = ModularPipeline.from_pretrained("YiYiXu/modular-diffdiff-0704", trust_remote_code=True, components_manager=components, collection="diffdiff")
345
+ diffdiff_pipeline.load_components(torch_dtype=torch.float16)
346
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/modular_diffusers/sequential_pipeline_blocks.md ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据Apache许可证2.0版("许可证")授权;除非符合许可证,否则不得使用此文件。您可以在
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 获取许可证的副本。
8
+
9
+ 除非适用法律要求或书面同意,根据许可证分发的软件是基于"按原样"基础分发的,没有任何形式的明示或暗示的保证或条件。有关许可证下特定语言的管理权限和限制,请参阅许可证。
10
+ -->
11
+
12
+ # 顺序管道块
13
+
14
+ [`~modular_pipelines.SequentialPipelineBlocks`] 是一种多块类型,它将其他 [`~modular_pipelines.ModularPipelineBlocks`] 按顺序组合在一起。数据通过 `intermediate_inputs` 和 `intermediate_outputs` 线性地从一个块流向下一个块。[`~modular_pipelines.SequentialPipelineBlocks`] 中的每个块通常代表管道中的一个步骤,通过组合它们,您逐步构建一个管道。
15
+
16
+ 本指南向您展示如何将两个块连接成一个 [`~modular_pipelines.SequentialPipelineBlocks`]。
17
+
18
+ 创建两个 [`~modular_pipelines.ModularPipelineBlocks`]。第一个块 `InputBlock` 输出一个 `batch_size` 值,第二个块 `ImageEncoderBlock` 使用 `batch_size` 作为 `intermediate_inputs`。
19
+
20
+ <hfoptions id="sequential">
21
+ <hfoption id="InputBlock">
22
+
23
+ ```py
24
+ from diffusers.modular_pipelines import ModularPipelineBlocks, InputParam, OutputParam
25
+
26
+ class InputBlock(ModularPipelineBlocks):
27
+
28
+ @property
29
+ def inputs(self):
30
+ return [
31
+ InputParam(name="prompt", type_hint=list, description="list of text prompts"),
32
+ InputParam(name="num_images_per_prompt", type_hint=int, description="number of images per prompt"),
33
+ ]
34
+
35
+ @property
36
+ def intermediate_outputs(self):
37
+ return [
38
+ OutputParam(name="batch_size", description="calculated batch size"),
39
+ ]
40
+
41
+ @property
42
+ def description(self):
43
+ return "A block that determines batch_size based on the number of prompts and num_images_per_prompt argument."
44
+
45
+ def __call__(self, components, state):
46
+ block_state = self.get_block_state(state)
47
+ batch_size = len(block_state.prompt)
48
+ block_state.batch_size = batch_size * block_state.num_images_per_prompt
49
+ self.set_block_state(state, block_state)
50
+ return components, state
51
+ ```
52
+
53
+ </hfoption>
54
+ <hfoption id="ImageEncoderBlock">
55
+
56
+ ```py
57
+ import torch
58
+ from diffusers.modular_pipelines import ModularPipelineBlocks, InputParam, OutputParam
59
+
60
+ class ImageEncoderBlock(ModularPipelineBlocks):
61
+
62
+ @property
63
+ def inputs(self):
64
+ return [
65
+ InputParam(name="image", type_hint="PIL.Image", description="raw input image to process"),
66
+ InputParam(name="batch_size", type_hint=int),
67
+ ]
68
+
69
+ @property
70
+ def intermediate_outputs(self):
71
+ return [
72
+ OutputParam(name="image_latents", description="latents representing the image"
73
+ ]
74
+
75
+ @property
76
+ def description(self):
77
+ return "Encode raw image into its latent presentation"
78
+
79
+ def __call__(self, components, state):
80
+ block_state = self.get_block_state(state)
81
+ # 模拟处理图像
82
+ # 这将改变所有块的图像状态,从PIL图像变为张量
83
+ block_state.image = torch.randn(1, 3, 512, 512)
84
+ block_state.batch_size = block_state.batch_size * 2
85
+ block_state.image_latents = torch.randn(1, 4, 64, 64)
86
+ self.set_block_state(state, block_state)
87
+ return components, state
88
+ ```
89
+
90
+ </hfoption>
91
+ </hfoptions>
92
+
93
+ 通过定义一个[`InsertableDict`]来连接两个块,将块名称映射到块实例。块按照它们在`blocks_dict`中注册的顺序执行。
94
+
95
+ 使用[`~modular_pipelines.SequentialPipelineBlocks.from_blocks_dict`]来创建一个[`~modular_pipelines.SequentialPipelineBlocks`]。
96
+
97
+ ```py
98
+ from diffusers.modular_pipelines import SequentialPipelineBlocks, InsertableDict
99
+
100
+ blocks_dict = InsertableDict()
101
+ blocks_dict["input"] = input_block
102
+ blocks_dict["image_encoder"] = image_encoder_block
103
+
104
+ blocks = SequentialPipelineBlocks.from_blocks_dict(blocks_dict)
105
+ ```
106
+
107
+ 通过调用`blocks`来检查[`~modular_pipelines.SequentialPipelineBlocks`]中的子块,要获取更多关于输入和输出的详细信息,可以访问`docs`属性。
108
+
109
+ ```py
110
+ print(blocks)
111
+ print(blocks.doc)
112
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/cache.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- 版权所有 2025 HuggingFace 团队。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版本(“许可证”)授权;除非符合许可证,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,否则根据许可证分发的软件按“原样”分发,不附带任何明示或暗示的担保或条件。请参阅许可证以了解具体的语言管理权限和限制。 -->
8
+
9
+ # 缓存
10
+
11
+ 缓存通过存储和重用不同层的中间输出(如注意力层和前馈层)来加速推理,而不是在每个推理步骤执行整个计算。它显著提高了生成速度,但以更多内存为代价,并且不需要额外的训练。
12
+
13
+ 本指南向您展示如何在 Diffusers 中使用支持的缓存方法。
14
+
15
+ ## 金字塔注意力广播
16
+
17
+ [金字塔注意力广播 (PAB)](https://huggingface.co/papers/2408.12588) 基于这样一种观察:在生成过程的连续时间步之间,注意力输出差异不大。注意力差异在交叉注意力层中最小,并且通常在一个较长的时间步范围内被缓存。其次是时间注意力和空间注意力层。
18
+
19
+ > [!TIP]
20
+ > 并非所有视频模型都有三种类型的注意力(交叉、时间和空间)!
21
+
22
+ PAB 可以与其他技术(如序列并行性和无分类器引导并行性(数据并行性))结合,实现近乎实时的视频生成。
23
+
24
+ 设置并传递一个 [`PyramidAttentionBroadcastConfig`] 到管道的变换器以启用它。`spatial_attention_block_skip_range` 控制跳过空间注意力块中注意力计算的频率,`spatial_attention_timestep_skip_range` 是要跳过的时间步范围。注意选择一个合适的范围,因为较小的间隔可能导致推理速度变慢,而较大的间隔可能导致生成质量降低。
25
+
26
+ ```python
27
+ import torch
28
+ from diffusers import CogVideoXPipeline, PyramidAttentionBroadcastConfig
29
+
30
+ pipeline = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16)
31
+ pipeline.to("cuda")
32
+
33
+ config = PyramidAttentionBroadcastConfig(
34
+ spatial_attention_block_skip_range=2,
35
+ spatial_attention_timestep_skip_range=(100, 800),
36
+ current_timestep_callback=lambda: pipe.current_timestep,
37
+ )
38
+ pipeline.transformer.enable_cache(config)
39
+ ```
40
+
41
+ ## FasterCache
42
+
43
+ [FasterCache](https://huggingface.co/papers/2410.19355) 缓存并重用注意力特征,类似于 [PAB](#pyramid-attention-broadcast),因为每个连续时间步的输出差异很小。
44
+
45
+ 此方法在使用无分类器引导进行采样时(在大多数基础模型中常见),也可能选择跳过无条件分支预测,并且
46
+ 如果连续时间步之间的预测潜在输出存在显著冗余,则从条件分支预测中估计它。
47
+
48
+ 设置并将 [`FasterCacheConfig`] 传递给管道的 transformer 以启用它。
49
+
50
+ ```python
51
+ import torch
52
+ from diffusers import CogVideoXPipeline, FasterCacheConfig
53
+
54
+ pipe line= CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16)
55
+ pipeline.to("cuda")
56
+
57
+ config = FasterCacheConfig(
58
+ spatial_attention_block_skip_range=2,
59
+ spatial_attention_timestep_skip_range=(-1, 681),
60
+ current_timestep_callback=lambda: pipe.current_timestep,
61
+ attention_weight_callback=lambda _: 0.3,
62
+ unconditional_batch_skip_range=5,
63
+ unconditional_batch_timestep_skip_range=(-1, 781),
64
+ tensor_format="BFCHW",
65
+ )
66
+ pipeline.transformer.enable_cache(config)
67
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/coreml.md ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版本("许可证")授权;除非符合许可证,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。有关许可证的具体语言,请参阅许可证中的权限和限制。
8
+ -->
9
+
10
+ # 如何使用 Core ML 运行 Stable Diffusion
11
+
12
+ [Core ML](https://developer.apple.com/documentation/coreml) 是 Apple 框架支持的模型格式和机器学习库。如果您有兴趣在 macOS 或 iOS/iPadOS 应用中运行 Stable Diffusion 模型,本指南将展示如何将现有的 PyTorch 检查点转换为 Core ML 格式,并使用 Python 或 Swift 进行推理。
13
+
14
+ Core ML 模型可以利用 Apple 设备中所有可用的计算引擎:CPU、GPU 和 Apple Neural Engine(或 ANE,一种在 Apple Silicon Mac 和现代 iPhone/iPad 中可用的张量优化加速器)。根据模型及其运行的设备,Core ML 还可以混合和匹配计算引擎,例如,模型的某些部分可能在 CPU 上运行,而其他部分在 GPU 上运行。
15
+
16
+ > [!TIP]
17
+ > 您还可以使用 PyTorch 内置的 `mps` 加速器在 Apple Silicon Mac 上运行 `diffusers` Python 代码库。这种方法在 [mps 指南](mps) 中有详细解释,但它与原生应用不兼容。
18
+
19
+ ## Stable Diffusion Core ML 检查点
20
+
21
+ Stable Diffusion 权重(或检查点)以 PyTorch 格式存储,因此在使用它们之前,需要将它们转换为 Core ML 格式。
22
+
23
+ 幸运的是,Apple 工程师基于 `diffusers` 开发了 [一个转换工具](https://github.com/apple/ml-stable-diffusion#-converting-models-to-core-ml),用于将 PyTorch 检查点转换为 Core ML。
24
+
25
+ 但在转换模型之前,花点时间探索 Hugging Face Hub——很可能您感兴趣的模型已经以 Core ML 格式提供:
26
+
27
+ - [Apple](https://huggingface.co/apple) 组织包括 Stable Diffusion 版本 1.4、1.5、2.0 基础和 2.1 基础
28
+ - [coreml community](https://huggingface.co/coreml-community) 包括自定义微调模型
29
+ - 使用此 [过滤器](https://huggingface.co/models?pipeline_tag=text-to-image&library=coreml&p=2&sort=likes) 返回所有可用的 Core ML 检查点
30
+
31
+ 如果您找不到感兴趣的模型,我们建议您遵循 Apple 的 [Converting Models to Core ML](https://github.com/apple/ml-stable-diffusion#-converting-models-to-core-ml) 说明。
32
+
33
+ ## 选择要使用的 Core ML 变体
34
+
35
+ Stable Diffusion 模型可以转换为不同的 Core ML 变体,用于不同目的:
36
+
37
+ - 注意力类型
38
+ 使用了n个块。注意力操作用于“关注”图像表示中不同区域之间的关系,并理解图像和文本表示如何相关。注意力的计算和内存消耗很大,因此存在不同的实现方式,以适应不同设备的硬件特性。对于Core ML Stable Diffusion模型,有两种注意力变体:
39
+ * `split_einsum`([由Apple引入](https://machinelearning.apple.com/research/neural-engine-transformers))针对ANE设备进行了优化,这些设备在现代iPhone、iPad和M系列计算机中可用。
40
+ * “原始”注意力(在`diffusers`中使用的基础实现)仅与CPU/GPU兼容,不与ANE兼容。在CPU + GPU上使用`original`注意力运行模型可能比ANE*更快*。请参阅[此性能基准](https://huggingface.co/blog/fast-mac-diffusers#performance-benchmarks)以及社区提供的[一些额外测量](https://github.com/huggingface/swift-coreml-diffusers/issues/31)以获取更多细节。
41
+
42
+ - 支持的推理框架。
43
+ * `packages`适用于Python推理。这可用于在尝试将转换后的Core ML模型集成到原生应用程序之前进行测试,或者如果您想探索Core ML性能但不需要支持原生应用程序。例如,具有Web UI的应用程序完全可以使用Python Core ML后端。
44
+ * `compiled`模型是Swift代码所必需的。Hub中的`compiled`模型将大型UNet模型权重分成多个文件,以兼容iOS和iPadOS设备。这对应于[`--chunk-unet`转换选项](https://github.com/apple/ml-stable-diffusion#-converting-models-to-core-ml)。如果您想支持原生应用程序,则需要选择`compiled`变体。
45
+
46
+ 官方的Core ML Stable Diffusion[模型](https://huggingface.co/apple/coreml-stable-diffusion-v1-4/tree/main)包括这些变体,但社区的可能有所不同:
47
+
48
+ ```
49
+ coreml-stable-diffusion-v1-4
50
+ ├── README.md
51
+ ├── original
52
+ │ ├── compiled
53
+ │ └── packages
54
+ └── split_einsum
55
+ ├── compiled
56
+ └── packages
57
+ ```
58
+
59
+ 您可以下载并使用所需的变体,如下所示。
60
+
61
+ ## Python中的Core ML推理
62
+
63
+ 安装以下库以在Python中运行Core ML推理:
64
+
65
+ ```bash
66
+ pip install huggingface_hub
67
+ pip install git+https://github.com/apple/ml-stable-diffusion
68
+ ```
69
+
70
+ ### 下载模型检查点
71
+
72
+ 要在Python中运行推理,请使用存储在`packages`文件夹中的版本之一,因为`compiled`版本仅��Swift兼容。您可以选择使用`original`或`split_einsum`注意力。
73
+
74
+ 这是您如何从Hub下载`original`注意力变体到一个名为`models`的目录:
75
+
76
+ ```Python
77
+ from huggingface_hub import snapshot_download
78
+ from pathlib import Path
79
+
80
+ repo_id = "apple/coreml-stable-diffusion-v1-4"
81
+ variant = "original/packages"
82
+
83
+ mo
84
+ del_path = Path("./models") / (repo_id.split("/")[-1] + "_" + variant.replace("/", "_"))
85
+ snapshot_download(repo_id, allow_patterns=f"{variant}/*", local_dir=model_path, local_dir_use_symlinks=False)
86
+ print(f"Model downloaded at {model_path}")
87
+ ```
88
+
89
+ ### 推理[[python-inference]]
90
+
91
+ 下载模型快照后,您可以使用 Apple 的 Python 脚本来测试它。
92
+
93
+ ```shell
94
+ python -m python_coreml_stable_diffusion.pipeline --prompt "a photo of an astronaut riding a horse on mars" -i ./models/coreml-stable-diffusion-v1-4_original_packages/original/packages -o </path/to/output/image> --compute-unit CPU_AND_GPU --seed 93
95
+ ```
96
+
97
+ 使用 `-i` 标志将下载的检查点路径传递给脚本。`--compute-unit` 表示您希望允许用于推理的硬件。它必须是以下选项之一:`ALL`、`CPU_AND_GPU`、`CPU_ONLY`、`CPU_AND_NE`。您也可以提供可选的输出路径和用于可重现性的种子。
98
+
99
+ 推理脚本假设您使用的是 Stable Diffusion 模型的原始版本,`CompVis/stable-diffusion-v1-4`。如果您使用另一个模型,您*必须*在推理命令行中使用 `--model-version` 选项指定其 Hub ID。这适用于已支持的模型以及您自己训练或微调的自定义模型。
100
+
101
+ 例如,如果您想使用 [`stable-diffusion-v1-5/stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5):
102
+
103
+ ```shell
104
+ python -m python_coreml_stable_diffusion.pipeline --prompt "a photo of an astronaut riding a horse on mars" --compute-unit ALL -o output --seed 93 -i models/coreml-stable-diffusion-v1-5_original_packages --model-version stable-diffusion-v1-5/stable-diffusion-v1-5
105
+ ```
106
+
107
+ ## Core ML 在 Swift 中的推理
108
+
109
+ 在 Swift 中运行推理比在 Python 中稍快,因为模型已经以 `mlmodelc` 格式编译。这在应用启动时加载模型时很明显,但如果在之后运行多次生成,则不应明显。
110
+
111
+ ### 下载
112
+
113
+ 要在您的 Mac 上运行 Swift 推理,您需要一个 `compiled` 检查点版本。我们建议您使用类似于先前示例的 Python 代码在本地下载它们,但使用 `compiled` 变体之一:
114
+
115
+ ```Python
116
+ from huggingface_hub import snapshot_download
117
+ from pathlib import Path
118
+
119
+ repo_id = "apple/coreml-stable-diffusion-v1-4"
120
+ variant = "original/compiled"
121
+
122
+ model_path = Path("./models") / (repo_id.split("/")[-1] + "_" + variant.replace("/", "_"))
123
+ snapshot_download(repo_id, allow_patterns=f"{variant}/*", local_dir=model_path, local_dir_use_symlinks=False)
124
+ print(f"Model downloaded at {model_path}")
125
+ ```
126
+
127
+ ### 推理[[swift-inference]]
128
+
129
+ 要运行推理,请克隆 Apple 的仓库:
130
+
131
+ ```bash
132
+ git clone https://github.com/apple/ml-stable-diffusion
133
+ cd ml-stable-diffusion
134
+ ```
135
+
136
+ 然后使用 Apple 的命令行工具,[Swift Package Manager](https://www.swift.org/package-manager/#):
137
+
138
+ ```bash
139
+ swift run StableDiffusionSample --resource-path models/coreml-stable-diffusion-v1-4_original_compiled --compute-units all "a photo of an astronaut riding a horse on mars"
140
+ ```
141
+
142
+ 您必须在 `--resource-path` 中指定上一步下载的检查点之一,请确保它包含扩展名为 `.mlmodelc` 的已编译 Core ML 包。`--compute-units` 必须是以下值之一:`all`、`cpuOnly`、`cpuAndGPU`、`cpuAndNeuralEngine`。
143
+
144
+ 有关更多详细信息,请参考 [Apple 仓库中的说明](https://github.com/apple/ml-stable-diffusion)。
145
+
146
+ ## 支持的 Diffusers 功能
147
+
148
+ Core ML 模型和推理代码不支持 🧨 Diffusers 的许多功能、选项和灵活性。以下是一些需要注意的限制:
149
+
150
+ - Core ML 模型仅适用于推理。它们不能用于训练或微调。
151
+ - 只有两个调度器已移植到 Swift:Stable Diffusion 使用的默认调度器和我们从 `diffusers` 实现移植到 Swift 的 `DPMSolverMultistepScheduler`。我们推荐您使用 `DPMSolverMultistepScheduler`,因为它在约一半的步骤中产生相同的质量。
152
+ - 负面提示、无分类器引导尺度和图像到图像任务在推理代码中可用。高级功能如深度引导、ControlNet 和潜在上采样器尚不可用。
153
+
154
+ Apple 的 [转换和推理仓库](https://github.com/apple/ml-stable-diffusion) 和我们自己的 [swift-coreml-diffusers](https://github.com/huggingface/swift-coreml-diffusers) 仓库旨在作为技术演示,以帮助其他开发者在此基础上构建。
155
+
156
+ 如果您对任何缺失功能有强烈需求,请随时提交功能请求或更好的是,贡献一个 PR 🙂。
157
+
158
+ ## 原生 Diffusers Swift 应用
159
+
160
+ 一个简单的方法来在您自己的 Apple 硬件上运行 Stable Diffusion 是使用 [我们的开源 Swift 仓库](https://github.com/huggingface/swift-coreml-diffusers),它基于 `diffusers` 和 Apple 的转换和推理仓库。您可以研究代码,使用 [Xcode](https://developer.apple.com/xcode/) 编译它,并根据您的需求进行适配。为了方便,[App Store 中还有一个独立 Mac 应用](https://apps.apple.com/app/diffusers/id1666309574),因此您无需处理代码或 IDE 即可使用它。如果您是开发者,并已确定 Core ML 是构建您的 Stable Diffusion 应用的最佳解决方案,那么您可以使用本指南的其余部分来开始您的项目。我们迫不及待想看看您会构建什么 🙂。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/deepcache.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版本("许可证")授权;除非遵守许可证,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,否则根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。有关许可证的具体语言,请参阅许可证中的权限和限制。
8
+ -->
9
+
10
+ # DeepCache
11
+ [DeepCache](https://huggingface.co/papers/2312.00858) 通过策略性地缓存和重用高级特征,同时利用 U-Net 架构高效更新低级特征,来加速 [`StableDiffusionPipeline`] 和 [`StableDiffusionXLPipeline`]。
12
+
13
+ 首先安装 [DeepCache](https://github.com/horseee/DeepCache):
14
+ ```bash
15
+ pip install DeepCache
16
+ ```
17
+
18
+ 然后加载并启用 [`DeepCacheSDHelper`](https://github.com/horseee/DeepCache#usage):
19
+
20
+ ```diff
21
+ import torch
22
+ from diffusers import StableDiffusionPipeline
23
+ pipe = StableDiffusionPipeline.from_pretrained('stable-diffusion-v1-5/stable-diffusion-v1-5', torch_dtype=torch.float16).to("cuda")
24
+
25
+ + from DeepCache import DeepCacheSDHelper
26
+ + helper = DeepCacheSDHelper(pipe=pipe)
27
+ + helper.set_params(
28
+ + cache_interval=3,
29
+ + cache_branch_id=0,
30
+ + )
31
+ + helper.enable()
32
+
33
+ image = pipe("a photo of an astronaut on a moon").images[0]
34
+ ```
35
+
36
+ `set_params` 方法接受两个参数:`cache_interval` 和 `cache_branch_id`。`cache_interval` 表示特征缓存的频率,指定为每次缓存操作之间的步数。`cache_branch_id` 标识网络的哪个分支(从最浅层到最深层排序)负责执行缓存过程。
37
+ 选择较低的 `cache_branch_id` 或较大的 `cache_interval` 可以加快推理速度,但会降低图像质量(这些超参数的消融实验可以在[论文](https://huggingface.co/papers/2312.00858)中找到)。一旦设置了这些参数,使用 `enable` 或 `disable` 方法来激活或停用 `DeepCacheSDHelper`。
38
+
39
+ <div class="flex justify-center">
40
+ <img src="https://github.com/horseee/Diffusion_DeepCache/raw/master/static/images/example.png">
41
+ </div>
42
+
43
+ 您可以在 [WandB 报告](https://wandb.ai/horseee/DeepCache/runs/jwlsqqgt?workspace=user-horseee) 中找到更多生成的样本(原始管道 vs DeepCache)和相应的推理延迟。提示是从 [MS-COCO 2017](https://cocodataset.org/#home) 数据集中随机选择的。
44
+
45
+ ## 基准测试
46
+
47
+ 我们在 NVIDIA RTX A5000 上测试了 DeepCache 使用 50 个推理步骤加速 [Stable Diffusion v2.1](https://huggingface.co/stabilityai/stable-diffusion-2-1) 的速度,使用不同的配置,包括分辨率、批处理大小、缓存间隔(I)和缓存分支(B)。
48
+
49
+ | **分辨率** | **批次大小** | **原始** | **DeepCache(I=3, B=0)** | **DeepCache(I=5, B=0)** | **DeepCache(I=5, B=1)** |
50
+ |----------------|----------------|--------------|-------------------------|-------------------------|-------------------------|
51
+ | 512| 8| 15.96| 6.88(2.32倍)| 5.03(3.18倍)| 7.27(2.20x)|
52
+ | | 4| 8.39| 3.60(2.33倍)| 2.62(3.21倍)| 3.75(2.24x)|
53
+ | | 1| 2.61| 1.12(2.33倍)| 0.81(3.24倍)| 1.11(2.35x)|
54
+ | 768| 8| 43.58| 18.99(2.29倍)| 13.96(3.12倍)| 21.27(2.05x)|
55
+ | | 4| 22.24| 9.67(2.30倍)| 7.10(3.13倍)| 10.74(2.07x)|
56
+ | | 1| 6.33| 2.72(2.33倍)| 1.97(3.21倍)| 2.98(2.12x)|
57
+ | 1024| 8| 101.95| 45.57(2.24倍)| 33.72(3.02倍)| 53.00(1.92x)|
58
+ | | 4| 49.25| 21.86(2.25倍)| 16.19(3.04倍)| 25.78(1.91x)|
59
+ | | 1| 13.83| 6.07(2.28倍)| 4.43(3.12倍)| 7.15(1.93x)|
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/fp16.md ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # 加速推理
14
+
15
+ Diffusion模型在推理时速度较慢,因为生成是一个迭代过程,需要经过一定数量的"步数"逐步将噪声细化为图像或视频。要加速这一过程,您可以尝试使用不同的[调度器](../api/schedulers/overview)、降低模型权重的精度以加快计算、使用更高效的内存注意力机制等方法。
16
+
17
+ 将这些技术组合使用,可以比单独使用任何一种技术获得更快的推理速度。
18
+
19
+ 本指南将介绍如何加速推理。
20
+
21
+ ## 模型数据类型
22
+
23
+ 模型权重的精度和数据类型会影响推理速度,因为更高的精度需要更多内存来加载,也需要更多时间进行计算。PyTorch默认以float32或全精度加载模型权重,因此更改数据类型是快速获得更快推理速度的简单方法。
24
+
25
+ <hfoptions id="dtypes">
26
+ <hfoption id="bfloat16">
27
+
28
+ bfloat16与float16类似,但对数值误差更稳健。硬件对bfloat16的支持各不相同,但大多数现代GPU都能支持bfloat16。
29
+
30
+ ```py
31
+ import torch
32
+ from diffusers import StableDiffusionXLPipeline
33
+
34
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
35
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
36
+ ).to("cuda")
37
+
38
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
39
+ pipeline(prompt, num_inference_steps=30).images[0]
40
+ ```
41
+
42
+ </hfoption>
43
+ <hfoption id="float16">
44
+
45
+ float16与bfloat16类似,但可能更容易出现数值误差。
46
+
47
+ ```py
48
+ import torch
49
+ from diffusers import StableDiffusionXLPipeline
50
+
51
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
52
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
53
+ ).to("cuda")
54
+
55
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
56
+ pipeline(prompt, num_inference_steps=30).images[0]
57
+ ```
58
+
59
+ </hfoption>
60
+ <hfoption id="TensorFloat-32">
61
+
62
+ [TensorFloat-32 (tf32)](https://blogs.nvidia.com/blog/2020/05/14/tensorfloat-32-precision-format/)模式在NVIDIA Ampere GPU上受支持,它以tf32计算卷积和矩阵乘法运算。存储和其他操作保持在float32。与bfloat16或float16结合使用时,可以显著加快计算速度。
63
+
64
+ PyTorch默认仅对卷积启用tf32模式,您需要显式启用矩阵乘法的tf32模式。
65
+
66
+ ```py
67
+ import torch
68
+ from diffusers import StableDiffusionXLPipeline
69
+
70
+ torch.backends.cuda.matmul.allow_tf32 = True
71
+
72
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
73
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
74
+ ).to("cuda")
75
+
76
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
77
+ pipeline(prompt, num_inference_steps=30).images[0]
78
+ ```
79
+
80
+ 更多详情请参阅[混合精度训练](https://huggingface.co/docs/transformers/en/perf_train_gpu_one#mixed-precision)文档。
81
+
82
+ </hfoption>
83
+ </hfoptions>
84
+
85
+ ## 缩放点积注意力
86
+
87
+ > [!TIP]
88
+ > 内存高效注意力优化了推理速度*和*[内存使用](./memory#memory-efficient-attention)!
89
+
90
+ [缩放点积注意力(SDPA)](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)实现了多种注意力后端,包括[FlashAttention](https://github.com/Dao-AILab/flash-attention)、[xFormers](https://github.com/facebookresearch/xformers)和原生C++实现。它会根据您的硬件自动选择最优的后端。
91
+
92
+ 如果您使用的是PyTorch >= 2.0,SDPA默认启用,无需对代码进行任何额外更改。不过,您也可以尝试使用其他注意力后端来自行选择。下面的示例使用[torch.nn.attention.sdpa_kernel](https://pytorch.org/docs/stable/generated/torch.nn.attention.sdpa_kernel.html)上下文管理器来启用高效注意力。
93
+
94
+ ```py
95
+ from torch.nn.attention import SDPBackend, sdpa_kernel
96
+ import torch
97
+ from diffusers import StableDiffusionXLPipeline
98
+
99
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
100
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
101
+ ).to("cuda")
102
+
103
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
104
+
105
+ with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
106
+ image = pipeline(prompt, num_inference_steps=30).images[0]
107
+ ```
108
+
109
+ ## torch.compile
110
+
111
+ [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html)通过将PyTorch代码和操作编译为优化的内核来加速推理。Diffusers通常会编译计算密集型的模型,如UNet、transformer或VAE。
112
+
113
+ 启用以下编译器设���以获得最大速度(更多选项请参阅[完整列表](https://github.com/pytorch/pytorch/blob/main/torch/_inductor/config.py))。
114
+
115
+ ```py
116
+ import torch
117
+ from diffusers import StableDiffusionXLPipeline
118
+
119
+ torch._inductor.config.conv_1x1_as_mm = True
120
+ torch._inductor.config.coordinate_descent_tuning = True
121
+ torch._inductor.config.epilogue_fusion = False
122
+ torch._inductor.config.coordinate_descent_check_all_directions = True
123
+ ```
124
+
125
+ 加载并编译UNet和VAE。有几种不同的模式可供选择,但`"max-autotune"`通过编译为CUDA图来优化速度。CUDA图通过单个CPU操作启动多个GPU操作,有效减少了开销。
126
+
127
+ > [!TIP]
128
+ > 在PyTorch 2.3.1中,您可以控制torch.compile的缓存行为。这对于像`"max-autotune"`这样的编译模式特别有用,它会通过网格搜索多个编译标志来找到最优配置。更多详情请参阅[torch.compile中的编译时间缓存](https://pytorch.org/tutorials/recipes/torch_compile_caching_tutorial.html)教程。
129
+
130
+ 将内存布局更改为[channels_last](./memory#torchchannels_last)也可以优化内存和推理速度。
131
+
132
+ ```py
133
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
134
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
135
+ ).to("cuda")
136
+ pipeline.unet.to(memory_format=torch.channels_last)
137
+ pipeline.vae.to(memory_format=torch.channels_last)
138
+ pipeline.unet = torch.compile(
139
+ pipeline.unet, mode="max-autotune", fullgraph=True
140
+ )
141
+ pipeline.vae.decode = torch.compile(
142
+ pipeline.vae.decode,
143
+ mode="max-autotune",
144
+ fullgraph=True
145
+ )
146
+
147
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
148
+ pipeline(prompt, num_inference_steps=30).images[0]
149
+ ```
150
+
151
+ 第一次编译时速度较慢,但一旦编译完成,速度会显著提升。尽量只在相同类型的推理操作上使用编译后的管道。在不同尺寸的图像上调用编译后的管道会重新触发编译,这会很慢且效率低下。
152
+
153
+ ### 动态形状编译
154
+
155
+ > [!TIP]
156
+ > 确保始终使用PyTorch的nightly版本以获得更好的支持。
157
+
158
+ `torch.compile`会跟踪输入形状和条件,如果这些不同,它会重新编译模型。例如,如果模型是在1024x1024分辨率的图像上编译的,而在不同分辨率的图像上使用,就会触发重新编译。
159
+
160
+ 为避免重新编译,添加`dynamic=True`以尝试生成更动态的内核,避免条件变化时重新编译。
161
+
162
+ ```diff
163
+ + torch.fx.experimental._config.use_duck_shape = False
164
+ + pipeline.unet = torch.compile(
165
+ pipeline.unet, fullgraph=True, dynamic=True
166
+ )
167
+ ```
168
+
169
+ 指定`use_duck_shape=False`会指示编译器是否应使用相同的符号变量来表示相同大小的输入。更多详情请参阅此[评论](https://github.com/huggingface/diffusers/pull/11327#discussion_r2047659790)。
170
+
171
+ 并非所有模型都能开箱即用地从动态编译中受益,可能需要更改。参考此[PR](https://github.com/huggingface/diffusers/pull/11297/),它改进了[`AuraFlowPipeline`]的实现以受益于动态编译。
172
+
173
+ 如果动态编译对Diffusers模型的效果不如预期,请随时提出问题。
174
+
175
+ ### 区域编译
176
+
177
+ [区域编译](https://docs.pytorch.org/tutorials/recipes/regional_compilation.html)通过仅编译模型中*小而频繁重复的块*(通常是transformer层)来减少冷启动延迟,并为每个后续出现的块重用编译后的工件。对于许多diffusion架构,这提供了与全图编译相同的运行时加速,并将编译时间减少了8-10倍。
178
+
179
+ 使用[`~ModelMixin.compile_repeated_blocks`]方法(一个包装`torch.compile`的辅助函数)在任何组件(如transformer模型)上,如下所示。
180
+
181
+ ```py
182
+ # pip install -U diffusers
183
+ import torch
184
+ from diffusers import StableDiffusionXLPipeline
185
+
186
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
187
+ "stabilityai/stable-diffusion-xl-base-1.0",
188
+ torch_dtype=torch.float16,
189
+ ).to("cuda")
190
+
191
+ # 仅编译UNet中重复的transformer层
192
+ pipeline.unet.compile_repeated_blocks(fullgraph=True)
193
+ ```
194
+
195
+ 要为新模型启用区域编译,请在模型类中添加一个`_repeated_blocks`属性,包含您想要编译的块的类名(作为字符串)。
196
+
197
+ ```py
198
+ class MyUNet(ModelMixin):
199
+ _repeated_blocks = ("Transformer2DModel",) # ← 默认编译
200
+ ```
201
+
202
+ > [!TIP]
203
+ > 更多区域编译示例,请参阅参考[PR](https://github.com/huggingface/diffusers/pull/11705)。
204
+
205
+ [Accelerate](https://huggingface.co/docs/accelerate/index)中还有一个[compile_regions](https://github.com/huggingface/accelerate/blob/273799c85d849a1954a4f2e65767216eb37fa089/src/accelerate/utils/other.py#L78)方法,可以自动选择模型中的候选块进行编译。其余图会单独编译。这对于快速实验很有用,因为您不需要设置哪些块要编译或调整编译标志。
206
+
207
+ ```py
208
+ # pip install -U accelerate
209
+ import torch
210
+ from diffusers import StableDiffusionXLPipeline
211
+ from accelerate.utils import compile regions
212
+
213
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
214
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
215
+ ).to("cuda")
216
+ pipeline.unet = compile_regions(pipeline.unet, mode="reduce-overhead", fullgraph=True)
217
+ ```
218
+
219
+ [`~ModelMixin.compile_repeated_blocks`]是故意显式的。在`_repeated_blocks`中列出要重复的块,辅助函数仅编译这些块。它提供了可预测的行为,并且只需一行代码即可轻松推理缓存重用。
220
+
221
+ ### 图中断
222
+
223
+ 在torch.compile中指定`fullgraph=True`非常重要,以确保底层模型中没有图中断。这使您可以充分利用torch.compile而不会降低性能。对于UNet和VAE,这会改变您访问返回变量的方式。
224
+
225
+ ```diff
226
+ - latents = unet(
227
+ - latents, timestep=timestep, encoder_hidden_states=prompt_embeds
228
+ -).sample
229
+
230
+ + latents = unet(
231
+ + latents, timestep=timestep, encoder_hidden_states=prompt_embeds, return_dict=False
232
+ +)[0]
233
+ ```
234
+
235
+ ### GPU同步
236
+
237
+ 每次去噪器做出预测后,调度器的`step()`函数会被[调用](https://github.com/huggingface/diffusers/blob/1d686bac8146037e97f3fd8c56e4063230f71751/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py#L1228),并且`sigmas`变量会被[索引](https://github.com/huggingface/diffusers/blob/1d686bac8146037e97f3fd8c56e4063230f71751/src/diffusers/schedulers/scheduling_euler_discrete.py#L476)。当放在GPU上时,这会引入延迟,因为CPU和GPU之间需要进行通信同步。当去噪器已经编译时,这一点会更加明显。
238
+
239
+ 一般来说,`sigmas`应该[保持在CPU上](https://github.com/huggingface/diffusers/blob/35a969d297cba69110d175ee79c59312b9f49e1e/src/diffusers/schedulers/scheduling_euler_discrete.py#L240),以避免通信同步和延迟。
240
+
241
+ > [!TIP]
242
+ > 参阅[torch.compile和Diffusers:峰值性能实践指南](https://pytorch.org/blog/torch-compile-and-diffusers-a-hands-on-guide-to-peak-performance/)博客文章,了解如何为扩散模型最大化`torch.compile`的性能。
243
+
244
+ ### 基准测试
245
+
246
+ 参阅[diffusers/benchmarks](https://huggingface.co/datasets/diffusers/benchmarks)数据集,查看编译管道的推理延迟和内存使用数据。
247
+
248
+ [diffusers-torchao](https://github.com/sayakpaul/diffusers-torchao#benchmarking-results)仓库还包含Flux和CogVideoX编译版本的基准测试结果。
249
+
250
+ ## 动态量化
251
+
252
+ [动态量化](https://pytorch.org/tutorials/recipes/recipes/dynamic_quantization.html)通过降低精度以加快数学运算来提高推理速度。这种特定类型的量化在运行时根据数据确定如何缩放激活,而不是使用固定的缩放因子。因此,缩放因子与数据更准确地匹配。
253
+
254
+ 以下示例使用[torchao](../quantization/torchao)库对UNet和VAE应用[动态int8量化](https://pytorch.org/tutorials/recipes/recipes/dynamic_quantization.html)。
255
+
256
+ > [!TIP]
257
+ > 参阅我们的[torchao](../quantization/torchao)文档,了解更多关于如何使用Diffusers torchao集成的信息。
258
+
259
+ 配置编译器标志以获得最大速度。
260
+
261
+ ```py
262
+ import torch
263
+ from torchao import apply_dynamic_quant
264
+ from diffusers import StableDiffusionXLPipeline
265
+
266
+ torch._inductor.config.conv_1x1_as_mm = True
267
+ torch._inductor.config.coordinate_descent_tuning = True
268
+ torch._inductor.config.epilogue_fusion = False
269
+ torch._inductor.config.coordinate_descent_check_all_directions = True
270
+ torch._inductor.config.force_fuse_int_mm_with_mul = True
271
+ torch._inductor.config.use_mixed_mm = True
272
+ ```
273
+
274
+ 使用[dynamic_quant_filter_fn](https://github.com/huggingface/diffusion-fast/blob/0f169640b1db106fe6a479f78c1ed3bfaeba3386/utils/pipeline_utils.py#L16)过滤掉UNet和VAE中一些不会从动态量化中受益的线性层。
275
+
276
+ ```py
277
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
278
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
279
+ ).to("cuda")
280
+
281
+ apply_dynamic_quant(pipeline.unet, dynamic_quant_filter_fn)
282
+ apply_dynamic_quant(pipeline.vae, dynamic_quant_filter_fn)
283
+
284
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
285
+ pipeline(prompt, num_inference_steps=30).images[0]
286
+ ```
287
+
288
+ ## 融合投影矩阵
289
+
290
+ > [!WARNING]
291
+ > [fuse_qkv_projections](https://github.com/huggingface/diffusers/blob/58431f102cf39c3c8a569f32d71b2ea8caa461e1/src/diffusers/pipelines/pipeline_utils.py#L2034)方法是实验性的,目前主要支持Stable Diffusion管道。参阅此[PR](https://github.com/huggingface/diffusers/pull/6179)了解如何为其他管道启用它。
292
+
293
+ 在注意力块中,输入被投影到三个子空间,分别由投影矩阵Q、K和V表示。这些投影通常单独计算,但您可以水平组合这些矩阵为一个矩阵,并在单步中执行投影。这会增加输入投影的矩阵乘法大小,并提高量化的效果。
294
+
295
+ ```py
296
+ pipeline.fuse_qkv_projections()
297
+ ```
298
+
299
+ ## 资源
300
+
301
+ - 阅读[Presenting Flux Fast: Making Flux go brrr on H100s](https://pytorch.org/blog/presenting-flux-fast-making-flux-go-brrr-on-h100s/)博客文章,了解如何结合所有这些优化与[TorchInductor](https://docs.pytorch.org/docs/stable/torch.compiler.html)和[AOTInductor](https://docs.pytorch.org/docs/stable/torch.compiler_aot_inductor.html),使用[flux-fast](https://github.com/huggingface/flux-fast)的配方获得约2.5倍的加速。
302
+
303
+ 这些配方支持AMD硬件和[Flux.1 Kontext Dev](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev)。
304
+ - 阅读[torch.compile和Diffusers:峰值性能实践指南](https://pytorch.org/blog/torch-compile-and-diffusers-a-hands-on-guide-to-peak-performance/)博客文章,了解如何在使用`torch.compile`时最大化性能。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/habana.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版本("许可证")授权;除非遵守许可证,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。有关许可证管理权限和限制的具体语言,请参阅许可证。
8
+ -->
9
+
10
+ # Intel Gaudi
11
+
12
+ Intel Gaudi AI 加速器系列包括 [Intel Gaudi 1](https://habana.ai/products/gaudi/)、[Intel Gaudi 2](https://habana.ai/products/gaudi2/) 和 [Intel Gaudi 3](https://habana.ai/products/gaudi3/)。每台服务器配备 8 个设备,称为 Habana 处理单元 (HPU),在 Gaudi 3 上提供 128GB 内存,在 Gaudi 2 上提供 96GB 内存,在第一代 Gaudi 上提供 32GB 内存。有关底层硬件架构的更多详细信息,请查看 [Gaudi 架构](https://docs.habana.ai/en/latest/Gaudi_Overview/Gaudi_Architecture.html) 概述。
13
+
14
+ Diffusers 管道可以利用 HPU 加速,即使管道尚未添加到 [Optimum for Intel Gaudi](https://huggingface.co/docs/optimum/main/en/habana/index),也可以通过 [GPU 迁移工具包](https://docs.habana.ai/en/latest/PyTorch/PyTorch_Model_Porting/GPU_Migration_Toolkit/GPU_Migration_Toolkit.html) 实现。
15
+
16
+ 在您的管道上调用 `.to("hpu")` 以将其移动到 HPU 设备,如下所示为 Flux 示例:
17
+ ```py
18
+ import torch
19
+ from diffusers import DiffusionPipeline
20
+
21
+ pipeline = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
22
+ pipeline.to("hpu")
23
+
24
+ image = pipeline("一张松鼠在毕加索风格中的图像").images[0]
25
+ ```
26
+
27
+ > [!TIP]
28
+ > 对于 Gaudi 优化的扩散管道实现,我们推荐使用 [Optimum for Intel Gaudi](https://huggingface.co/docs/optimum/main/en/habana/index)。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/memory.md ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 HuggingFace 团队。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版本(“许可证”)授权;除非遵守许可证,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,根据许可证分发的软件按“原样”分发,无任何明示或暗示的担保或条件。有关许可证的特定语言管理权限和限制,请参阅许可证。
8
+ -->
9
+
10
+ # 减少内存使用
11
+
12
+ 现代diffusion models,如 [Flux](../api/pipelines/flux) 和 [Wan](../api/pipelines/wan),拥有数十亿参数,在您的硬件上进行推理时会占用大量内存。这是一个挑战,因为常见的 GPU 通常没有足够的内存。为了克服内存限制,您可以使用多个 GPU(如果可用)、将一些管道组件卸载到 CPU 等。
13
+
14
+ 本指南将展示如何减少内存使用。
15
+
16
+ > [!TIP]
17
+ > 请记住,这些技术可能需要根据模型进行调整。例如,基于 transformer 的扩散模型可能不会像基于 UNet 的模型那样从这些内存优化中同等受益。
18
+
19
+ ## 多个 GPU
20
+
21
+ 如果您有多个 GPU 的访问权限,有几种选项可以高效地在硬件上加载和分发大型模型。这些功能由 [Accelerate](https://huggingface.co/docs/accelerate/index) 库支持,因此请确保先安装它。
22
+
23
+ ```bash
24
+ pip install -U accelerate
25
+ ```
26
+
27
+ ### 分片检查点
28
+
29
+ 将大型检查点加载到多个分片中很有用,因为分片会逐个加载。这保持了低内存使用,只需要足够的内存来容纳模型大小和最大分片大小。我们建议当 fp32 检查点大于 5GB 时进行分片。默认分片大小为 5GB。
30
+
31
+ 在 [`~DiffusionPipeline.save_pretrained`] 中使用 `max_shard_size` 参数对检查点进行分片。
32
+
33
+ ```py
34
+ from diffusers import AutoModel
35
+
36
+ unet = AutoModel.from_pretrained(
37
+ "stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet"
38
+ )
39
+ unet.save_pretrained("sdxl-unet-sharded", max_shard_size="5GB")
40
+ ```
41
+
42
+ 现在您可以使用分片检查点,而不是常规检查点,以节省内存。
43
+
44
+ ```py
45
+ import torch
46
+ from diffusers import AutoModel, StableDiffusionXLPipeline
47
+
48
+ unet = AutoModel.from_pretrained(
49
+ "username/sdxl-unet-sharded", torch_dtype=torch.float16
50
+ )
51
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
52
+ "stabilityai/stable-diffusion-xl-base-1.0",
53
+ unet=unet,
54
+ torch_dtype=torch.float16
55
+ ).to("cuda")
56
+ ```
57
+
58
+ ### 设备放置
59
+
60
+ > [!WARNING]
61
+ > 设备放置是一个实验性功能,API 可能会更改。目前仅支持 `balanced` 策略。我们计划在未来支持额外的映射策略。
62
+
63
+ `device_map` 参数控制管道或模型中的组件如何
64
+ 单个模型中的层分布在多个设备上。
65
+
66
+ <hfoptions id="device-map">
67
+ <hfoption id="pipeline level">
68
+
69
+ `balanced` 设备放置策略将管道均匀分割到所有可用设备上。
70
+
71
+ ```py
72
+ import torch
73
+ from diffusers import AutoModel, StableDiffusionXLPipeline
74
+
75
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
76
+ "stabilityai/stable-diffusion-xl-base-1.0",
77
+ torch_dtype=torch.float16,
78
+ device_map="balanced"
79
+ )
80
+ ```
81
+
82
+ 您可以使用 `hf_device_map` 检查管道的设备映射。
83
+
84
+ ```py
85
+ print(pipeline.hf_device_map)
86
+ {'unet': 1, 'vae': 1, 'safety_checker': 0, 'text_encoder': 0}
87
+ ```
88
+
89
+ </hfoption>
90
+ <hfoption id="model level">
91
+
92
+ `device_map` 对于加载大型模型非常有用,例如具有 125 亿参数的 Flux diffusion transformer。将其设置为 `"auto"` 可以自动将模型首先分布到最快的设备上,然后再移动到较慢的设备。有关更多详细信息,请参阅 [模型分片](../training/distributed_inference#model-sharding) 文档。
93
+
94
+ ```py
95
+ import torch
96
+ from diffusers import AutoModel
97
+
98
+ transformer = AutoModel.from_pretrained(
99
+ "black-forest-labs/FLUX.1-dev",
100
+ subfolder="transformer",
101
+ device_map="auto",
102
+ torch_dtype=torch.bfloat16
103
+ )
104
+ ```
105
+
106
+ 您可以使用 `hf_device_map` 检查模型的设备映射。
107
+
108
+ ```py
109
+ print(transformer.hf_device_map)
110
+ ```
111
+
112
+ </hfoption>
113
+ </hfoptions>
114
+
115
+ 当设计您自己的 `device_map` 时,它应该是一个字典,包含模型的特定模块名称或层以及设备标识符(整数表示 GPU,`cpu` 表示 CPU,`disk` 表示磁盘)。
116
+
117
+ 在模型上调用 `hf_device_map` 以查看模型层如何分布,然后设计您自己的映射。
118
+
119
+ ```py
120
+ print(transformer.hf_device_map)
121
+ {'pos_embed': 0, 'time_text_embed': 0, 'context_embedder': 0, 'x_embedder': 0, 'transformer_blocks': 0, 'single_transformer_blocks.0': 0, 'single_transformer_blocks.1': 0, 'single_transformer_blocks.2': 0, 'single_transformer_blocks.3': 0, 'single_transformer_blocks.4': 0, 'single_transformer_blocks.5': 0, 'single_transformer_blocks.6': 0, 'single_transformer_blocks.7': 0, 'single_transformer_blocks.8': 0, 'single_transformer_blocks.9': 0, 'single_transformer_blocks.10': 'cpu', 'single_transformer_blocks.11': 'cpu', 'single_transformer_blocks.12': 'cpu', 'single_transformer_blocks.13': 'cpu', 'single_transformer_blocks.14': 'cpu', 'single_transformer_blocks.15': 'cpu', 'single_transformer_blocks.16': 'cpu', 'single_transformer_blocks.17': 'cpu', 'single_transformer_blocks.18': 'cpu', 'single_transformer_blocks.19': 'cpu', 'single_transformer_blocks.20': 'cpu', 'single_transformer_blocks.21': 'cpu', 'single_transformer_blocks.22': 'cpu', 'single_transformer_blocks.23': 'cpu', 'single_transformer_blocks.24': 'cpu', 'single_transformer_blocks.25': 'cpu', 'single_transformer_blocks.26': 'cpu', 'single_transformer_blocks.27': 'cpu', 'single_transformer_blocks.28': 'cpu', 'single_transformer_blocks.29': 'cpu', 'single_transformer_blocks.30': 'cpu', 'single_transformer_blocks.31': 'cpu', 'single_transformer_blocks.32': 'cpu', 'single_transformer_blocks.33': 'cpu', 'single_transformer_blocks.34': 'cpu', 'single_transformer_blocks.35': 'cpu', 'single_transformer_blocks.36': 'cpu', 'single_transformer_blocks.37': 'cpu', 'norm_out': 'cpu', 'proj_out': 'cpu'}
122
+ ```
123
+
124
+ 例如,下面的 `device_map` 将 `single_transformer_blocks.10` 到 `single_transformer_blocks.20` 放置在第二个 GPU(`1`)上。
125
+
126
+ ```py
127
+ import torch
128
+ from diffusers import AutoModel
129
+
130
+ device_map = {
131
+ 'pos_embed': 0, 'time_text_embed': 0, 'context_embedder': 0, 'x_embedder': 0, 'transformer_blocks': 0, 'single_transformer_blocks.0': 0, 'single_transformer_blocks.1': 0, 'single_transformer_blocks.2': 0, 'single_transformer_blocks.3': 0, 'single_transformer_blocks.4': 0, 'single_transformer_blocks.5': 0, 'single_transformer_blocks.6': 0, 'single_transformer_blocks.7': 0, 'single_transformer_blocks.8': 0, 'single_transformer_blocks.9': 0, 'single_transformer_blocks.10': 1, 'single_transformer_blocks.11': 1, 'single_transformer_blocks.12': 1, 'single_transformer_blocks.13': 1, 'single_transformer_blocks.14': 1, 'single_transformer_blocks.15': 1, 'single_transformer_blocks.16': 1, 'single_transformer_blocks.17': 1, 'single_transformer_blocks.18': 1, 'single_transformer_blocks.19': 1, 'single_transformer_blocks.20': 1, 'single_transformer_blocks.21': 'cpu', 'single_transformer_blocks.22': 'cpu', 'single_transformer_blocks.23': 'cpu', 'single_transformer_blocks.24': 'cpu', 'single_transformer_blocks.25': 'cpu', 'single_transformer_blocks.26': 'cpu', 'single_transformer_blocks.27': 'cpu', 'single_transformer_blocks.28': 'cpu', 'single_transformer_blocks.29': 'cpu', 'single_transformer_blocks.30': 'cpu', 'single_transformer_blocks.31': 'cpu', 'single_transformer_blocks.32': 'cpu', 'single_transformer_blocks.33': 'cpu', 'single_transformer_blocks.34': 'cpu', 'single_transformer_blocks.35': 'cpu', 'single_transformer_blocks.36': 'cpu', 'single_transformer_blocks.37': 'cpu', 'norm_out': 'cpu', 'proj_out': 'cpu'
132
+ }
133
+
134
+ transformer = AutoModel.from_pretrained(
135
+ "black-forest-labs/FLUX.1-dev",
136
+ subfolder="transformer",
137
+ device_map=device_map,
138
+ torch_dtype=torch.bfloat16
139
+ )
140
+ ```
141
+
142
+ 传递一个字典,将最大内存使用量映射到每个设备以强制执行限制。如果设备不在 `max_memory` 中,它将被忽略,管道组件不会分发到该设备。
143
+
144
+ ```py
145
+ import torch
146
+ from diffusers import AutoModel, StableDiffusionXLPipeline
147
+
148
+ max_memory = {0:"1GB", 1:"1GB"}
149
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
150
+ "stabilityai/stable-diffusion-xl-base-1.0",
151
+ torch_dtype=torch.float16,
152
+ device_map="balanced",
153
+ max_memory=max_memory
154
+ )
155
+ ```
156
+
157
+ Diffusers 默认使用所有设备的最大内存,但如果它们无法适应 GPU,则需要使用单个 GPU 并通过以下方法卸载到 CPU。
158
+
159
+ - [`~DiffusionPipeline.enable_model_cpu_offload`] 仅适用于单个 GPU,但非常大的模型可能无法适应它
160
+ - 使用 [`~DiffusionPipeline.enable_sequential_cpu_offload`] 可能有效,但它极其缓慢,并且仅限于单个 GPU。
161
+
162
+ 使用 [`~DiffusionPipeline.reset_device_map`] 方法来重置 `device_map`。如果您想在已进行设备映射的管道上使用方法如 `.to()`、[`~DiffusionPipeline.enable_sequential_cpu_offload`] 和 [`~DiffusionPipeline.enable_model_cpu_offload`],这是必要的。
163
+
164
+ ```py
165
+ pipeline.reset_device_map()
166
+ ```
167
+
168
+ ## VAE 切片
169
+
170
+ VAE 切片通过将大批次输入拆分为单个数据批次并分别处理它们来节省内存。这种方法在同时生成多个图像时效果最佳。
171
+
172
+ 例如,如果您同时生成 4 个图像,解码会将峰值激活内存增加 4 倍。VAE 切片通过一次只解码 1 个图像而不是所有 4 个图像来减少这种情况。
173
+
174
+ 调用 [`~StableDiffusionPipeline.enable_vae_slicing`] 来启用切片 VAE。您可以预期在解码多图像批次时性能会有小幅提升,而在单图像批次时没有性能影响。
175
+
176
+ ```py
177
+ import torch
178
+ from diffusers import AutoModel, StableDiffusionXLPipeline
179
+
180
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
181
+ "stabilityai/stable-diffusion-xl-base-1.0",
182
+ torch_dtype=torch.float16,
183
+ ).to("cuda")
184
+ pipeline.enable_vae_slicing()
185
+ pipeline(["An astronaut riding a horse on Mars"]*32).images[0]
186
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
187
+ ```
188
+
189
+ > [!WARNING]
190
+ > [`AutoencoderKLWan`] 和 [`AsymmetricAutoencoderKL`] 类不支持切片。
191
+
192
+ ## VAE 平铺
193
+
194
+ VAE 平铺通过将图像划分为较小的重叠图块而不是一次性处理整个图像来节省内存。这也减少了峰值内存使用量,因为 GPU 一次只处理一个图块。
195
+
196
+ 调用 [`~StableDiffusionPipeline.enable_vae_tiling`] 来启用 VAE 平铺。生成的图像可能因图块到图块的色调变化而有所不同,因为它们被单独解码,但图块之间不应有明显的接缝。对于低于预设(但可配置)限制的分辨率,平铺被禁用。例如,对于 [`StableDiffusionPipeline`] 中的 VAE,此限制为 512x512。
197
+
198
+ ```py
199
+ import torch
200
+ from diffusers import AutoPipelineForImage2Image
201
+ from diffusers.utils import load_image
202
+
203
+ pipeline = AutoPipelineForImage2Image.from_pretrained(
204
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
205
+ ).to("cuda")
206
+ pipeline.enable_vae_tiling()
207
+
208
+ init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-sdxl-init.png")
209
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
210
+ pipeline(prompt, image=init_image, strength=0.5).images[0]
211
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
212
+ ```
213
+
214
+ > [!WARNING]
215
+ > [`AutoencoderKLWan`] 和 [`AsymmetricAutoencoderKL`] 不支持平铺。
216
+
217
+ ## 卸载
218
+
219
+ 卸载策略将非当前活动层移动
220
+ 将模型移动到 CPU 以避免增加 GPU 内存。这些策略可以与量化和 torch.compile 结合使用,以平衡推理速度和内存使用。
221
+
222
+ 有关更多详细信息,请参考 [编译和卸载量化模型](./speed-memory-optims) 指南。
223
+
224
+ ### CPU 卸载
225
+
226
+ CPU 卸载选择性地将权重从 GPU 移动到 CPU。当需要某个组件时,它被传输到 GPU;当不需要时,它被移动到 CPU。此方法作用于子模块而非整个模型。它通过避免将整个模型存储在 GPU 上来节省内存。
227
+
228
+ CPU 卸载显著减少内存使用,但由于子模块在设备之间多次来回传递,它也非常慢。由于速度极慢,它通常不实用。
229
+
230
+ > [!WARNING]
231
+ > 在调用 [`~DiffusionPipeline.enable_sequential_cpu_offload`] 之前,不要将管道移动到 CUDA,否则节省的内存非常有限(更多细节请参考此 [issue](https://github.com/huggingface/diffusers/issues/1934))。这是一个状态操作,会在模型上安装钩子。
232
+
233
+ 调用 [`~DiffusionPipeline.enable_sequential_cpu_offload`] 以在管道上启用它。
234
+
235
+ ```py
236
+ import torch
237
+ from diffusers import DiffusionPipeline
238
+
239
+ pipeline = DiffusionPipeline.from_pretrained(
240
+ "black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16
241
+ )
242
+ pipeline.enable_sequential_cpu_offload()
243
+
244
+ pipeline(
245
+ prompt="An astronaut riding a horse on Mars",
246
+ guidance_scale=0.,
247
+ height=768,
248
+ width=1360,
249
+ num_inference_steps=4,
250
+ max_sequence_length=256,
251
+ ).images[0]
252
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
253
+ ```
254
+
255
+ ### 模型卸载
256
+
257
+ 模型卸载将整个模型移动到 GPU,而不是选择性地移动某些层或模型组件。一个主要管道模型,通常是文本编码器、UNet 和 VAE,被放置在 GPU 上,而其他组件保持在 CPU 上。像 UNet 这样运行多次的组件会一直留在 GPU 上,直到完全完成且不再需要。这消除了 [CPU 卸载](#cpu-offloading) 的通信开销,使模型卸载成为一个更快的替代方案。权衡是内存节省不会那么大。
258
+
259
+ > [!WARNING]
260
+ > 请注意,如果在安装钩子后模型在管道外部被重用(更多细节请参考 [移除钩子](https://huggingface.co/docs/accelerate/en/package_reference/big_modeling#accelerate.hooks.remove_hook_from_module)),您需要按预期顺序运行整个管道和模型以正确卸载它们。这是一个状态操作,会在模型上安装钩子。
261
+
262
+ 调用 [`~DiffusionPipeline.enable_model_cpu_offload`] 以在管道上启用它。
263
+
264
+ ```py
265
+ import torch
266
+ from diffusers import DiffusionPipeline
267
+
268
+ pipeline = DiffusionPipeline.from_pretrained(
269
+ "black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16
270
+ )
271
+ pipeline.enable_model_cpu_offload()
272
+
273
+ pipeline(
274
+ prompt="An astronaut riding a horse on Mars",
275
+ guidance_scale=0.,
276
+ height=768,
277
+ width=1360,
278
+ num_inference_steps=4,
279
+ max_sequence_length=256,
280
+ ).images[0]
281
+ print(f"最大内存保留: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
282
+ ```
283
+
284
+ [`~DiffusionPipeline.enable_model_cpu_offload`] 在您单独使用 [`~StableDiffusionXLPipeline.encode_prompt`] 方法生成文本编码器隐藏状态时也有帮助。
285
+
286
+ ### 组卸载
287
+
288
+ 组卸载将内部层组([torch.nn.ModuleList](https://pytorch.org/docs/stable/generated/torch.nn.ModuleList.html) 或 [torch.nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html))移动到 CPU。它比[模型卸载](#model-offloading)使用更少的内存,并且比[CPU 卸载](#cpu-offloading)更快,因为它减少了通信开销。
289
+
290
+ > [!WARNING]
291
+ > 如果前向实现包含权重相关的输入设备转换,组卸载可能不适用于所有模型,因为它可能与组卸载的设备转换机制冲突。
292
+
293
+ 调用 [`~ModelMixin.enable_group_offload`] 为继承自 [`ModelMixin`] 的标准 Diffusers 模型组件启用它。对于不继承自 [`ModelMixin`] 的其他模型组件,例如通用 [torch.nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html),使用 [`~hooks.apply_group_offloading`] 代替。
294
+
295
+ `offload_type` 参数可以设置为 `block_level` 或 `leaf_level`。
296
+
297
+ - `block_level` 基于 `num_blocks_per_group` 参数卸载层组。例如,如果 `num_blocks_per_group=2` 在一个有 40 层的模型上,每次加载和卸载 2 层(总共 20 次加载/卸载)。这大大减少了内存需求。
298
+ - `leaf_level` 在最低级别卸载单个层,等同于[CPU 卸载](#cpu-offloading)。但如果您使用流而不放弃推理速度,它可以更快。
299
+
300
+ ```py
301
+ import torch
302
+ from diffusers import CogVideoXPipeline
303
+ from diffusers.hooks import apply_group_offloading
304
+ from diffusers.utils import export_to_video
305
+
306
+ onload_device = torch.device("cuda")
307
+ offload_device = torch.device("cpu")
308
+ pipeline = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16)
309
+
310
+ # 对 Diffusers 模型实现使用 enable_group_offload 方法
311
+ pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level")
312
+ pipeline.vae.enable_group_offload(onload_device=onload_device, offload_type="leaf_level")
313
+
314
+ # 对其他模型组件使用 apply_group_offloading 方法
315
+ apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2)
316
+
317
+ prompt = (
318
+ "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
319
+ "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
320
+ "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
321
+ "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
322
+ "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
323
+ "atmosphere of this unique musical performance."
324
+ )
325
+ video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
326
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
327
+ export_to_video(video, "output.mp4", fps=8)
328
+ ```
329
+
330
+ #### CUDA 流
331
+ `use_stream` 参数可以激活支持异步数据传输流的 CUDA 设备,以减少整体执行时间,与 [CPU 卸载](#cpu-offloading) 相比。它通过使用层预取重叠数据传输和计算。下一个要执行的层在当前层仍在执行时加载到 GPU 上。这会显著增加 CPU 内存,因此请确保您有模型大小的 2 倍内存。
332
+
333
+ 设置 `record_stream=True` 以获得更多速度提升,代价是内存使用量略有增加。请参阅 [torch.Tensor.record_stream](https://pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html) 文档了解更多信息。
334
+
335
+ > [!TIP]
336
+ > 当 `use_stream=True` 在启用平铺的 VAEs 上时,确保在推理前进行虚拟前向传递(可以使用虚拟输入),以避免设备不匹配错误。这可能不适用于所有实现,因此如果遇到任何问题,请随时提出问题。
337
+
338
+ 如果您在使用启用 `use_stream` 的 `block_level` 组卸载,`num_blocks_per_group` 参数应设置为 `1`,否则会引发警告。
339
+
340
+ ```py
341
+ pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level", use_stream=True, record_stream=True)
342
+ ```
343
+
344
+ `low_cpu_mem_usage` 参数可以设置为 `True`,以在使用流进行组卸载时减少 CPU 内存使用。它最适合 `leaf_level` 卸载和 CPU 内存瓶颈的情况。通过动态创建固定张量而不是预先固定它们来节省内存。然而,这可能会增加整体执行时间。
345
+
346
+ #### 卸载到磁盘
347
+ 组卸载可能会消耗大量系统内存,具体取决于模型大小。在内存有限的系统上,尝试将组卸载到磁盘作为辅助内存。
348
+
349
+ 在 [`~ModelMixin.enable_group_offload`] 或 [`~hooks.apply_group_offloading`] 中设置 `offload_to_disk_path` 参数,将模型卸载到磁盘。
350
+
351
+ ```py
352
+ pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level", offload_to_disk_path="path/to/disk")
353
+
354
+ apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2, offload_to_disk_path="path/to/disk")
355
+ ```
356
+
357
+ 参考这些[两个](https://github.com/huggingface/diffusers/pull/11682#issue-3129365363)[表格](https://github.com/huggingface/diffusers/pull/11682#issuecomment-2955715126)来比较速度和内存的权衡。
358
+
359
+ ## 分层类型转换
360
+
361
+ > [!TIP]
362
+ > 将分层类型转���与[组卸载](#group-offloading)结合使用,以获得更多内存节省。
363
+
364
+ 分层类型转换将权重存储在较小的数据格式中(例如 `torch.float8_e4m3fn` 和 `torch.float8_e5m2`),以使用更少的内存,并在计算时将那些权重上转换为更高精度如 `torch.float16` 或 `torch.bfloat16`。某些层(归一化和调制相关权重)被跳过,因为将它们存储在 fp8 中可能会降低生成质量。
365
+
366
+ > [!WARNING]
367
+ > 如果前向实现包含权重的内部类型转换,分层类型转换可能不适用于所有模型。当前的分层类型转换实现假设前向传递独立于权重精度,并且输入数据类型始终在 `compute_dtype` 中指定(请参见[这里](https://github.com/huggingface/transformers/blob/7f5077e53682ca855afc826162b204ebf809f1f9/src/transformers/models/t5/modeling_t5.py#L294-L299)以获取不兼容的实现)。
368
+ >
369
+ > 分层类型转换也可能在使用[PEFT](https://huggingface.co/docs/peft/index)层的自定义建模实现上失败。有一些检查可用,但它们没有经过广泛测试或保证在所有情况下都能工作。
370
+
371
+ 调用 [`~ModelMixin.enable_layerwise_casting`] 来设置存储和计算数据类型。
372
+
373
+ ```py
374
+ import torch
375
+ from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
376
+ from diffusers.utils import export_to_video
377
+
378
+ transformer = CogVideoXTransformer3DModel.from_pretrained(
379
+ "THUDM/CogVideoX-5b",
380
+ subfolder="transformer",
381
+ torch_dtype=torch.bfloat16
382
+ )
383
+ transformer.enable_layerwise_casting(storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
384
+
385
+ pipeline = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b",
386
+ transformer=transformer,
387
+ torch_dtype=torch.bfloat16
388
+ ).to("cuda")
389
+ prompt = (
390
+ "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
391
+ "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
392
+ "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
393
+ "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
394
+ "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
395
+ "atmosphere of this unique musical performance."
396
+ )
397
+ video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
398
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
399
+ export_to_video(video, "output.mp4", fps=8)
400
+ ```
401
+
402
+ [`~hooks.apply_layerwise_casting`] 方法也可以在您需要更多控制和灵活性时使用。它可以通过在特定内部模块上调用它来部分应用于模型层。使用 `skip_modules_pattern` 或 `skip_modules_classes` 参数来指定要避免的模块,例如归一化和调制层。
403
+
404
+ ```python
405
+ import torch
406
+ from diffusers import CogVideoXTransformer3DModel
407
+ from diffusers.hooks import apply_layerwise_casting
408
+
409
+ transformer = CogVideoXTransformer3DModel.from_pretrained(
410
+ "THUDM/CogVideoX-5b",
411
+ subfolder="transformer",
412
+ torch_dtype=torch.bfloat16
413
+ )
414
+
415
+ # 跳过归一化层
416
+ apply_layerwise_casting(
417
+ transformer,
418
+ storage_dtype=torch.float8_e4m3fn,
419
+ compute_dtype=torch.bfloat16,
420
+ skip_modules_classes=["norm"],
421
+ non_blocking=True,
422
+ )
423
+ ```
424
+
425
+ ## torch.channels_last
426
+
427
+ [torch.channels_last](https://pytorch.org/tutorials/intermediate/memory_format_tutorial.html) 将张量的存储方式从 `(批次大小, 通道数, 高度, 宽度)` 翻转为 `(批次大小, 高度, 宽度, 通道数)`。这使张量与硬件如何顺序访问存储在内存中的张量对齐,并避免了在内存中跳转以访问像素值。
428
+
429
+ 并非所有运算符当前都支持通道最后格式,并且可能导致性能更差,但仍然值得尝试。
430
+
431
+ ```py
432
+ print(pipeline.unet.conv_out.state_dict()["weight"].stride()) # (2880, 9, 3, 1)
433
+ pipeline.unet.to(memory_format=torch.channels_last) # 原地操作
434
+ print(
435
+ pipeline.unet.conv_out.state_dict()["weight"].stride()
436
+ ) # (2880, 1, 960, 320) 第二个维度的跨度为1证明它有效
437
+ ```
438
+
439
+ ## torch.jit.trace
440
+
441
+ [torch.jit.trace](https://pytorch.org/docs/stable/generated/torch.jit.trace.html) 记录模型在样本输入上执行的操作,并根据记录的执行路径创建一个新的、优化的模型表示。在跟踪过程中,模型被优化以减少来自Python和动态控制流的开销,并且操作被融合在一起以提高效率。返回的可执行文件或 [ScriptFunction](https://pytorch.org/docs/stable/generated/torch.jit.ScriptFunction.html) 可以被编译。
442
+
443
+ ```py
444
+ import time
445
+ import torch
446
+ from diffusers import StableDiffusionPipeline
447
+ import functools
448
+
449
+ # torch 禁用梯度
450
+ torch.set_grad_enabled(False)
451
+
452
+ # 设置变量
453
+ n_experiments = 2
454
+ unet_runs_per_experiment = 50
455
+
456
+ # 加载样本输入
457
+ def generate_inputs():
458
+ sample = torch.randn((2, 4, 64, 64), device="cuda", dtype=torch.float16)
459
+ timestep = torch.rand(1, device="cuda", dtype=torch.float16) * 999
460
+ encoder_hidden_states = torch.randn((2, 77, 768), device="cuda", dtype=torch.float16)
461
+ return sample, timestep, encoder_hidden_states
462
+
463
+
464
+ pipeline = StableDiffusionPipeline.from_pretrained(
465
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
466
+ torch_dtype=torch.float16,
467
+ use_safetensors=True,
468
+ ).to("cuda")
469
+ unet = pipeline.unet
470
+ unet.eval()
471
+ unet.to(memory
472
+ _format=torch.channels_last) # 使用 channels_last 内存格式
473
+ unet.forward = functools.partial(unet.forward, return_dict=False) # 设置 return_dict=False 为默认
474
+
475
+ # 预热
476
+ for _ in range(3):
477
+ with torch.inference_mode():
478
+ inputs = generate_inputs()
479
+ orig_output = unet(*inputs)
480
+
481
+ # 追踪
482
+ print("tracing..")
483
+ unet_traced = torch.jit.trace(unet, inputs)
484
+ unet_traced.eval()
485
+ print("done tracing")
486
+
487
+ # 预热和优化图
488
+ for _ in range(5):
489
+ with torch.inference_mode():
490
+ inputs = generate_inputs()
491
+ orig_output = unet_traced(*inputs)
492
+
493
+ # 基准测试
494
+ with torch.inference_mode():
495
+ for _ in range(n_experiments):
496
+ torch.cuda.synchronize()
497
+ start_time = time.time()
498
+ for _ in range(unet_runs_per_experiment):
499
+ orig_output = unet_traced(*inputs)
500
+ torch.cuda.synchronize()
501
+ print(f"unet traced inference took {time.time() - start_time:.2f} seconds")
502
+ for _ in range(n_experiments):
503
+ torch.cuda.synchronize()
504
+ start_time = time.time()
505
+ for _ in range(unet_runs_per_experiment):
506
+ orig_output = unet(*inputs)
507
+ torch.cuda.synchronize()
508
+ print(f"unet inference took {time.time() - start_time:.2f} seconds")
509
+
510
+ # 保存模型
511
+ unet_traced.save("unet_traced.pt")
512
+ ```
513
+
514
+ 替换管道的 UNet 为追踪版本。
515
+
516
+ ```py
517
+ import torch
518
+ from diffusers import StableDiffusionPipeline
519
+ from dataclasses import dataclass
520
+
521
+ @dataclass
522
+ class UNet2DConditionOutput:
523
+ sample: torch.Tensor
524
+
525
+ pipeline = StableDiffusionPipeline.from_pretrained(
526
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
527
+ torch_dtype=torch.float16,
528
+ use_safetensors=True,
529
+ ).to("cuda")
530
+
531
+ # 使用 jitted unet
532
+ unet_traced = torch.jit.load("unet_traced.pt")
533
+
534
+ # del pipeline.unet
535
+ class TracedUNet(torch.nn.Module):
536
+ def __init__(self):
537
+ super().__init__()
538
+ self.in_channels = pipe.unet.config.in_channels
539
+ self.device = pipe.unet.device
540
+
541
+ def forward(self, latent_model_input, t, encoder_hidden_states):
542
+ sample = unet_traced(latent_model_input, t, encoder_hidden_states)[0]
543
+ return UNet2DConditionOutput(sample=sample)
544
+
545
+ pipeline.unet = TracedUNet()
546
+
547
+ with torch.inference_mode():
548
+ image = pipe([prompt] * 1, num_inference_steps=50).images[0]
549
+ ```
550
+
551
+ ## 内存高效注意力
552
+
553
+ > [!TIP]
554
+ > 内存高效注意力优化内存使用 *和* [推理速度](./fp16#scaled-dot-product-attention)!
555
+
556
+ Transformers 注意力机制是内存密集型的,尤其对于长序列,因此您可以尝试使用不同且更内存高效的注意力类型。
557
+
558
+ 默认情况下,如果安装了 PyTorch >= 2.0,则使用 [scaled dot-product attention (SDPA)](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)。您无需对代码进行任何额外更改。
559
+
560
+ SDPA 还支持 [FlashAttention](https://github.com/Dao-AILab/flash-attention) 和 [xFormers](https://github.com/facebookresearch/xformers),以及 a
561
+ 这是一个原生的 C++ PyTorch 实现。它会根据您的输入自动选择最优的实现。
562
+
563
+ 您可以使用 [`~ModelMixin.enable_xformers_memory_efficient_attention`] 方法显式地使用 xFormers。
564
+
565
+ ```py
566
+ # pip install xformers
567
+ import torch
568
+ from diffusers import StableDiffusionXLPipeline
569
+
570
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
571
+ "stabilityai/stable-diffusion-xl-base-1.0",
572
+ torch_dtype=torch.float16,
573
+ ).to("cuda")
574
+ pipeline.enable_xformers_memory_efficient_attention()
575
+ ```
576
+
577
+ 调用 [`~ModelMixin.disable_xformers_memory_efficient_attention`] 来禁用它。
578
+
579
+ ```py
580
+ pipeline.disable_xformers_memory_efficient_attention()
581
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/mps.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版本("许可证")授权;除非遵守许可证,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。请参阅许可证了解具体的语言管理权限和限制。
8
+ -->
9
+
10
+ # Metal Performance Shaders (MPS)
11
+
12
+ > [!TIP]
13
+ > 带有 <img alt="MPS" src="https://img.shields.io/badge/MPS-000000?style=flat&logo=apple&logoColor=white%22"> 徽章的管道表示模型可以利用 Apple silicon 设备上的 MPS 后端进行更快的推理。欢迎提交 [Pull Request](https://github.com/huggingface/diffusers/compare) 来为缺少此徽章的管道添加它。
14
+
15
+ 🤗 Diffusers 与 Apple silicon(M1/M2 芯片)兼容,使用 PyTorch 的 [`mps`](https://pytorch.org/docs/stable/notes/mps.html) 设备,该设备利用 Metal 框架来发挥 MacOS 设备上 GPU 的性能。您需要具备:
16
+
17
+ - 配备 Apple silicon(M1/M2)硬件的 macOS 计算机
18
+ - macOS 12.6 或更高版本(推荐 13.0 或更高)
19
+ - arm64 版本的 Python
20
+ - [PyTorch 2.0](https://pytorch.org/get-started/locally/)(推荐)或 1.13(支持 `mps` 的最低版本)
21
+
22
+ `mps` 后端使用 PyTorch 的 `.to()` 接口将 Stable Diffusion 管道移动到您的 M1 或 M2 设备上:
23
+
24
+ ```python
25
+ from diffusers import DiffusionPipeline
26
+
27
+ pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
28
+ pipe = pipe.to("mps")
29
+
30
+ # 如果您的计算机内存小于 64 GB,推荐使用
31
+ pipe.enable_attention_slicing()
32
+
33
+ prompt = "a photo of an astronaut riding a horse on mars"
34
+ image = pipe(prompt).images[0]
35
+ image
36
+ ```
37
+
38
+ > [!WARNING]
39
+ > PyTorch [mps](https://pytorch.org/docs/stable/notes/mps.html) 后端不支持大小超过 `2**32` 的 NDArray。如果您遇到此问题,请提交 [Issue](https://github.com/huggingface/diffusers/issues/new/choose) 以便我们调查。
40
+
41
+ 如果您使用 **PyTorch 1.13**,您需要通过管道进行一次额外的"预热"传递。这是一个临时解决方法,用于解决首次推理传递产生的结果与后续传递略有不同的问题。您只需要执行此传递一次,并且在仅进行一次推理步骤后可以丢弃结果。
42
+
43
+ ```diff
44
+ from diffusers import DiffusionPipeline
45
+
46
+ pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5").to("mps")
47
+ pipe.enable_attention_slicing()
48
+
49
+ prompt = "a photo of an astronaut riding a horse on mars"
50
+ # 如果 PyTorch 版本是 1.13,进行首次"预热"传递
51
+ + _ = pipe(prompt, num_inference_steps=1)
52
+
53
+ # 预热传递后,结果与 CPU 设备上的结果匹配。
54
+ image = pipe(prompt).images[0]
55
+ ```
56
+
57
+ ## 故障排除
58
+
59
+ 本节列出了使用 `mps` 后端时的一些常见问题及其解决方法。
60
+
61
+ ### 注意力切片
62
+
63
+ M1/M2 性能对内存压力非常敏感。当发生这种情况时,系统会自动交换内存,这会显著降低性能。
64
+
65
+ 为了防止这种情况发生,我们建议使用*注意力切片*来减少推理过程中的内存压力并防止交换。这在您的计算机系统内存少于 64GB 或生成非标准分辨率(大于 512×512 像素)的图像时尤其相关。在您的管道上调用 [`~DiffusionPipeline.enable_attention_slicing`] 函数:
66
+
67
+ ```py
68
+ from diffusers import DiffusionPipeline
69
+ import torch
70
+
71
+ pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True).to("mps")
72
+ pipeline.enable_attention_slicing()
73
+ ```
74
+
75
+ 注意力切片将昂贵的注意力操作分多个步骤执行,而不是一次性完成。在没有统一内存的计算机中,它通常能提高约 20% 的性能,但我们观察到在大多数 Apple 芯片计算机中,除非您有 64GB 或更多 RAM,否则性能会*更好*。
76
+
77
+ ### 批量推理
78
+
79
+ 批量生成多个提示可能会导致崩溃或无法可靠工作。如果是这种情况,请尝试迭代而不是批量处理。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/neuron.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 The HuggingFace Team。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版(“许可证”)授权;除非遵守许可证,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,根据许可证分发的软件按“原样”分发,无任何明示或暗示的担保或条件。请参阅许可证了解特定语言管理权限和限制。
8
+ -->
9
+
10
+ # AWS Neuron
11
+
12
+ Diffusers 功能可在 [AWS Inf2 实例](https://aws.amazon.com/ec2/instance-types/inf2/)上使用,这些是由 [Neuron 机器学习加速器](https://aws.amazon.com/machine-learning/inferentia/)驱动的 EC2 实例。这些实例旨在提供更好的计算性能(更高的吞吐量、更低的延迟)和良好的成本效益,使其成为 AWS 用户将扩散模型部署到生产环境的良好选择。
13
+
14
+ [Optimum Neuron](https://huggingface.co/docs/optimum-neuron/en/index) 是 Hugging Face 库与 AWS 加速器之间的接口,包括 AWS [Trainium](https://aws.amazon.com/machine-learning/trainium/) 和 AWS [Inferentia](https://aws.amazon.com/machine-learning/inferentia/)。它支持 Diffusers 中的许多功能,并具有类似的 API,因此如果您已经熟悉 Diffusers,学习起来更容易。一旦您创建了 AWS Inf2 实例,请安装 Optimum Neuron。
15
+
16
+ ```bash
17
+ python -m pip install --upgrade-strategy eager optimum[neuronx]
18
+ ```
19
+
20
+ > [!TIP]
21
+ > 我们提供预构建的 [Hugging Face Neuron 深度学习 AMI](https://aws.amazon.com/marketplace/pp/prodview-gr3e6yiscria2)(DLAMI)和用于 Amazon SageMaker 的 Optimum Neuron 容器。建议正确设置您的环境。
22
+
23
+ 下面的示例演示了如何在 inf2.8xlarge 实例上使用 Stable Diffusion XL 模型生成图像(一旦模型编译完成,您可以切换到更便宜的 inf2.xlarge 实例)。要生成一些图像,请使用 [`~optimum.neuron.NeuronStableDiffusionXLPipeline`] 类,该类类似于 Diffusers 中的 [`StableDiffusionXLPipeline`] 类。
24
+
25
+ 与 Diffusers 不同,您需要将管道中的模型编译为 Neuron 格式,即 `.neuron`。运行以下命令将模型导出为 `.neuron` 格式。
26
+
27
+ ```bash
28
+ optimum-cli export neuron --model stabilityai/stable-diffusion-xl-base-1.0 \
29
+ --batch_size 1 \
30
+ --height 1024 `# 生成图像的高度(像素),例如 768, 1024` \
31
+ --width 1024 `# 生成图像的宽度(像素),例如 768, 1024` \
32
+ --num_images_per_prompt 1 `# 每个提示生成的图像数量,默认为 1` \
33
+ --auto_cast matmul `# 仅转换矩阵乘法操作` \
34
+ --auto_cast_type bf16 `# 将操作从 FP32 转换为 BF16` \
35
+ sd_neuron_xl/
36
+ ```
37
+
38
+ 现在使用预编译的 SDXL 模型生成一些图像。
39
+
40
+ ```python
41
+ >>> from optimum.neuron import Neu
42
+ ronStableDiffusionXLPipeline
43
+
44
+ >>> stable_diffusion_xl = NeuronStableDiffusionXLPipeline.from_pretrained("sd_neuron_xl/")
45
+ >>> prompt = "a pig with wings flying in floating US dollar banknotes in the air, skyscrapers behind, warm color palette, muted colors, detailed, 8k"
46
+ >>> image = stable_diffusion_xl(prompt).images[0]
47
+ ```
48
+
49
+ <img
50
+ src="https://huggingface.co/datasets/Jingya/document_images/resolve/main/optimum/neuron/sdxl_pig.png"
51
+ width="256"
52
+ height="256"
53
+ alt="peggy generated by sdxl on inf2"
54
+ />
55
+
56
+ 欢迎查看Optimum Neuron [文档](https://huggingface.co/docs/optimum-neuron/en/inference_tutorials/stable_diffusion#generate-images-with-stable-diffusion-models-on-aws-inferentia)中更多不同用例的指南和示例!
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/onnx.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ 根据 Apache License 2.0 许可证(以下简称"许可证")授权,除非符合许可证要求,否则不得使用本文件。您可以通过以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或以书面形式同意,本软件按"原样"分发,不附带任何明示或暗示的担保或条件。详见许可证中规定的特定语言权限和限制。
8
+ -->
9
+
10
+ # ONNX Runtime
11
+
12
+ 🤗 [Optimum](https://github.com/huggingface/optimum) 提供了兼容 ONNX Runtime 的 Stable Diffusion 流水线。您需要运行以下命令安装支持 ONNX Runtime 的 🤗 Optimum:
13
+
14
+ ```bash
15
+ pip install -q optimum["onnxruntime"]
16
+ ```
17
+
18
+ 本指南将展示如何使用 ONNX Runtime 运行 Stable Diffusion 和 Stable Diffusion XL (SDXL) 流水线。
19
+
20
+ ## Stable Diffusion
21
+
22
+ 要加载并运行推理,请使用 [`~optimum.onnxruntime.ORTStableDiffusionPipeline`]。若需加载 PyTorch 模型并实时转换为 ONNX 格式,请设置 `export=True`:
23
+
24
+ ```python
25
+ from optimum.onnxruntime import ORTStableDiffusionPipeline
26
+
27
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
28
+ pipeline = ORTStableDiffusionPipeline.from_pretrained(model_id, export=True)
29
+ prompt = "sailing ship in storm by Leonardo da Vinci"
30
+ image = pipeline(prompt).images[0]
31
+ pipeline.save_pretrained("./onnx-stable-diffusion-v1-5")
32
+ ```
33
+
34
+ > [!WARNING]
35
+ > 当前批量生成多个提示可能会占用过高内存。在问题修复前,建议采用迭代方式而非批量处理。
36
+
37
+ 如需离线导出 ONNX 格式流水线供后续推理使用,请使用 [`optimum-cli export`](https://huggingface.co/docs/optimum/main/en/exporters/onnx/usage_guides/export_a_model#exporting-a-model-to-onnx-using-the-cli) 命令:
38
+
39
+ ```bash
40
+ optimum-cli export onnx --model stable-diffusion-v1-5/stable-diffusion-v1-5 sd_v15_onnx/
41
+ ```
42
+
43
+ 随后进行推理时(无需再次指定 `export=True`):
44
+
45
+ ```python
46
+ from optimum.onnxruntime import ORTStableDiffusionPipeline
47
+
48
+ model_id = "sd_v15_onnx"
49
+ pipeline = ORTStableDiffusionPipeline.from_pretrained(model_id)
50
+ prompt = "sailing ship in storm by Leonardo da Vinci"
51
+ image = pipeline(prompt).images[0]
52
+ ```
53
+
54
+ <div class="flex justify-center">
55
+ <img src="https://huggingface.co/datasets/optimum/documentation-images/resolve/main/onnxruntime/stable_diffusion_v1_5_ort_sail_boat.png">
56
+ </div>
57
+
58
+ 您可以在 🤗 Optimum [文档](https://huggingface.co/docs/optimum/) 中找到更多示例,Stable Diffusion 支持文生图、图生图和图像修复任务。
59
+
60
+ ## Stable Diffusion XL
61
+
62
+ 要加载并运行 SDXL 推理,请使用 [`~optimum.onnxruntime.ORTStableDiffusionXLPipeline`]:
63
+
64
+ ```python
65
+ from optimum.onnxruntime import ORTStableDiffusionXLPipeline
66
+
67
+ model_id = "stabilityai/stable-diffusion-xl-base-1.0"
68
+ pipeline = ORTStableDiffusionXLPipeline.from_pretrained(model_id)
69
+ prompt = "sailing ship in storm by Leonardo da Vinci"
70
+ image = pipeline(prompt).images[0]
71
+ ```
72
+
73
+ 如需导出 ONNX 格式流水线供后续推理使用,请运行:
74
+
75
+ ```bash
76
+ optimum-cli export onnx --model stabilityai/stable-diffusion-xl-base-1.0 --task stable-diffusion-xl sd_xl_onnx/
77
+ ```
78
+
79
+ SDXL 的 ONNX 格式目前支持文生图和图生图任务。
tasks/tasksmith-ee553a5e62c1/environment/source/docs/source/zh/optimization/open_vino.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--版权所有 2025 HuggingFace 团队。保留所有权利。
2
+
3
+ 根据 Apache 许可证 2.0 版本("许可证")授权;除非遵守许可证,否则不得使用此文件。您可以在以下网址获取许可证副本:
4
+
5
+ http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ 除非适用法律要求或书面同意,根据许可证分发的软件按"原样"分发,无任何明示或暗示的担保或条件。请参阅许可证以了解具体的语言管理权限和限制。
8
+ -->
9
+
10
+ # OpenVINO
11
+
12
+ 🤗 [Optimum](https://github.com/huggingface/optimum-intel) 提供与 OpenVINO 兼容的 Stable Diffusion 管道,可在各种 Intel 处理器上执行推理(请参阅支持的设备[完整列表](https://docs.openvino.ai/latest/openvino_docs_OV_UG_supported_plugins_Supported_Devices.html))。
13
+
14
+ 您需要安装 🤗 Optimum Intel,并使用 `--upgrade-strategy eager` 选项以确保 [`optimum-intel`](https://github.com/huggingface/optimum-intel) 使用最新版本:
15
+
16
+ ```bash
17
+ pip install --upgrade-strategy eager optimum["openvino"]
18
+ ```
19
+
20
+ 本指南将展示如何使用 Stable Diffusion 和 Stable Diffusion XL (SDXL) 管道与 OpenVINO。
21
+
22
+ ## Stable Diffusion
23
+
24
+ 要加载并运行推理,请使用 [`~optimum.intel.OVStableDiffusionPipeline`]。如果您想加载 PyTorch 模型并即时转换为 OpenVINO 格式,请设置 `export=True`:
25
+
26
+ ```python
27
+ from optimum.intel import OVStableDiffusionPipeline
28
+
29
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
30
+ pipeline = OVStableDiffusionPipeline.from_pretrained(model_id, export=True)
31
+ prompt = "sailing ship in storm by Rembrandt"
32
+ image = pipeline(prompt).images[0]
33
+
34
+ # 别忘了保存导出的模型
35
+ pipeline.save_pretrained("openvino-sd-v1-5")
36
+ ```
37
+
38
+ 为了进一步加速推理,静态重塑模型。如果您更改任何参数,例如输出高度或宽度,您需要再次静态重塑模型。
39
+
40
+ ```python
41
+ # 定义与输入和期望输出相关的形状
42
+ batch_size, num_images, height, width = 1, 1, 512, 512
43
+
44
+ # 静态重塑模型
45
+ pipeline.reshape(batch_size, height, width, num_images)
46
+ # 在推理前编译模型
47
+ pipeline.compile()
48
+
49
+ image = pipeline(
50
+ prompt,
51
+ height=height,
52
+ width=width,
53
+ num_images_per_prompt=num_images,
54
+ ).images[0]
55
+ ```
56
+ <div class="flex justify-center">
57
+ <img src="https://huggingface.co/datasets/optimum/documentation-images/resolve/main/intel/openvino/stable_diffusion_v1_5_sail_boat_rembrandt.png">
58
+ </div>
59
+
60
+ 您可以在 🤗 Optimum [文档](https://huggingface.co/docs/optimum/intel/inference#stable-diffusion) 中找到更多示例,Stable Diffusion 支持文本到图像、图像到图像和修复。
61
+
62
+ ## Stable Diffusion XL
63
+
64
+ 要加载并运行 SDXL 推理,请使用 [`~optimum.intel.OVStableDiffusionXLPipeline`]:
65
+
66
+ ```python
67
+ from optimum.intel import OVStableDiffusionXLPipeline
68
+
69
+ model_id = "stabilityai/stable-diffusion-xl-base-1.0"
70
+ pipeline = OVStableDiffusionXLPipeline.from_pretrained(model_id)
71
+ prompt = "sailing ship in storm by Rembrandt"
72
+ image = pipeline(prompt).images[0]
73
+ ```
74
+
75
+ 为了进一步加速推理,可以如Stable Diffusion部分所示[静态重塑](#stable-diffusion)模型。
76
+
77
+ 您可以在🤗 Optimum[文档](https://huggingface.co/docs/optimum/intel/inference#stable-diffusion-xl)中找到更多示例,并且在OpenVINO中运行SDXL支持文本到图像和图像到图像。