GPTQ_loader.py 2.4 KB

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