models.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import json
  2. import os
  3. import time
  4. import zipfile
  5. from pathlib import Path
  6. import numpy as np
  7. import torch
  8. import transformers
  9. from accelerate import infer_auto_device_map, init_empty_weights
  10. from transformers import (AutoConfig, AutoModelForCausalLM, AutoTokenizer,
  11. BitsAndBytesConfig)
  12. from peft import PeftModel
  13. import modules.shared as shared
  14. transformers.logging.set_verbosity_error()
  15. local_rank = None
  16. if shared.args.flexgen:
  17. from flexgen.flex_opt import CompressionConfig, ExecutionEnv, OptLM, Policy
  18. if shared.args.deepspeed:
  19. import deepspeed
  20. from transformers.deepspeed import (HfDeepSpeedConfig,
  21. is_deepspeed_zero3_enabled)
  22. from modules.deepspeed_parameters import generate_ds_config
  23. # Distributed setup
  24. local_rank = shared.args.local_rank if shared.args.local_rank is not None else int(os.getenv("LOCAL_RANK", "0"))
  25. world_size = int(os.getenv("WORLD_SIZE", "1"))
  26. torch.cuda.set_device(local_rank)
  27. deepspeed.init_distributed()
  28. ds_config = generate_ds_config(shared.args.bf16, 1 * world_size, shared.args.nvme_offload_dir)
  29. dschf = HfDeepSpeedConfig(ds_config) # Keep this object alive for the Transformers integration
  30. def load_model(model_name):
  31. print(f"Loading {model_name}...")
  32. t0 = time.time()
  33. shared.is_RWKV = model_name.lower().startswith('rwkv-')
  34. # Default settings
  35. if not any([shared.args.cpu, shared.args.load_in_8bit, shared.args.gptq_bits, shared.args.auto_devices, shared.args.disk, shared.args.gpu_memory is not None, shared.args.cpu_memory is not None, shared.args.deepspeed, shared.args.flexgen, shared.is_RWKV]):
  36. if any(size in shared.model_name.lower() for size in ('13b', '20b', '30b')):
  37. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{shared.model_name}"), device_map='auto', load_in_8bit=True)
  38. else:
  39. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{shared.model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.bfloat16 if shared.args.bf16 else torch.float16).cuda()
  40. # FlexGen
  41. elif shared.args.flexgen:
  42. # Initialize environment
  43. env = ExecutionEnv.create(shared.args.disk_cache_dir)
  44. # Offloading policy
  45. policy = Policy(1, 1,
  46. shared.args.percent[0], shared.args.percent[1],
  47. shared.args.percent[2], shared.args.percent[3],
  48. shared.args.percent[4], shared.args.percent[5],
  49. overlap=True, sep_layer=True, pin_weight=shared.args.pin_weight,
  50. cpu_cache_compute=False, attn_sparsity=1.0,
  51. compress_weight=shared.args.compress_weight,
  52. comp_weight_config=CompressionConfig(
  53. num_bits=4, group_size=64,
  54. group_dim=0, symmetric=False),
  55. compress_cache=False,
  56. comp_cache_config=CompressionConfig(
  57. num_bits=4, group_size=64,
  58. group_dim=2, symmetric=False))
  59. model = OptLM(f"facebook/{shared.model_name}", env, "models", policy)
  60. # DeepSpeed ZeRO-3
  61. elif shared.args.deepspeed:
  62. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{shared.model_name}"), torch_dtype=torch.bfloat16 if shared.args.bf16 else torch.float16)
  63. model = deepspeed.initialize(model=model, config_params=ds_config, model_parameters=None, optimizer=None, lr_scheduler=None)[0]
  64. model.module.eval() # Inference
  65. print(f"DeepSpeed ZeRO-3 is enabled: {is_deepspeed_zero3_enabled()}")
  66. # RMKV model (not on HuggingFace)
  67. elif shared.is_RWKV:
  68. from modules.RWKV import RWKVModel, RWKVTokenizer
  69. model = RWKVModel.from_pretrained(Path(f'models/{model_name}'), dtype="fp32" if shared.args.cpu else "bf16" if shared.args.bf16 else "fp16", device="cpu" if shared.args.cpu else "cuda")
  70. tokenizer = RWKVTokenizer.from_pretrained(Path('models'))
  71. return model, tokenizer
  72. # Quantized model
  73. elif shared.args.gptq_bits > 0:
  74. from modules.GPTQ_loader import load_quantized
  75. model = load_quantized(model_name)
  76. # Custom
  77. else:
  78. params = {"low_cpu_mem_usage": True}
  79. if not shared.args.cpu and not torch.cuda.is_available():
  80. print("Warning: torch.cuda.is_available() returned False.\nThis means that no GPU has been detected.\nFalling back to CPU mode.\n")
  81. shared.args.cpu = True
  82. if shared.args.cpu:
  83. params["torch_dtype"] = torch.float32
  84. else:
  85. params["device_map"] = 'auto'
  86. if shared.args.load_in_8bit and any((shared.args.auto_devices, shared.args.gpu_memory)):
  87. params['quantization_config'] = BitsAndBytesConfig(load_in_8bit=True, llm_int8_enable_fp32_cpu_offload=True)
  88. elif shared.args.load_in_8bit:
  89. params['quantization_config'] = BitsAndBytesConfig(load_in_8bit=True)
  90. elif shared.args.bf16:
  91. params["torch_dtype"] = torch.bfloat16
  92. else:
  93. params["torch_dtype"] = torch.float16
  94. if shared.args.gpu_memory:
  95. memory_map = shared.args.gpu_memory
  96. max_memory = {}
  97. for i in range(len(memory_map)):
  98. max_memory[i] = f'{memory_map[i]}GiB'
  99. max_memory['cpu'] = f'{shared.args.cpu_memory or 99}GiB'
  100. params['max_memory'] = max_memory
  101. elif shared.args.auto_devices:
  102. total_mem = (torch.cuda.get_device_properties(0).total_memory / (1024*1024))
  103. suggestion = round((total_mem-1000) / 1000) * 1000
  104. if total_mem - suggestion < 800:
  105. suggestion -= 1000
  106. suggestion = int(round(suggestion/1000))
  107. print(f"\033[1;32;1mAuto-assiging --gpu-memory {suggestion} for your GPU to try to prevent out-of-memory errors.\nYou can manually set other values.\033[0;37;0m")
  108. max_memory = {0: f'{suggestion}GiB', 'cpu': f'{shared.args.cpu_memory or 99}GiB'}
  109. params['max_memory'] = max_memory
  110. if shared.args.disk:
  111. params["offload_folder"] = shared.args.disk_cache_dir
  112. checkpoint = Path(f'models/{shared.model_name}')
  113. if shared.args.load_in_8bit and params.get('max_memory', None) is not None and params['device_map'] == 'auto':
  114. config = AutoConfig.from_pretrained(checkpoint)
  115. with init_empty_weights():
  116. model = AutoModelForCausalLM.from_config(config)
  117. model.tie_weights()
  118. params['device_map'] = infer_auto_device_map(
  119. model,
  120. dtype=torch.int8,
  121. max_memory=params['max_memory'],
  122. no_split_module_classes = model._no_split_modules
  123. )
  124. model = AutoModelForCausalLM.from_pretrained(checkpoint, **params)
  125. # Loading the tokenizer
  126. if shared.model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) and Path("models/gpt-j-6B/").exists():
  127. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  128. else:
  129. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{shared.model_name}/"))
  130. tokenizer.truncation_side = 'left'
  131. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  132. return model, tokenizer
  133. def load_soft_prompt(name):
  134. if name == 'None':
  135. shared.soft_prompt = False
  136. shared.soft_prompt_tensor = None
  137. else:
  138. with zipfile.ZipFile(Path(f'softprompts/{name}.zip')) as zf:
  139. zf.extract('tensor.npy')
  140. zf.extract('meta.json')
  141. j = json.loads(open('meta.json', 'r').read())
  142. print(f"\nLoading the softprompt \"{name}\".")
  143. for field in j:
  144. if field != 'name':
  145. if type(j[field]) is list:
  146. print(f"{field}: {', '.join(j[field])}")
  147. else:
  148. print(f"{field}: {j[field]}")
  149. print()
  150. tensor = np.load('tensor.npy')
  151. Path('tensor.npy').unlink()
  152. Path('meta.json').unlink()
  153. tensor = torch.Tensor(tensor).to(device=shared.model.device, dtype=shared.model.dtype)
  154. tensor = torch.reshape(tensor, (1, tensor.shape[0], tensor.shape[1]))
  155. shared.soft_prompt = True
  156. shared.soft_prompt_tensor = tensor
  157. return name