quant_loader.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. def load_quantized(model_name):
  8. if not shared.args.gptq_model_type:
  9. # Try to determine model type from model name
  10. model_type = model_name.split('-')[0].lower()
  11. if model_type not in ('llama', 'opt'):
  12. print("Can't determine model type from model name. Please specify it manually using --gptq-model-type "
  13. "argument")
  14. exit()
  15. else:
  16. model_type = shared.args.gptq_model_type.lower()
  17. if model_type == 'llama':
  18. from llama import load_quant
  19. elif model_type == 'opt':
  20. from opt import load_quant
  21. else:
  22. print("Unknown pre-quantized model type specified. Only 'llama' and 'opt' are supported")
  23. exit()
  24. path_to_model = Path(f'models/{model_name}')
  25. if path_to_model.name.lower().startswith('llama-7b'):
  26. pt_model = f'llama-7b-{shared.args.gptq_bits}bit.pt'
  27. elif path_to_model.name.lower().startswith('llama-13b'):
  28. pt_model = f'llama-13b-{shared.args.gptq_bits}bit.pt'
  29. elif path_to_model.name.lower().startswith('llama-30b'):
  30. pt_model = f'llama-30b-{shared.args.gptq_bits}bit.pt'
  31. elif path_to_model.name.lower().startswith('llama-65b'):
  32. pt_model = f'llama-65b-{shared.args.gptq_bits}bit.pt'
  33. else:
  34. pt_model = f'{model_name}-{shared.args.gptq_bits}bit.pt'
  35. # Try to find the .pt both in models/ and in the subfolder
  36. pt_path = None
  37. for path in [Path(p) for p in [f"models/{pt_model}", f"{path_to_model}/{pt_model}"]]:
  38. if path.exists():
  39. pt_path = path
  40. if not pt_path:
  41. print(f"Could not find {pt_model}, exiting...")
  42. exit()
  43. model = load_quant(path_to_model, str(pt_path), shared.args.gptq_bits)
  44. # Multiple GPUs or GPU+CPU
  45. if shared.args.gpu_memory:
  46. max_memory = {}
  47. for i in range(len(shared.args.gpu_memory)):
  48. max_memory[i] = f"{shared.args.gpu_memory[i]}GiB"
  49. max_memory['cpu'] = f"{shared.args.cpu_memory or '99'}GiB"
  50. device_map = accelerate.infer_auto_device_map(model, max_memory=max_memory, no_split_module_classes=["LLaMADecoderLayer"])
  51. model = accelerate.dispatch_model(model, device_map=device_map)
  52. # Single GPU
  53. else:
  54. model = model.to(torch.device('cuda:0'))
  55. return model