quantized_LLaMA.py 1.8 KB

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