chatglm_llm.py 7.3 KB

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