models.py 10.0 KB

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