Buckets:
| # LoRA | |
| > [!WARNING] | |
| > 이것은 실험적이며 API가 향후 변경될 수 있습니다. | |
| [LoRA (Low-Rank Adaptation of Large Language Models)](https://hf.co/papers/2106.09685)는 학습 가능한 매개변수의 수를 크게 줄이는 인기 있고 경량화된 학습 기법입니다. 모델에 더 적은 수의 새로운 가중치를 삽입하고 이 가중치만 학습하는 방식으로 작동합니다. 이를 통해 LoRA를 사용한 학습은 훨씬 빠르고 메모리 효율적이며, 저장 및 공유가 용이한 더 작은 모델 가중치(수백 MB)를 생성합니다. LoRA는 DreamBooth와 같은 다른 학습 기법과 결합하여 학습 속도를 높일 수도 있습니다. | |
| > [!TIP] | |
| > LoRA는 매우 다재다능하며 [DreamBooth](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth_lora.py), [Kandinsky 2.2](https://github.com/huggingface/diffusers/blob/main/examples/kandinsky2_2/text_to_image/train_text_to_image_lora_decoder.py), [Stable Diffusion XL](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora_sdxl.py), [text-to-image](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py)에 지원됩니다. | |
| This guide will explore the [train_text_to_image_lora.py](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py) script to help you become more familiar with it, and how you can adapt it for your own use-case. | |
| … | |
| ```bash | |
| git clone https://github.com/huggingface/diffusers | |
| cd diffusers | |
| pip install . | |
| ``` | |
| 학습 스크립트가 포함된 예제 폴더로 이동하고, 사용 중인 스크립트에 필요한 의존성을 설치하세요: | |
| ```bash | |
| cd examples/text_to_image | |
| pip install -r requirements.txt | |
| ``` | |
| > [!TIP] | |
| > 🤗 Accelerate는 여러 GPU/TPU 또는 혼합 정밀도로 학습하는 것을 돕는 라이브러리입니다. 하드웨어와 환경에 따라 학습 설정을 자동으로 구성합니다. 자세한 내용은 🤗 Accelerate [Quick tour](https://huggingface.co/docs/accelerate/quicktour)를 참고하세요. | |
| 🤗 Accelerate 환경을 초기화합니다: | |
| ```bash | |
| accelerate config | |
| ``` | |
| 어떤 구성도 선택하지 않고 기본 🤗 Accelerate 환경을 설정하려면: | |
| ```bash | |
| accelerate config default | |
| ``` | |
| 또는 노트북과 같이 인터랙티브 셸을 지원하지 않는 환경에서는 다음을 사용할 수 있습니다: | |
| ```py | |
| from accelerate.utils import write_basic_config | |
| write_basic_config() | |
| ``` | |
| 마지막으로, 자체 데이터셋으로 모델을 학습하려면 [학습용 데이터셋 만들기](create_dataset) 가이드를 참고하여 학습 스크립트와 호환되는 데이터셋을 만드는 방법을 배워보세요. | |
| > [!TIP] | |
| > 다음 섹션에서는 스크립트를 수정하는 방법을 이해하는 데 중요한 학습 스크립트의 일부 부분을 강조합니다. 그러나 스크립트의 모든 측면을 자세히 다루지는 않습니다. 더 자세히 알고 싶으시다면 [스크립트](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py)를 읽어보시고, 질문이나 우려 사항이 있으시면 알려주시기 바랍니다. | |
| ## 스크립트 매개변수 | |
| 학습 스크립트에는 학습 실행을 사용자 정의하는 데 도움이 되는 많은 매개변수가 있습니다. 모든 매개변수와 그 설명은 [`parse_args()`](https://github.com/huggingface/diffusers/blob/dd9a5caf61f04d11c0fa9f3947b69ab0010c9a0f/examples/text_to_image/train_text_to_image_lora.py#L85) 함수에서 찾을 수 있습니다. 대부분의 매개변수에는 잘 작동하는 기본값이 제공되지만, 원하시는 경우 학습 명령에서 자체 값을 설정할 수도 있습니다. | |
| 예를 들어, 학습할 에포크 수를 늘리려면: | |
| ```bash | |
| accelerate launch train_text_to_image_lora.py \ | |
| --num_train_epochs=150 \ | |
| ``` | |
| 기본적이고 중요한 대부분의 매개변수는 [텍스트-이미지](text2image#script-parameters) 학습 가이드에 설명되어 있으므로, 이 가이드에서는 LoRA와 관련된 매개변수에만 초점을 맞춥니다: | |
| - `--rank`: 학습할 저순위 행렬의 내부 차원; 랭크가 높을수록 학습 가능한 파라미터가 많아집니다 | |
| - `--learning_rate`: 기본 학습률은 1e-4이지만, LoRA를 사용하면 더 높은 학습률을 사용할 수 있습니다 | |
| ## 학습 스크립트 | |
| 데이터셋 전처리 코드와 학습 루프는 [`main()`](https://github.com/huggingface/diffusers/blob/dd9a5caf61f04d11c0fa9f3947b69ab0010c9a0f/examples/text_to_image/train_text_to_image_lora.py#L371) 함수에 있으며, 학습 스크립트를 수정해야 하는 경우 이 부분을 변경하면 됩니다. | |
| 스크립트 매개변수와 마찬가지로, [Text-to-image](text2image#training-script) 학습 가이드에서 학습 스크립트의 전체적인 흐름을 안내합니다. 대신 이 가이드에서는 스크립트 중 LoRA와 관련된 부분을 살펴봅니다. | |
| Diffusers는 [PEFT](https://hf.co/docs/peft) 라이브러리의 `LoraConfig`를 사용하여 LoRA 어댑터의 매개변수, 즉 랭크, 알파, LoRA 가중치를 삽입할 모듈을 설정합니다. 어댑터는 UNet에 추가되며, `lora_layers`에서는 최적화를 위해 LoRA 레이어만 필터링됩니다. | |
| ```py | |
| unet_lora_config = LoraConfig( | |
| r=args.rank, | |
| lora_alpha=args.rank, | |
| init_lora_weights="gaussian", | |
| target_modules=["to_k", "to_q", "to_v", "to_out.0"], | |
| ) | |
| unet.add_adapter(unet_lora_config) | |
| lora_layers = filter(lambda p: p.requires_grad, unet.parameters()) | |
| ``` | |
| Diffusers는 Stable Diffusion XL(SDXL)과 같이 필요한 경우 [PEFT](https://hf.co/docs/peft) 라이브러리를 사용하여 텍스트 인코더를 LoRA로 미세 조정하는 것도 지원합니다. `LoraConfig`는 텍스트 인코더에 추가되는 LoRA 어댑터의 매개변수를 구성하는 데 사용되며, 학습을 위해 LoRA 레이어만 필터링됩니다. | |
| ```py | |
| text_lora_config = LoraConfig( | |
| r=args.rank, | |
| lora_alpha=args.rank, | |
| init_lora_weights="gaussian", | |
| target_modules=["q_proj", "k_proj", "v_proj", "out_proj"], | |
| ) | |
| text_encoder_one.add_adapter(text_lora_config) | |
| text_encoder_two.add_adapter(text_lora_config) | |
| text_lora_parameters_one = list(filter(lambda p: p.requires_grad, text_encoder_one.parameters())) | |
| text_lora_parameters_two = list(filter(lambda p: p.requires_grad, text_encoder_two.parameters())) | |
| ``` | |
| `lora_layers`가 최적화될 유일한 가중치이므로 [optimizer](https://github.com/huggingface/diffusers/blob/e4b8f173b97731686e290b2eb98e7f5df2b1b322/examples/text_to_image/train_text_to_image_lora.py#L529)는 `lora_layers`로 초기화됩니다: | |
| ```py | |
| optimizer = optimizer_cls( | |
| lora_layers, | |
| lr=args.learning_rate, | |
| betas=(args.adam_beta1, args.adam_beta2), | |
| weight_decay=args.adam_weight_decay, | |
| eps=args.adam_epsilon, | |
| ) | |
| ``` | |
| Aside from setting up the LoRA layers, the training script is more or less the same as train_text_to_image.py! | |
| ## 스크립트 실행 | |
| 모든 변경 사항을 완료했거나 기본 구성으로 진행하는 데 문제가 없다면, 학습 스크립트를 실행할 준비가 된 것입니다! 🚀 | |
| [Naruto BLIP captions](https://huggingface.co/datasets/lambdalabs/naruto-blip-captions) 데이터셋을 학습하여 나루토 캐릭터를 생성해 보겠습니다. `MODEL_NAME`과 `DATASET_NAME` 환경 변수를 각각 모델과 데이터셋으로 설정합니다. 또한 `OUTPUT_DIR`에 모델을 저장할 위치를 지정하고, `HUB_MODEL_ID`로 Hub에 저장할 모델 이름을 지정해야 합니다. 스크립트는 다음 파일들을 생성하여 저장소에 저장합니다: | |
| - 저장된 모델 체크포인트 | |
| - `pytorch_lora_weights.safetensors` (학습된 LoRA 가중치) | |
| 여러 개의 GPU에서 학습하는 경우 `accelerate launch` 명령에 `--multi_gpu` 매개변수를 추가하세요. | |
| > [!WARNING] | |
| > 2080 Ti GPU(11GB VRAM)에서 전체 학습 실행에 약 5시간이 소요됩니다. | |
| ```bash | |
| export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-v1-5" | |
| export OUTPUT_DIR="/sddata/finetune/lora/naruto" | |
| export HUB_MODEL_ID="naruto-lora" | |
| export DATASET_NAME="lambdalabs/naruto-blip-captions" | |
| accelerate launch --mixed_precision="fp16" train_text_to_image_lora.py \ | |
| --pretrained_model_name_or_path=$MODEL_NAME \ | |
| --dataset_name=$DATASET_NAME \ | |
| --dataloader_num_workers=8 \ | |
| --resolution=512 \ | |
| --center_crop \ | |
| --random_flip \ | |
| --train_batch_size=1 \ | |
| --gradient_accumulation_steps=4 \ | |
| --max_train_steps=15000 \ | |
| --learning_rate=1e-04 \ | |
| --max_grad_norm=1 \ | |
| --lr_scheduler="cosine" \ | |
| --lr_warmup_steps=0 \ | |
| --output_dir=${OUTPUT_DIR} \ | |
| --push_to_hub \ | |
| --hub_model_id=${HUB_MODEL_ID} \ | |
| --report_to=wandb \ | |
| --checkpointing_steps=500 \ | |
| --validation_prompt="A naruto with blue eyes." \ | |
| --seed=1337 | |
| ``` | |
| 학습이 완료되면 모델을 추론에 사용할 수 있습니다: | |
| ```py | |
| from diffusers import AutoPipelineForText2Image | |
| import torch | |
| pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16).to("cuda") # or "mps", "xpu", "cpu" | |
| pipeline.load_lora_weights("path/to/lora/model", weight_name="pytorch_lora_weights.safetensors") | |
| image = pipeline("A naruto with blue eyes").images[0] | |
| ``` | |
| ## 다음 단계 | |
| LoRA로 새로운 모델을 학습하신 것을 축하드립니다! 새로운 모델을 사용하는 방법에 대해 더 알고 싶으시다면, 다음 가이드가 도움이 될 수 있습니다: | |
| - Kohya, TheLastBen과 같은 커뮤니티 트레이너로 학습한 [다양한 LoRA 형식](../tutorials/using_peft_for_inference)을 로드하는 방법을 알아보세요. | |
| - PEFT를 사용하여 추론 시 [여러 LoRA를 조합](../tutorials/using_peft_for_inference)하는 방법을 학습합니다. | |
Xet Storage Details
- Size:
- 9.94 kB
- Xet hash:
- f7eb8d7e67f846c2a98789acc42ea6ffe655baf91366285fd888a095e3d0e068
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.