LoRA.py 1.5 KB

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