LoRA.py 1.1 KB

123456789101112131415161718192021222324252627282930
  1. from pathlib import Path
  2. import modules.shared as shared
  3. from modules.models import load_model
  4. def add_lora_to_model(lora_name):
  5. from peft import PeftModel
  6. # Is there a more efficient way of returning to the base model?
  7. if lora_name == "None":
  8. print("Reloading the model to remove the LoRA...")
  9. shared.model, shared.tokenizer = load_model(shared.model_name)
  10. else:
  11. print(f"Adding the LoRA {lora_name} to the model...")
  12. params = {}
  13. if not shared.args.cpu:
  14. params['dtype'] = shared.model.dtype
  15. if hasattr(shared.model, "hf_device_map"):
  16. params['device_map'] = {"base_model.model."+k: v for k, v in shared.model.hf_device_map.items()}
  17. elif shared.args.load_in_8bit:
  18. params['device_map'] = {'': 0}
  19. shared.model = PeftModel.from_pretrained(shared.model, Path(f"loras/{lora_name}"), **params)
  20. if not shared.args.load_in_8bit and not shared.args.cpu:
  21. shared.model.half()
  22. if not hasattr(shared.model, "hf_device_map"):
  23. shared.model.cuda()