LoRA.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from pathlib import Path
  2. import torch
  3. from peft import PeftModel
  4. import modules.shared as shared
  5. from modules.models import reload_model
  6. def add_lora_to_model(lora_name):
  7. # If a LoRA had been previously loaded, or if we want
  8. # to unload a LoRA, reload the model
  9. if shared.lora_name not in ['None', ''] or lora_name in ['None', '']:
  10. reload_model()
  11. shared.lora_name = lora_name
  12. if lora_name not in ['None', '']:
  13. print(f"Adding the LoRA {lora_name} to the model...")
  14. params = {}
  15. if not shared.args.cpu:
  16. params['dtype'] = shared.model.dtype
  17. if hasattr(shared.model, "hf_device_map"):
  18. params['device_map'] = {"base_model.model." + k: v for k, v in shared.model.hf_device_map.items()}
  19. elif shared.args.load_in_8bit:
  20. params['device_map'] = {'': 0}
  21. shared.model = PeftModel.from_pretrained(shared.model, Path(f"{shared.args.lora_dir}/{lora_name}"), **params)
  22. if not shared.args.load_in_8bit and not shared.args.cpu:
  23. shared.model.half()
  24. if not hasattr(shared.model, "hf_device_map"):
  25. if torch.has_mps:
  26. device = torch.device('mps')
  27. shared.model = shared.model.to(device)
  28. else:
  29. shared.model = shared.model.cuda()