LoRA.py 1.3 KB

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