当前位置:   article > 正文

[linux-sd-webui]api化之训练lora_lora api

lora api

lora的训练使用的文件是https://github.com/Akegarasu/lora-scripts

lora训练是需要成对的文本图像对的,需要准备相应的训练数据。

1.训练数据准备

使用deepbooru/blip生成训练数据,建筑类建议使用blip来生成。

2.lora在linux上环境

cuda 10.1 p40 python3.7

accelerate==0.15.0 应该只能在虚拟环境中,在train.sh中把accelerate launch --num_cpu_threads_per_process=8换成python,这么改accelerate多卡训练有问题

albumentations==0.2.0

scikit-image==0.14 版本高了会报错

numpy==1.17

这里面有个skimage的版本问题,会报错

[bug解决] cannot import name ‘_validate_lengths‘ from ‘numpy.lib.arraypad‘_arrycrop.py在那_Harry嗷的博客-CSDN博客

safetensors==0.3.0

voluptuous==0.12.1

huggingface-hub==0.12.0

transformers==4.20.0

tokenizers==0.11.6

opencv-python==4.0.0.21

einops==0.3.0

ftfy==6.0

pytorch-lightning==1.2.8

xformers==0.0.9(torch可以支持torch==1.8.1)

diffusers==0.10.0

pyre-extensions==0.3.0

regex==2021.4.4

升级glic

3.sh train.sh训练

openai的clip权重要配置一下

library/train_util/ 1900多行中load_tokenizer函数中的tokenizer=CLIPTokenizer.from_pretrained()

使用的是openai的clip-vit-large-patch14参数

4.lora-scripts的核心代码解析

  1. train_network.py->train->
  2. train_util.load_tokenizer->
  3. BuleprintGenerator->
  4. config_util.generate_dreambooth_subsets_config_by_subdirs->
  5. blueprint_generator.generate->
  6. config_util.generate_dataset_group_by_blueprint 加载数据->
  7. train_util.prepare_accelerator->
  8. train_util.prepare_dtype->
  9. train_util.load_target_model 加载sd模型->
  10. train_util.replace_unet_modules->
  11. vae.to(accelerator.device)->
  12. vae.requires_grad_(False)->
  13. vae.eval()->
  14. train_dataset_group.cache_lantents->
  15. network_module(LoRANetwork)->
  16. network.apply_to(text_encoder,unet,train_text_encoder,train_unet)->
  17. network.prepare_optimizer_params->
  18. train_util.get_optimizer->
  19. train_dataloader=torch.utils.data.DataLoader(train_dataset_group)->
  20. lr_scheduler=train_util.get_scheduler_fix->
  21. unet,text_encoder,network,optimizer,train_dataloader,lr_scheduler=accelerator.prepare(unet,text_encoder,network,optimizer,train_dataloader,lr_scheduler)->
  22. unet.requires_grad_(False)->
  23. unet.to(accelerator.device)->
  24. text_encoder.requires_grad_->
  25. text_encoder.to(accelerator-device)->
  26. unet.eval()->
  27. text_encoder.eval()->
  28. network.prepare_grad_etc(text_encoder,unet)->
  29. dataset=train_dataset_group.dataset[0]->
  30. noise_scheduler=DDPMScheduler(beta_start=0.00085,beta_end=0.012,beta_schedule='scaled_linear',num_train_timesteps=1000,clip_sample=False)->
  31. accelerator.init_trackers('netwoek_train')->
  32. network.on_epoch_start(text_encoder,unet)->
  33. latents=batch['latents'].to(accelerator.device)->
  34. latents=latents*0.18215->
  35. encoder_hidden_states=train_util.get_hidden_states->
  36. noise = torch.randn(latents,device=latent.device)->
  37. timesteps=torch.randint(0,noise_scheduler.config.num_train_timesteps,(b_size,),device=latents.device)->
  38. noise_latents=noise_scheduler.add_noise(lantents,noise,timesteps) [1,4,64,64]->
  39. noise_pred=unet(noisy_latents,timesteps,encoder_hidden_states).sample [1,4,64,64]->
  40. target=noise_scheduler.get_velocity(latnets,noise,timesteps) [1,4,64,64]->
  41. loss=torch.nn.functional.mse_loss(noise_pred.float(),target.float(),reduction='none') [1,4,64,64]->
  42. loss=loss.mean([1,2,3])->
  43. loss_weights=batch['loss_weights']->
  44. loss=loss*loss_weights->
  45. accelerator.backward(loss)->
  46. param_to_clip=network.get_trainable_params()->
  47. accelerator.clip_grad_norm_()->
  48. optimizer.grad()->
  49. lr_scheduler.step()->
  50. optimizer.zero_grad()->
  51. train_util.sample_images(accelerator,args,None,global_step,accelerator.device,vae,tokenizer,text_encoder,unet)

5.入参

  1. args = Namespace(
  2. bucket_no_upscale=False,
  3. bucket_reso_steps=64,
  4. cache_latents=True,
  5. caption_dropout_every_n_epochs=0,
  6. caption_dropout_rate=0.0,
  7. caption_extension='.txt',
  8. caption_extention=None,
  9. caption_tag_dropout_rate=0.0,
  10. clip_skip=2,
  11. color_aug=False,
  12. dataset_config=None,
  13. dataset_repeats=1,
  14. debug_dataset=False,
  15. enable_bucket=True,
  16. face_crop_aug_range=None,
  17. flip_aug=False,
  18. full_fp16=False,
  19. gradient_accumulation_steps=1,
  20. gradient_checkpointing=False,
  21. in_json=None,
  22. keep_tokens=0,
  23. learning_rate=0.0001,
  24. log_prefix=None,
  25. logging_dir='./logs',
  26. lowram=False,
  27. lr_scheduler='cosine_with_restarts',
  28. lr_scheduler_num_cycles=1,
  29. lr_scheduler_power=1,
  30. lr_warmup_steps=0,
  31. max_bucket_reso=1024,
  32. max_data_loader_n_workers=8,
  33. max_grad_norm=1.0,
  34. max_token_length=225,
  35. max_train_epochs=10,
  36. max_train_steps=1600,
  37. mem_eff_attn=False,
  38. min_bucket_reso=256,
  39. mixed_precision='fp16',
  40. network_alpha=32.0,
  41. network_args=None,
  42. network_dim=32,
  43. network_module='networks.lora',
  44. network_train_text_encoder_only=False,
  45. network_train_unet_only=False,
  46. network_weights=None,
  47. no_metadata=False,
  48. noise_offset=0.0,
  49. optimizer_args=None,
  50. optimizer_type='',
  51. output_dir='./output',
  52. output_name='/home/sniss/local_disk/lora-scripts/output',
  53. persistent_data_loader_workers=False,
  54. pretrained_model_name_or_path='/home/sniss/local_disk/stable-diffusion-webui_23-02-17/models/Stable-diffusion/sd-v1.5.ckpt',
  55. prior_loss_weight=1.0,
  56. random_crop=False,
  57. reg_data_dir=None,
  58. resolution=(512, 512),
  59. resume=None,
  60. sample_every_n_epochs=None,
  61. sample_every_n_steps=None,
  62. sample_prompts=None,
  63. sample_sampler='ddim',
  64. save_every_n_epochs=2,
  65. save_last_n_epochs=None,
  66. save_last_n_epochs_state=None,
  67. save_model_as='ckpt',
  68. save_n_epoch_ratio=None,
  69. save_precision='fp16',
  70. save_state=False,
  71. seed=1337,
  72. shuffle_caption=True,
  73. text_encoder_lr=1e-05,
  74. tokenizer_cache_dir=None,
  75. train_batch_size=1,
  76. train_data_dir='/home/sniss/local_disk/lora-scripts/data',
  77. training_comment=None,
  78. unet_lr=0.0001,
  79. use_8bit_adam=False,
  80. use_lion_optimizer=False,
  81. v2=False,
  82. v_parameterization=False,
  83. vae=None,
  84. xformers=True)

参数的设置有好几块:

1.输入的train.sh

2.train_network.py中的main部分

3.train_util.py中的1536行附近的

add_sd_models_args/add_optimizer_args/add_training_args/add_dataset_args

6.注意事项

a.数据集名称第一个是数字20_arch,这个数字和训练轮数epoch有关

b.train_network中

PyTorch 训练时中遇到的卡住停住等问题_训练时候卡住_yyywxk的博客-CSDN博客- 问题描述使用 PyTorch 框架训练模型,训练第一个 epoch 时,在最后一个 batch 处卡死,卡了一天都没有动弹,而 CPU 和 GPU 都处于正常运行的状态,程序也没有报错,并且之前训练一直都是正常的。最终,只能通过 Ctrl+C 强制性暂停。如下图所示。- 可能的原因搜索文章发现,有人出现这种问题是和 cv2.imread 有关,用 OpenCV 的接口进行数据读取,而没有用 PIL,导致出现 OpenCV与Pytorch互锁的问题,关闭OpenCV的多线程即可解决问题1 2。但https://blog.csdn.net/yyywxk/article/details/106323049在args.max_data_loader_n_workers改为0

c.max_token_length=75,150,225,使用225会报错?RuntimeError: The size of tensor a (227) must match the size of tensor b (77) at non-singleton dimension 1,这块是个巨坑,主要是clip初始化的时候,忘了加tokenizer_config.json这个文件。

d.bash: accelerate: command not found,没搞定

多卡训练

  1. python -m torch.distributed.launch --nproc_per_node=4 --nnodes=1 --node_rank=0 --master_addr=localhost --master_port=22222 --use_env "./sd-scripts/train_network.py" \
  2. import torch.distributed as dist
  3. dist.init_process_group(backend='gloo', init_method='env://')

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/135138
推荐阅读
相关标签
  

闽ICP备14008679号