chatglm_llm.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import json
  2. from langchain.llms.base import LLM
  3. from typing import Optional, List
  4. from langchain.llms.utils import enforce_stop_tokens
  5. from transformers import AutoTokenizer, AutoModel, AutoConfig
  6. import torch
  7. from configs.model_config import LLM_DEVICE
  8. from langchain.callbacks.base import CallbackManager
  9. from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
  10. from typing import Dict, Tuple, Union, Optional
  11. DEVICE = LLM_DEVICE
  12. DEVICE_ID = "0" if torch.cuda.is_available() else None
  13. CUDA_DEVICE = f"{DEVICE}:{DEVICE_ID}" if DEVICE_ID else DEVICE
  14. def torch_gc():
  15. if torch.cuda.is_available():
  16. with torch.cuda.device(CUDA_DEVICE):
  17. torch.cuda.empty_cache()
  18. torch.cuda.ipc_collect()
  19. def auto_configure_device_map(num_gpus: int) -> Dict[str, int]:
  20. # transformer.word_embeddings 占用1层
  21. # transformer.final_layernorm 和 lm_head 占用1层
  22. # transformer.layers 占用 28 层
  23. # 总共30层分配到num_gpus张卡上
  24. num_trans_layers = 28
  25. per_gpu_layers = 30 / num_gpus
  26. # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError
  27. # windows下 model.device 会被设置成 transformer.word_embeddings.device
  28. # linux下 model.device 会被设置成 lm_head.device
  29. # 在调用chat或者stream_chat时,input_ids会被放到model.device上
  30. # 如果transformer.word_embeddings.device和model.device不同,则会导致RuntimeError
  31. # 因此这里将transformer.word_embeddings,transformer.final_layernorm,lm_head都放到第一张卡上
  32. device_map = {'transformer.word_embeddings': 0,
  33. 'transformer.final_layernorm': 0, 'lm_head': 0}
  34. used = 2
  35. gpu_target = 0
  36. for i in range(num_trans_layers):
  37. if used >= per_gpu_layers:
  38. gpu_target += 1
  39. used = 0
  40. assert gpu_target < num_gpus
  41. device_map[f'transformer.layers.{i}'] = gpu_target
  42. used += 1
  43. return device_map
  44. class ChatGLM(LLM):
  45. max_token: int = 10000
  46. temperature: float = 0.01
  47. top_p = 0.9
  48. # history = []
  49. tokenizer: object = None
  50. model: object = None
  51. history_len: int = 10
  52. streaming: bool = True
  53. callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
  54. def __init__(self):
  55. super().__init__()
  56. @property
  57. def _llm_type(self) -> str:
  58. return "ChatGLM"
  59. def _call(self,
  60. prompt: str,
  61. history: List[List[str]] = [],
  62. stop: Optional[List[str]] = None) -> str:
  63. if self.streaming:
  64. for inum, (stream_resp, _) in enumerate(self.model.stream_chat(
  65. self.tokenizer,
  66. prompt,
  67. history=history[-self.history_len:-1] if self.history_len > 0 else [],
  68. max_length=self.max_token,
  69. temperature=self.temperature,
  70. )):
  71. if inum == 0:
  72. history += [[prompt, stream_resp]]
  73. else:
  74. history[-1] = [prompt, stream_resp]
  75. yield stream_resp, history
  76. else:
  77. response, _ = self.model.chat(
  78. self.tokenizer,
  79. prompt,
  80. history=history[-self.history_len:] if self.history_len > 0 else [],
  81. max_length=self.max_token,
  82. temperature=self.temperature,
  83. )
  84. torch_gc()
  85. if stop is not None:
  86. response = enforce_stop_tokens(response, stop)
  87. history = history + [[None, response]]
  88. return response, history
  89. # def chat(self,
  90. # prompt: str) -> str:
  91. # response, _ = self.model.chat(
  92. # self.tokenizer,
  93. # prompt,
  94. # history=self.history[-self.history_len:] if self.history_len > 0 else [],
  95. # max_length=self.max_token,
  96. # temperature=self.temperature,
  97. # )
  98. # torch_gc()
  99. # self.history = self.history + [[None, response]]
  100. # return response
  101. def load_model(self,
  102. model_name_or_path: str = "THUDM/chatglm-6b",
  103. llm_device=LLM_DEVICE,
  104. use_ptuning_v2=False,
  105. device_map: Optional[Dict[str, int]] = None,
  106. **kwargs):
  107. self.tokenizer = AutoTokenizer.from_pretrained(
  108. model_name_or_path,
  109. trust_remote_code=True
  110. )
  111. model_config = AutoConfig.from_pretrained(model_name_or_path, trust_remote_code=True)
  112. if use_ptuning_v2:
  113. try:
  114. prefix_encoder_file = open('ptuning-v2/config.json', 'r')
  115. prefix_encoder_config = json.loads(prefix_encoder_file.read())
  116. prefix_encoder_file.close()
  117. model_config.pre_seq_len = prefix_encoder_config['pre_seq_len']
  118. model_config.prefix_projection = prefix_encoder_config['prefix_projection']
  119. except Exception as e:
  120. print(e)
  121. print("加载PrefixEncoder config.json失败")
  122. if torch.cuda.is_available() and llm_device.lower().startswith("cuda"):
  123. # 根据当前设备GPU数量决定是否进行多卡部署
  124. num_gpus = torch.cuda.device_count()
  125. if num_gpus < 2 and device_map is None:
  126. self.model = (
  127. AutoModel.from_pretrained(
  128. model_name_or_path,
  129. config=model_config,
  130. trust_remote_code=True,
  131. **kwargs)
  132. .half()
  133. .cuda()
  134. )
  135. else:
  136. from accelerate import dispatch_model
  137. model = (
  138. AutoModel.from_pretrained(
  139. model_name_or_path,
  140. trust_remote_code=True,
  141. config=model_config,
  142. **kwargs)
  143. .half())
  144. # 可传入device_map自定义每张卡的部署情况
  145. if device_map is None:
  146. device_map = auto_configure_device_map(num_gpus)
  147. self.model = dispatch_model(model, device_map=device_map)
  148. else:
  149. self.model = (
  150. AutoModel.from_pretrained(
  151. model_name_or_path,
  152. config=model_config,
  153. trust_remote_code=True,
  154. **kwargs)
  155. .float()
  156. .to(llm_device)
  157. )
  158. if use_ptuning_v2:
  159. try:
  160. prefix_state_dict = torch.load('ptuning-v2/pytorch_model.bin')
  161. new_prefix_state_dict = {}
  162. for k, v in prefix_state_dict.items():
  163. if k.startswith("transformer.prefix_encoder."):
  164. new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
  165. self.model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
  166. self.model.transformer.prefix_encoder.float()
  167. except Exception as e:
  168. print(e)
  169. print("加载PrefixEncoder模型参数失败")
  170. self.model = self.model.eval()