quantized_LLaMA.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. import sys
  3. from pathlib import Path
  4. import accelerate
  5. import torch
  6. import modules.shared as shared
  7. sys.path.insert(0, os.path.abspath(Path("repositories/GPTQ-for-LLaMa")))
  8. from llama import load_quant
  9. # 4-bit LLaMA
  10. def load_quantized_LLaMA(model_name):
  11. if shared.args.load_in_4bit:
  12. bits = 4
  13. else:
  14. bits = shared.args.gptq_bits
  15. path_to_model = Path(f'models/{model_name}')
  16. pt_model = ''
  17. if path_to_model.name.lower().startswith('llama-7b'):
  18. pt_model = f'llama-7b-{bits}bit.pt'
  19. elif path_to_model.name.lower().startswith('llama-13b'):
  20. pt_model = f'llama-13b-{bits}bit.pt'
  21. elif path_to_model.name.lower().startswith('llama-30b'):
  22. pt_model = f'llama-30b-{bits}bit.pt'
  23. elif path_to_model.name.lower().startswith('llama-65b'):
  24. pt_model = f'llama-65b-{bits}bit.pt'
  25. else:
  26. pt_model = f'{model_name}-{bits}bit.pt'
  27. # Try to find the .pt both in models/ and in the subfolder
  28. pt_path = None
  29. for path in [Path(p) for p in [f"models/{pt_model}", f"{path_to_model}/{pt_model}"]]:
  30. if path.exists():
  31. pt_path = path
  32. if not pt_path:
  33. print(f"Could not find {pt_model}, exiting...")
  34. exit()
  35. model = load_quant(path_to_model, os.path.abspath(pt_path), bits)
  36. # Multi-GPU setup
  37. if shared.args.gpu_memory:
  38. max_memory = {}
  39. for i in range(len(shared.args.gpu_memory)):
  40. max_memory[i] = f"{shared.args.gpu_memory[i]}GiB"
  41. max_memory['cpu'] = f"{shared.args.cpu_memory or '99'}GiB"
  42. device_map = accelerate.infer_auto_device_map(model, max_memory=max_memory, no_split_module_classes=["LLaMADecoderLayer"])
  43. model = accelerate.dispatch_model(model, device_map=device_map)
  44. # Single GPU
  45. else:
  46. model = model.to(torch.device('cuda:0'))
  47. return model