Unverified Commit 468ae09e authored by Tolga Cangöz's avatar Tolga Cangöz Committed by GitHub
Browse files

Errata - Trim trailing white space in the whole repo (#8575)



* Trim all the trailing white space in the whole repo

* Remove unnecessary empty places

* make style && make quality

* Trim trailing white space

* trim

---------
Co-authored-by: default avatarSayak Paul <spsayakpaul@gmail.com>
parent 3fca5202
...@@ -55,7 +55,7 @@ To learn more, take a look at the [Distributed Inference with 🤗 Accelerate](h ...@@ -55,7 +55,7 @@ To learn more, take a look at the [Distributed Inference with 🤗 Accelerate](h
### Device placement ### Device placement
> [!WARNING] > [!WARNING]
> This feature is experimental and its APIs might change in the future. > This feature is experimental and its APIs might change in the future.
With Accelerate, you can use the `device_map` to determine how to distribute the models of a pipeline across multiple devices. This is useful in situations where you have more than one GPU. With Accelerate, you can use the `device_map` to determine how to distribute the models of a pipeline across multiple devices. This is useful in situations where you have more than one GPU.
...@@ -90,8 +90,8 @@ import torch ...@@ -90,8 +90,8 @@ import torch
max_memory = {0:"1GB", 1:"1GB"} max_memory = {0:"1GB", 1:"1GB"}
pipeline = DiffusionPipeline.from_pretrained( pipeline = DiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", "runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16, torch_dtype=torch.float16,
use_safetensors=True, use_safetensors=True,
device_map="balanced", device_map="balanced",
+ max_memory=max_memory + max_memory=max_memory
) )
...@@ -99,7 +99,7 @@ image = pipeline("a dog").images[0] ...@@ -99,7 +99,7 @@ image = pipeline("a dog").images[0]
image image
``` ```
If a device is not present in `max_memory`, then it will be completely ignored and will not participate in the device placement. If a device is not present in `max_memory`, then it will be completely ignored and will not participate in the device placement.
By default, Diffusers uses the maximum memory of all devices. If the models don't fit on the GPUs, they are offloaded to the CPU. If the CPU doesn't have enough memory, then you might see an error. In that case, you could defer to using [`~DiffusionPipeline.enable_sequential_cpu_offload`] and [`~DiffusionPipeline.enable_model_cpu_offload`]. By default, Diffusers uses the maximum memory of all devices. If the models don't fit on the GPUs, they are offloaded to the CPU. If the CPU doesn't have enough memory, then you might see an error. In that case, you could defer to using [`~DiffusionPipeline.enable_sequential_cpu_offload`] and [`~DiffusionPipeline.enable_model_cpu_offload`].
......
...@@ -533,7 +533,7 @@ python train_dreambooth_lora.py \ ...@@ -533,7 +533,7 @@ python train_dreambooth_lora.py \
--resolution=256 \ --resolution=256 \
--train_batch_size=4 \ --train_batch_size=4 \
--gradient_accumulation_steps=1 \ --gradient_accumulation_steps=1 \
--learning_rate=1e-6 \ --learning_rate=1e-6 \
--max_train_steps=2000 \ --max_train_steps=2000 \
--validation_prompt="a sks dog" \ --validation_prompt="a sks dog" \
--validation_epochs=100 \ --validation_epochs=100 \
......
...@@ -222,7 +222,7 @@ First, configure all the compiler tags: ...@@ -222,7 +222,7 @@ First, configure all the compiler tags:
```python ```python
from diffusers import StableDiffusionXLPipeline from diffusers import StableDiffusionXLPipeline
import torch import torch
# Notice the two new flags at the end. # Notice the two new flags at the end.
torch._inductor.config.conv_1x1_as_mm = True torch._inductor.config.conv_1x1_as_mm = True
......
...@@ -506,7 +506,7 @@ make_image_grid([original_image, canny_image], rows=1, cols=2) ...@@ -506,7 +506,7 @@ make_image_grid([original_image, canny_image], rows=1, cols=2)
</div> </div>
For human pose estimation, install [controlnet_aux](https://github.com/patrickvonplaten/controlnet_aux): For human pose estimation, install [controlnet_aux](https://github.com/patrickvonplaten/controlnet_aux):
```py ```py
# uncomment to install the necessary library in Colab # uncomment to install the necessary library in Colab
#!pip install -q controlnet-aux #!pip install -q controlnet-aux
......
...@@ -147,11 +147,11 @@ prompt = "cat, hiding in the leaves, ((rain)), zazie rainyday, beautiful eyes, m ...@@ -147,11 +147,11 @@ prompt = "cat, hiding in the leaves, ((rain)), zazie rainyday, beautiful eyes, m
neg_prompt = "(deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime, mutated hands and fingers:1.4), (deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated, ugly, disgusting, amputation" neg_prompt = "(deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime, mutated hands and fingers:1.4), (deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated, ugly, disgusting, amputation"
generator = torch.Generator(device="cpu").manual_seed(20) generator = torch.Generator(device="cpu").manual_seed(20)
out_lpw = pipe_lpw( out_lpw = pipe_lpw(
prompt, prompt,
negative_prompt=neg_prompt, negative_prompt=neg_prompt,
width=512, width=512,
height=512, height=512,
max_embeddings_multiples=3, max_embeddings_multiples=3,
num_inference_steps=50, num_inference_steps=50,
generator=generator, generator=generator,
).images[0] ).images[0]
......
...@@ -235,7 +235,7 @@ image = pipe( ...@@ -235,7 +235,7 @@ image = pipe(
mask_image=mask_image, mask_image=mask_image,
generator=generator, generator=generator,
num_inference_steps=4, num_inference_steps=4,
guidance_scale=4, guidance_scale=4,
).images[0] ).images[0]
image image
``` ```
...@@ -497,7 +497,7 @@ pipe = StableDiffusionXLAdapterPipeline.from_pretrained( ...@@ -497,7 +497,7 @@ pipe = StableDiffusionXLAdapterPipeline.from_pretrained(
unet=unet, unet=unet,
adapter=adapter, adapter=adapter,
torch_dtype=torch.float16, torch_dtype=torch.float16,
variant="fp16", variant="fp16",
).to("cuda") ).to("cuda")
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
...@@ -512,7 +512,7 @@ image = pipe( ...@@ -512,7 +512,7 @@ image = pipe(
image=canny_image, image=canny_image,
num_inference_steps=4, num_inference_steps=4,
guidance_scale=5, guidance_scale=5,
adapter_conditioning_scale=0.8, adapter_conditioning_scale=0.8,
adapter_conditioning_factor=1, adapter_conditioning_factor=1,
generator=generator, generator=generator,
).images[0] ).images[0]
...@@ -554,10 +554,10 @@ canny_image = Image.fromarray(image).resize((1024, 1024)) ...@@ -554,10 +554,10 @@ canny_image = Image.fromarray(image).resize((1024, 1024))
adapter = T2IAdapter.from_pretrained("TencentARC/t2i-adapter-canny-sdxl-1.0", torch_dtype=torch.float16, varient="fp16").to("cuda") adapter = T2IAdapter.from_pretrained("TencentARC/t2i-adapter-canny-sdxl-1.0", torch_dtype=torch.float16, varient="fp16").to("cuda")
pipe = StableDiffusionXLAdapterPipeline.from_pretrained( pipe = StableDiffusionXLAdapterPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", "stabilityai/stable-diffusion-xl-base-1.0",
adapter=adapter, adapter=adapter,
torch_dtype=torch.float16, torch_dtype=torch.float16,
variant="fp16", variant="fp16",
).to("cuda") ).to("cuda")
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
...@@ -573,8 +573,8 @@ image = pipe( ...@@ -573,8 +573,8 @@ image = pipe(
negative_prompt=negative_prompt, negative_prompt=negative_prompt,
image=canny_image, image=canny_image,
num_inference_steps=4, num_inference_steps=4,
guidance_scale=1.5, guidance_scale=1.5,
adapter_conditioning_scale=0.8, adapter_conditioning_scale=0.8,
adapter_conditioning_factor=1, adapter_conditioning_factor=1,
generator=generator, generator=generator,
).images[0] ).images[0]
......
...@@ -445,8 +445,8 @@ generator = torch.Generator(device="cpu").manual_seed(42) ...@@ -445,8 +445,8 @@ generator = torch.Generator(device="cpu").manual_seed(42)
images = pipeline( images = pipeline(
prompt="A photo of a girl", prompt="A photo of a girl",
ip_adapter_image_embeds=[id_embeds], ip_adapter_image_embeds=[id_embeds],
negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality", negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
num_inference_steps=20, num_images_per_prompt=1, num_inference_steps=20, num_images_per_prompt=1,
generator=generator generator=generator
).images ).images
...@@ -661,7 +661,7 @@ image ...@@ -661,7 +661,7 @@ image
### Style & layout control ### Style & layout control
[InstantStyle](https://arxiv.org/abs/2404.02733) is a plug-and-play method on top of IP-Adapter, which disentangles style and layout from image prompt to control image generation. This way, you can generate images following only the style or layout from image prompt, with significantly improved diversity. This is achieved by only activating IP-Adapters to specific parts of the model. [InstantStyle](https://arxiv.org/abs/2404.02733) is a plug-and-play method on top of IP-Adapter, which disentangles style and layout from image prompt to control image generation. This way, you can generate images following only the style or layout from image prompt, with significantly improved diversity. This is achieved by only activating IP-Adapters to specific parts of the model.
By default IP-Adapters are inserted to all layers of the model. Use the [`~loaders.IPAdapterMixin.set_ip_adapter_scale`] method with a dictionary to assign scales to IP-Adapter at different layers. By default IP-Adapters are inserted to all layers of the model. Use the [`~loaders.IPAdapterMixin.set_ip_adapter_scale`] method with a dictionary to assign scales to IP-Adapter at different layers.
......
...@@ -81,14 +81,14 @@ pipeline = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffu ...@@ -81,14 +81,14 @@ pipeline = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffu
Use the Space below to gauge a pipeline's memory requirements before you download and load it to see if it runs on your hardware. Use the Space below to gauge a pipeline's memory requirements before you download and load it to see if it runs on your hardware.
<div class="block dark:hidden"> <div class="block dark:hidden">
<iframe <iframe
src="https://diffusers-compute-pipeline-size.hf.space?__theme=light" src="https://diffusers-compute-pipeline-size.hf.space?__theme=light"
width="850" width="850"
height="1600" height="1600"
></iframe> ></iframe>
</div> </div>
<div class="hidden dark:block"> <div class="hidden dark:block">
<iframe <iframe
src="https://diffusers-compute-pipeline-size.hf.space?__theme=dark" src="https://diffusers-compute-pipeline-size.hf.space?__theme=dark"
width="850" width="850"
height="1600" height="1600"
...@@ -138,11 +138,11 @@ Now pass the new scheduler and VAE to the [`StableDiffusionXLPipeline`]. ...@@ -138,11 +138,11 @@ Now pass the new scheduler and VAE to the [`StableDiffusionXLPipeline`].
```py ```py
pipeline = StableDiffusionXLPipeline.from_pretrained( pipeline = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", "stabilityai/stable-diffusion-xl-base-1.0",
scheduler=scheduler, scheduler=scheduler,
vae=vae, vae=vae,
torch_dtype=torch.float16, torch_dtype=torch.float16,
variant="fp16", variant="fp16",
use_safetensors=True use_safetensors=True
).to("cuda") ).to("cuda")
``` ```
...@@ -178,7 +178,7 @@ pipe_sd.to("cuda") ...@@ -178,7 +178,7 @@ pipe_sd.to("cuda")
generator = torch.Generator(device="cpu").manual_seed(33) generator = torch.Generator(device="cpu").manual_seed(33)
out_sd = pipe_sd( out_sd = pipe_sd(
prompt="bear eats pizza", prompt="bear eats pizza",
negative_prompt="wrong white balance, dark, sketches,worst quality,low quality", negative_prompt="wrong white balance, dark, sketches,worst quality,low quality",
ip_adapter_image=image, ip_adapter_image=image,
num_inference_steps=50, num_inference_steps=50,
generator=generator, generator=generator,
...@@ -284,7 +284,7 @@ pipe.sag_unload_ip_adapter() ...@@ -284,7 +284,7 @@ pipe.sag_unload_ip_adapter()
generator = torch.Generator(device="cpu").manual_seed(33) generator = torch.Generator(device="cpu").manual_seed(33)
out_sd = pipe_sd( out_sd = pipe_sd(
prompt="bear eats pizza", prompt="bear eats pizza",
negative_prompt="wrong white balance, dark, sketches,worst quality,low quality", negative_prompt="wrong white balance, dark, sketches,worst quality,low quality",
ip_adapter_image=image, ip_adapter_image=image,
num_inference_steps=50, num_inference_steps=50,
generator=generator, generator=generator,
......
...@@ -166,7 +166,7 @@ For both [`~loaders.LoraLoaderMixin.load_lora_weights`] and [`~loaders.UNet2DCon ...@@ -166,7 +166,7 @@ For both [`~loaders.LoraLoaderMixin.load_lora_weights`] and [`~loaders.UNet2DCon
For more granular control on the amount of LoRA weights used per layer, you can use [`~loaders.LoraLoaderMixin.set_adapters`] and pass a dictionary specifying by how much to scale the weights in each layer by. For more granular control on the amount of LoRA weights used per layer, you can use [`~loaders.LoraLoaderMixin.set_adapters`] and pass a dictionary specifying by how much to scale the weights in each layer by.
```python ```python
pipe = ... # create pipeline pipe = ... # create pipeline
pipe.load_lora_weights(..., adapter_name="my_adapter") pipe.load_lora_weights(..., adapter_name="my_adapter")
scales = { scales = {
"text_encoder": 0.5, "text_encoder": 0.5,
"text_encoder_2": 0.5, # only usable if pipe has a 2nd text encoder "text_encoder_2": 0.5, # only usable if pipe has a 2nd text encoder
......
...@@ -71,7 +71,7 @@ import torch ...@@ -71,7 +71,7 @@ import torch
unet = UNet2DConditionModel.from_pretrained( unet = UNet2DConditionModel.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", "stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16, torch_dtype=torch.float16,
use_safetensors=True, use_safetensors=True,
variant="fp16", variant="fp16",
subfolder="unet", subfolder="unet",
...@@ -138,7 +138,7 @@ from peft import PeftModel ...@@ -138,7 +138,7 @@ from peft import PeftModel
base_unet = UNet2DConditionModel.from_pretrained( base_unet = UNet2DConditionModel.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", "stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16, torch_dtype=torch.float16,
use_safetensors=True, use_safetensors=True,
variant="fp16", variant="fp16",
subfolder="unet", subfolder="unet",
......
...@@ -472,7 +472,6 @@ my_local_config_path = snapshot_download( ...@@ -472,7 +472,6 @@ my_local_config_path = snapshot_download(
local_dir_use_symlinks=False, local_dir_use_symlinks=False,
) )
print("My local config: ", my_local_config_path) print("My local config: ", my_local_config_path)
``` ```
Then you can pass the local paths to the `pretrained_model_link_or_path` and `config` parameters. Then you can pass the local paths to the `pretrained_model_link_or_path` and `config` parameters.
......
...@@ -63,7 +63,7 @@ from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipelin ...@@ -63,7 +63,7 @@ from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipelin
import torch import torch
pipeline = StableDiffusionXLPipeline.from_single_file( pipeline = StableDiffusionXLPipeline.from_single_file(
"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors", "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
torch_dtype=torch.float16 torch_dtype=torch.float16
).to("cuda") ).to("cuda")
......
...@@ -155,7 +155,7 @@ def get_inputs(batch_size=1): ...@@ -155,7 +155,7 @@ def get_inputs(batch_size=1):
`batch_size=4`で開始し、どれだけメモリを消費したかを確認します: `batch_size=4`で開始し、どれだけメモリを消費したかを確認します:
```python ```python
from diffusers.utils import make_image_grid from diffusers.utils import make_image_grid
images = pipeline(**get_inputs(batch_size=4)).images images = pipeline(**get_inputs(batch_size=4)).images
make_image_grid(images, 2, 2) make_image_grid(images, 2, 2)
......
...@@ -22,7 +22,7 @@ specific language governing permissions and limitations under the License. ...@@ -22,7 +22,7 @@ specific language governing permissions and limitations under the License.
## 개요 ## 개요
이슈에 있는 질문에 답변하는 것에서부터 코어 라이브러리에 새로운 diffusion 모델을 추가하는 것까지 다양한 방법으로 기여를 할 수 있습니다. 이슈에 있는 질문에 답변하는 것에서부터 코어 라이브러리에 새로운 diffusion 모델을 추가하는 것까지 다양한 방법으로 기여를 할 수 있습니다.
이어지는 부분에서 우리는 다양한 방법의 기여에 대한 개요를 난이도에 따라 오름차순으로 정리하였습니다. 모든 기여는 커뮤니티에게 가치가 있습니다. 이어지는 부분에서 우리는 다양한 방법의 기여에 대한 개요를 난이도에 따라 오름차순으로 정리하였습니다. 모든 기여는 커뮤니티에게 가치가 있습니다.
...@@ -94,7 +94,7 @@ Diffusers 라이브러리와 관련된 모든 질문이나 의견은 [토론 포 ...@@ -94,7 +94,7 @@ Diffusers 라이브러리와 관련된 모든 질문이나 의견은 [토론 포
- 이슈를 설명해야 합니다. 독자가 문제가 무엇이며 왜 문제인지 모르면 해결할 수 없습니다. - 이슈를 설명해야 합니다. 독자가 문제가 무엇이며 왜 문제인지 모르면 해결할 수 없습니다.
- **항상** 독자가 가능한 한 적은 노력으로 문제를 재현할 수 있도록 해야 합니다. 코드 조각이 라이브러리가 없거나 정의되지 않은 변수 때문에 실행되지 않는 경우 독자가 도움을 줄 수 없습니다. 재현 가능한 코드 조각이 가능한 한 최소화되고 간단한 Python 셸에 복사하여 붙여넣을 수 있도록 해야 합니다. - **항상** 독자가 가능한 한 적은 노력으로 문제를 재현할 수 있도록 해야 합니다. 코드 조각이 라이브러리가 없거나 정의되지 않은 변수 때문에 실행되지 않는 경우 독자가 도움을 줄 수 없습니다. 재현 가능한 코드 조각이 가능한 한 최소화되고 간단한 Python 셸에 복사하여 붙여넣을 수 있도록 해야 합니다.
- 문제를 재현하기 위해 모델과/또는 데이터셋이 필요한 경우 독자가 해당 모델이나 데이터셋에 접근할 수 있도록 해야 합니다. 모델이나 데이터셋을 [Hub](https://huggingface.co)에 업로드하여 쉽게 다운로드할 수 있도록 할 수 있습니다. 문제 재현을 가능한 한 쉽게하기 위해 모델과 데이터셋을 가능한 한 작게 유지하려고 노력하세요. - 문제를 재현하기 위해 모델과/또는 데이터셋이 필요한 경우 독자가 해당 모델이나 데이터셋에 접근할 수 있도록 해야 합니다. 모델이나 데이터셋을 [Hub](https://huggingface.co)에 업로드하여 쉽게 다운로드할 수 있도록 할 수 있습니다. 문제 재현을 가능한 한 쉽게하기 위해 모델과 데이터셋을 가능한 한 작게 유지하려고 노력하세요.
자세한 내용은 [좋은 이슈 작성 방법](#how-to-write-a-good-issue) 섹션을 참조하세요. 자세한 내용은 [좋은 이슈 작성 방법](#how-to-write-a-good-issue) 섹션을 참조하세요.
버그 보고서를 열려면 [여기](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&projects=&template=bug-report.yml)를 클릭하세요. 버그 보고서를 열려면 [여기](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&projects=&template=bug-report.yml)를 클릭하세요.
...@@ -151,7 +151,7 @@ GitHub에서 이슈에 대한 답변을 하기 위해서는 Diffusers에 대한 ...@@ -151,7 +151,7 @@ GitHub에서 이슈에 대한 답변을 하기 위해서는 Diffusers에 대한
이슈가 올바른 버그 보고서이고 소스 코드에서 수정이 필요하다고 확인한 경우, 다음 섹션을 살펴보세요. 이슈가 올바른 버그 보고서이고 소스 코드에서 수정이 필요하다고 확인한 경우, 다음 섹션을 살펴보세요.
다음 모든 기여에 대해서는 PR을 열여야 합니다. [PR 열기](#how-to-open-a-pr) 섹션에서 자세히 설명되어 있습니다. 다음 모든 기여에 대해서는 PR을 열여야 합니다. [PR 열기](#how-to-open-a-pr) 섹션에서 자세히 설명되어 있습니다.
### 4. "Good first issue" 고치기 ### 4. "Good first issue" 고치기
...@@ -308,7 +308,7 @@ Good second issue는 일반적으로 Good first issue 이슈보다 병합하기 ...@@ -308,7 +308,7 @@ Good second issue는 일반적으로 Good first issue 이슈보다 병합하기
### 9. 파이프라인, 모델, 스케줄러 추가하기 ### 9. 파이프라인, 모델, 스케줄러 추가하기
파이프라인, 모델, 스케줄러는 Diffusers 라이브러리에서 가장 중요한 부분입니다. 파이프라인, 모델, 스케줄러는 Diffusers 라이브러리에서 가장 중요한 부분입니다.
이들은 최첨단 diffusion 기술에 쉽게 접근하도록 하며, 따라서 커뮤니티가 강력한 생성형 AI 애플리케이션을 만들 수 있도록 합니다. 이들은 최첨단 diffusion 기술에 쉽게 접근하도록 하며, 따라서 커뮤니티가 강력한 생성형 AI 애플리케이션을 만들 수 있도록 합니다.
새로운 모델, 파이프라인 또는 스케줄러를 추가함으로써, 사용자 인터페이스에 새로운 강력한 사용 사례를 활성화할 수 있으며, 이는 전체 생성형 AI 생태계에 매우 중요한 가치를 제공할 수 있습니다. 새로운 모델, 파이프라인 또는 스케줄러를 추가함으로써, 사용자 인터페이스에 새로운 강력한 사용 사례를 활성화할 수 있으며, 이는 전체 생성형 AI 생태계에 매우 중요한 가치를 제공할 수 있습니다.
......
...@@ -37,7 +37,7 @@ Diffusers 커뮤니티는 프로젝트의 개발에 다음과 같은 윤리 지 ...@@ -37,7 +37,7 @@ Diffusers 커뮤니티는 프로젝트의 개발에 다음과 같은 윤리 지
- **간결성**: Diffusers 라이브러리를 사용하고 활용하기 쉽게 만들기 위해, 프로젝트의 목표를 간결하고 일관성 있게 유지할 것을 약속합니다. - **간결성**: Diffusers 라이브러리를 사용하고 활용하기 쉽게 만들기 위해, 프로젝트의 목표를 간결하고 일관성 있게 유지할 것을 약속합니다.
- **접근성**: Diffusers 프로젝트는 기술적 전문 지식 없어도 프로젝트 운영에 참여할 수 있는 기여자의 진입장벽을 낮춥니다. 이를 통해 연구 결과물이 커뮤니티에 더 잘 접근할 수 있게 됩니다. - **접근성**: Diffusers 프로젝트는 기술적 전문 지식 없어도 프로젝트 운영에 참여할 수 있는 기여자의 진입장벽을 낮춥니다. 이를 통해 연구 결과물이 커뮤니티에 더 잘 접근할 수 있게 됩니다.
- **재현성**: 우리는 Diffusers 라이브러리를 통해 제공되는 업스트림(upstream) 코드, 모델 및 데이터셋의 재현성에 대해 투명하게 공개할 것을 목표로 합니다. - **재현성**: 우리는 Diffusers 라이브러리를 통해 제공되는 업스트림(upstream) 코드, 모델 및 데이터셋의 재현성에 대해 투명하게 공개할 것을 목표로 합니다.
...@@ -58,6 +58,6 @@ Diffusers 커뮤니티는 프로젝트의 개발에 다음과 같은 윤리 지 ...@@ -58,6 +58,6 @@ Diffusers 커뮤니티는 프로젝트의 개발에 다음과 같은 윤리 지
- [**안전 검사기**](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py): 이미지가 생성된 후에 이미자가 임베딩 공간에서 일련의 하드코딩된 유해 개념의 클래스일 확률을 확인하고 비교합니다. 유해 개념은 역공학을 방지하기 위해 의도적으로 숨겨져 있습니다. - [**안전 검사기**](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py): 이미지가 생성된 후에 이미자가 임베딩 공간에서 일련의 하드코딩된 유해 개념의 클래스일 확률을 확인하고 비교합니다. 유해 개념은 역공학을 방지하기 위해 의도적으로 숨겨져 있습니다.
- **Hub에서의 단계적인 배포**: 특히 민감한 상황에서는 일부 리포지토리에 대한 접근을 제한해야 합니다. 이 단계적인 배포는 중간 단계로, 리포지토리 작성자가 사용에 대한 더 많은 통제력을 갖게 합니다. - **Hub에서의 단계적인 배포**: 특히 민감한 상황에서는 일부 리포지토리에 대한 접근을 제한해야 합니다. 이 단계적인 배포는 중간 단계로, 리포지토리 작성자가 사용에 대한 더 많은 통제력을 갖게 합니다.
- **라이선싱**: [OpenRAILs](https://huggingface.co/blog/open_rail)와 같은 새로운 유형의 라이선싱을 통해 자유로운 접근을 보장하면서도 더 책임 있는 사용을 위한 일련의 제한을 둘 수 있습니다. - **라이선싱**: [OpenRAILs](https://huggingface.co/blog/open_rail)와 같은 새로운 유형의 라이선싱을 통해 자유로운 접근을 보장하면서도 더 책임 있는 사용을 위한 일련의 제한을 둘 수 있습니다.
...@@ -141,7 +141,7 @@ print(images.shape) ...@@ -141,7 +141,7 @@ print(images.shape)
# (6, 512, 512, 3) # (6, 512, 512, 3)
``` ```
그러고 나서 CLIP 점수를 계산합니다. 그러고 나서 CLIP 점수를 계산합니다.
```python ```python
from torchmetrics.functional.multimodal import clip_score from torchmetrics.functional.multimodal import clip_score
......
...@@ -158,7 +158,7 @@ Core ML 모델과 추론 코드는 🧨 Diffusers의 많은 기능, 옵션 및 ...@@ -158,7 +158,7 @@ Core ML 모델과 추론 코드는 🧨 Diffusers의 많은 기능, 옵션 및
- Swift에 포팅된 스케줄러는 Stable Diffusion에서 사용하는 기본 스케줄러와 `diffusers` 구현에서 Swift로 포팅한 `DPMSolverMultistepScheduler` 두 개뿐입니다. 이들 중 약 절반의 스텝으로 동일한 품질을 생성하는 `DPMSolverMultistepScheduler`를 사용하는 것이 좋습니다. - Swift에 포팅된 스케줄러는 Stable Diffusion에서 사용하는 기본 스케줄러와 `diffusers` 구현에서 Swift로 포팅한 `DPMSolverMultistepScheduler` 두 개뿐입니다. 이들 중 약 절반의 스텝으로 동일한 품질을 생성하는 `DPMSolverMultistepScheduler`를 사용하는 것이 좋습니다.
- 추론 코드에서 네거티브 프롬프트, classifier-free guidance scale 및 image-to-image 작업을 사용할 수 있습니다. depth guidance, ControlNet, latent upscalers와 같은 고급 기능은 아직 사용할 수 없습니다. - 추론 코드에서 네거티브 프롬프트, classifier-free guidance scale 및 image-to-image 작업을 사용할 수 있습니다. depth guidance, ControlNet, latent upscalers와 같은 고급 기능은 아직 사용할 수 없습니다.
Apple의 [변환 및 추론 리포지토리](https://github.com/apple/ml-stable-diffusion)와 자체 [swift-coreml-diffusers](https://github.com/huggingface/swift-coreml-diffusers) 리포지토리는 다른 개발자들이 구축할 수 있는 기술적인 데모입니다. Apple의 [변환 및 추론 리포지토리](https://github.com/apple/ml-stable-diffusion)와 자체 [swift-coreml-diffusers](https://github.com/huggingface/swift-coreml-diffusers) 리포지토리는 다른 개발자들이 구축할 수 있는 기술적인 데모입니다.
누락된 기능이 있다고 생각되면 언제든지 기능을 요청하거나, 더 좋은 방법은 기여 PR을 열어주세요. :) 누락된 기능이 있다고 생각되면 언제든지 기능을 요청하거나, 더 좋은 방법은 기여 PR을 열어주세요. :)
......
...@@ -12,6 +12,6 @@ specific language governing permissions and limitations under the License. ...@@ -12,6 +12,6 @@ specific language governing permissions and limitations under the License.
# 개요 # 개요
노이즈가 많은 출력에서 적은 출력으로 만드는 과정으로 고품질 생성 모델의 출력을 만드는 각각의 반복되는 스텝은 많은 계산이 필요합니다. 🧨 Diffuser의 목표 중 하나는 모든 사람이 이 기술을 널리 이용할 수 있도록 하는 것이며, 여기에는 소비자 및 특수 하드웨어에서 빠른 추론을 가능하게 하는 것을 포함합니다. 노이즈가 많은 출력에서 적은 출력으로 만드는 과정으로 고품질 생성 모델의 출력을 만드는 각각의 반복되는 스텝은 많은 계산이 필요합니다. 🧨 Diffuser의 목표 중 하나는 모든 사람이 이 기술을 널리 이용할 수 있도록 하는 것이며, 여기에는 소비자 및 특수 하드웨어에서 빠른 추론을 가능하게 하는 것을 포함합니다.
이 섹션에서는 추론 속도를 최적화하고 메모리 소비를 줄이기 위한 반정밀(half-precision) 가중치 및 sliced attention과 같은 팁과 요령을 다룹니다. 또한 [`torch.compile`](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) 또는 [ONNX Runtime](https://onnxruntime.ai/docs/)을 사용하여 PyTorch 코드의 속도를 높이고, [xFormers](https://facebookresearch.github.io/xformers/)를 사용하여 memory-efficient attention을 활성화하는 방법을 배울 수 있습니다. Apple Silicon, Intel 또는 Habana 프로세서와 같은 특정 하드웨어에서 추론을 실행하기 위한 가이드도 있습니다. 이 섹션에서는 추론 속도를 최적화하고 메모리 소비를 줄이기 위한 반정밀(half-precision) 가중치 및 sliced attention과 같은 팁과 요령을 다룹니다. 또한 [`torch.compile`](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) 또는 [ONNX Runtime](https://onnxruntime.ai/docs/)을 사용하여 PyTorch 코드의 속도를 높이고, [xFormers](https://facebookresearch.github.io/xformers/)를 사용하여 memory-efficient attention을 활성화하는 방법을 배울 수 있습니다. Apple Silicon, Intel 또는 Habana 프로세서와 같은 특정 하드웨어에서 추론을 실행하기 위한 가이드도 있습니다.
\ No newline at end of file
...@@ -96,17 +96,17 @@ We benchmarked the impact of using `tomesd` on [`StableDiffusionPipeline`] along ...@@ -96,17 +96,17 @@ We benchmarked the impact of using `tomesd` on [`StableDiffusionPipeline`] along
| | 2 | OOM | 13 | 10.78 | | | | | 2 | OOM | 13 | 10.78 | | |
| | 1 | OOM | 6.66 | 5.54 | | | | | 1 | OOM | 6.66 | 5.54 | | |
위의 표에서 볼 수 있듯이, 이미지 해상도가 높을수록 `tomesd`를 사용한 속도 향상이 더욱 두드러집니다. 또한 `tomesd`를 사용하면 1024x1024와 같은 더 높은 해상도에서 파이프라인을 실행할 수 있다는 점도 흥미롭습니다. 위의 표에서 볼 수 있듯이, 이미지 해상도가 높을수록 `tomesd`를 사용한 속도 향상이 더욱 두드러집니다. 또한 `tomesd`를 사용하면 1024x1024와 같은 더 높은 해상도에서 파이프라인을 실행할 수 있다는 점도 흥미롭습니다.
[`torch.compile()`](https://huggingface.co/docs/diffusers/optimization/torch2.0)을 사용하면 추론 속도를 더욱 높일 수 있습니다. [`torch.compile()`](https://huggingface.co/docs/diffusers/optimization/torch2.0)을 사용하면 추론 속도를 더욱 높일 수 있습니다.
## 품질 ## 품질
As reported in [the paper](https://arxiv.org/abs/2303.17604), ToMe can preserve the quality of the generated images to a great extent while speeding up inference. By increasing the `ratio`, it is possible to further speed up inference, but that might come at the cost of a deterioration in the image quality. As reported in [the paper](https://arxiv.org/abs/2303.17604), ToMe can preserve the quality of the generated images to a great extent while speeding up inference. By increasing the `ratio`, it is possible to further speed up inference, but that might come at the cost of a deterioration in the image quality.
To test the quality of the generated samples using our setup, we sampled a few prompts from the “Parti Prompts” (introduced in [Parti](https://parti.research.google/)) and performed inference with the [`StableDiffusionPipeline`] in the following settings: To test the quality of the generated samples using our setup, we sampled a few prompts from the “Parti Prompts” (introduced in [Parti](https://parti.research.google/)) and performed inference with the [`StableDiffusionPipeline`] in the following settings:
[논문](https://arxiv.org/abs/2303.17604)에 보고된 바와 같이, ToMe는 생성된 이미지의 품질을 상당 부분 보존하면서 추론 속도를 높일 수 있습니다. `ratio`을 높이면 추론 속도를 더 높일 수 있지만, 이미지 품질이 저하될 수 있습니다. [논문](https://arxiv.org/abs/2303.17604)에 보고된 바와 같이, ToMe는 생성된 이미지의 품질을 상당 부분 보존하면서 추론 속도를 높일 수 있습니다. `ratio`을 높이면 추론 속도를 더 높일 수 있지만, 이미지 품질이 저하될 수 있습니다.
해당 설정을 사용하여 생성된 샘플의 품질을 테스트하기 위해, "Parti 프롬프트"([Parti](https://parti.research.google/)에서 소개)에서 몇 가지 프롬프트를 샘플링하고 다음 설정에서 [`StableDiffusionPipeline`]을 사용하여 추론을 수행했습니다: 해당 설정을 사용하여 생성된 샘플의 품질을 테스트하기 위해, "Parti 프롬프트"([Parti](https://parti.research.google/)에서 소개)에서 몇 가지 프롬프트를 샘플링하고 다음 설정에서 [`StableDiffusionPipeline`]을 사용하여 추론을 수행했습니다:
...@@ -114,7 +114,7 @@ To test the quality of the generated samples using our setup, we sampled a few p ...@@ -114,7 +114,7 @@ To test the quality of the generated samples using our setup, we sampled a few p
- [`StableDiffusionPipeline`] + ToMe - [`StableDiffusionPipeline`] + ToMe
- [`StableDiffusionPipeline`] + ToMe + xformers - [`StableDiffusionPipeline`] + ToMe + xformers
생성된 샘플의 품질이 크게 저하되는 것을 발견하지 못했습니다. 다음은 샘플입니다: 생성된 샘플의 품질이 크게 저하되는 것을 발견하지 못했습니다. 다음은 샘플입니다:
![tome-samples](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/tome/tome_samples.png) ![tome-samples](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/tome/tome_samples.png)
......
...@@ -30,7 +30,7 @@ pip install --upgrade torch diffusers ...@@ -30,7 +30,7 @@ pip install --upgrade torch diffusers
1. **가속화된 트랜스포머 구현** 1. **가속화된 트랜스포머 구현**
PyTorch 2.0에는 [`torch.nn.functional.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) 함수를 통해 최적화된 memory-efficient attention의 구현이 포함되어 있습니다. 이는 입력 및 GPU 유형에 따라 여러 최적화를 자동으로 활성화합니다. 이는 [xFormers](https://github.com/facebookresearch/xformers)`memory_efficient_attention`과 유사하지만 기본적으로 PyTorch에 내장되어 있습니다. PyTorch 2.0에는 [`torch.nn.functional.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) 함수를 통해 최적화된 memory-efficient attention의 구현이 포함되어 있습니다. 이는 입력 및 GPU 유형에 따라 여러 최적화를 자동으로 활성화합니다. 이는 [xFormers](https://github.com/facebookresearch/xformers)`memory_efficient_attention`과 유사하지만 기본적으로 PyTorch에 내장되어 있습니다.
이러한 최적화는 PyTorch 2.0이 설치되어 있고 `torch.nn.functional.scaled_dot_product_attention`을 사용할 수 있는 경우 Diffusers에서 기본적으로 활성화됩니다. 이를 사용하려면 `torch 2.0`을 설치하고 파이프라인을 사용하기만 하면 됩니다. 예를 들어: 이러한 최적화는 PyTorch 2.0이 설치되어 있고 `torch.nn.functional.scaled_dot_product_attention`을 사용할 수 있는 경우 Diffusers에서 기본적으로 활성화됩니다. 이를 사용하려면 `torch 2.0`을 설치하고 파이프라인을 사용하기만 하면 됩니다. 예를 들어:
```Python ```Python
...@@ -84,7 +84,7 @@ pip install --upgrade torch diffusers ...@@ -84,7 +84,7 @@ pip install --upgrade torch diffusers
``` ```
GPU 유형에 따라 `compile()`은 가속화된 트랜스포머 최적화를 통해 **5% - 300%**의 _추가 성능 향상_을 얻을 수 있습니다. 그러나 컴파일은 Ampere(A100, 3090), Ada(4090) 및 Hopper(H100)와 같은 최신 GPU 아키텍처에서 더 많은 성능 향상을 가져올 수 있음을 참고하세요. GPU 유형에 따라 `compile()`은 가속화된 트랜스포머 최적화를 통해 **5% - 300%**의 _추가 성능 향상_을 얻을 수 있습니다. 그러나 컴파일은 Ampere(A100, 3090), Ada(4090) 및 Hopper(H100)와 같은 최신 GPU 아키텍처에서 더 많은 성능 향상을 가져올 수 있음을 참고하세요.
컴파일은 완료하는 데 약간의 시간이 걸리므로, 파이프라인을 한 번 준비한 다음 동일한 유형의 추론 작업을 여러 번 수행해야 하는 상황에 가장 적합합니다. 다른 이미지 크기에서 컴파일된 파이프라인을 호출하면 시간적 비용이 많이 들 수 있는 컴파일 작업이 다시 트리거됩니다. 컴파일은 완료하는 데 약간의 시간이 걸리므로, 파이프라인을 한 번 준비한 다음 동일한 유형의 추론 작업을 여러 번 수행해야 하는 상황에 가장 적합합니다. 다른 이미지 크기에서 컴파일된 파이프라인을 호출하면 시간적 비용이 많이 들 수 있는 컴파일 작업이 다시 트리거됩니다.
...@@ -94,9 +94,9 @@ PyTorch 2.0의 효율적인 어텐션 구현과 `torch.compile`을 사용하여 ...@@ -94,9 +94,9 @@ PyTorch 2.0의 효율적인 어텐션 구현과 `torch.compile`을 사용하여
### 벤치마킹 코드 ### 벤치마킹 코드
#### Stable Diffusion text-to-image #### Stable Diffusion text-to-image
```python ```python
from diffusers import DiffusionPipeline from diffusers import DiffusionPipeline
import torch import torch
...@@ -118,9 +118,9 @@ for _ in range(3): ...@@ -118,9 +118,9 @@ for _ in range(3):
images = pipe(prompt=prompt).images images = pipe(prompt=prompt).images
``` ```
#### Stable Diffusion image-to-image #### Stable Diffusion image-to-image
```python ```python
from diffusers import StableDiffusionImg2ImgPipeline from diffusers import StableDiffusionImg2ImgPipeline
import requests import requests
import torch import torch
...@@ -153,7 +153,7 @@ for _ in range(3): ...@@ -153,7 +153,7 @@ for _ in range(3):
#### Stable Diffusion - inpainting #### Stable Diffusion - inpainting
```python ```python
from diffusers import StableDiffusionInpaintPipeline from diffusers import StableDiffusionInpaintPipeline
import requests import requests
import torch import torch
...@@ -191,9 +191,9 @@ for _ in range(3): ...@@ -191,9 +191,9 @@ for _ in range(3):
image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0] image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
``` ```
#### ControlNet #### ControlNet
```python ```python
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
import requests import requests
import torch import torch
...@@ -231,7 +231,7 @@ for _ in range(3): ...@@ -231,7 +231,7 @@ for _ in range(3):
#### IF text-to-image + upscaling #### IF text-to-image + upscaling
```python ```python
from diffusers import DiffusionPipeline from diffusers import DiffusionPipeline
import torch import torch
...@@ -269,7 +269,7 @@ PyTorch 2.0 및 `torch.compile()`로 얻을 수 있는 가능한 속도 향상 ...@@ -269,7 +269,7 @@ PyTorch 2.0 및 `torch.compile()`로 얻을 수 있는 가능한 속도 향상
![t2i_speedup](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/pt2_benchmarks/t2i_speedup.png) ![t2i_speedup](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/pt2_benchmarks/t2i_speedup.png)
To give you an even better idea of how this speed-up holds for the other pipelines presented above, consider the following To give you an even better idea of how this speed-up holds for the other pipelines presented above, consider the following
plot that shows the benchmarking numbers from an A100 across three different batch sizes plot that shows the benchmarking numbers from an A100 across three different batch sizes
(with PyTorch 2.0 nightly and `torch.compile()`): (with PyTorch 2.0 nightly and `torch.compile()`):
이 속도 향상이 위에 제시된 다른 파이프라인에 대해서도 어떻게 유지되는지 더 잘 이해하기 위해, 세 가지의 다른 배치 크기에 걸쳐 A100의 벤치마킹(PyTorch 2.0 nightly 및 `torch.compile() 사용) 수치를 보여주는 차트를 보입니다: 이 속도 향상이 위에 제시된 다른 파이프라인에 대해서도 어떻게 유지되는지 더 잘 이해하기 위해, 세 가지의 다른 배치 크기에 걸쳐 A100의 벤치마킹(PyTorch 2.0 nightly 및 `torch.compile() 사용) 수치를 보여주는 차트를 보입니다:
...@@ -434,8 +434,8 @@ _(위 차트의 벤치마크 메트릭은 **초당 iteration 수(iterations/seco ...@@ -434,8 +434,8 @@ _(위 차트의 벤치마크 메트릭은 **초당 iteration 수(iterations/seco
## 참고 ## 참고
* Follow [this PR](https://github.com/huggingface/diffusers/pull/3313) for more details on the environment used for conducting the benchmarks. * Follow [this PR](https://github.com/huggingface/diffusers/pull/3313) for more details on the environment used for conducting the benchmarks.
* For the IF pipeline and batch sizes > 1, we only used a batch size of >1 in the first IF pipeline for text-to-image generation and NOT for upscaling. So, that means the two upscaling pipelines received a batch size of 1. * For the IF pipeline and batch sizes > 1, we only used a batch size of >1 in the first IF pipeline for text-to-image generation and NOT for upscaling. So, that means the two upscaling pipelines received a batch size of 1.
*Thanks to [Horace He](https://github.com/Chillee) from the PyTorch team for their support in improving our support of `torch.compile()` in Diffusers.* *Thanks to [Horace He](https://github.com/Chillee) from the PyTorch team for their support in improving our support of `torch.compile()` in Diffusers.*
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment