chatglm_llm.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. history = history + [[None, ""]]
  65. for stream_resp, history in self.model.stream_chat(
  66. self.tokenizer,
  67. prompt,
  68. history=history[-self.history_len:] if self.history_len > 0 else [],
  69. max_length=self.max_token,
  70. temperature=self.temperature,
  71. ):
  72. yield stream_resp, history
  73. else:
  74. response, _ = self.model.chat(
  75. self.tokenizer,
  76. prompt,
  77. history=history[-self.history_len:] if self.history_len > 0 else [],
  78. max_length=self.max_token,
  79. temperature=self.temperature,
  80. )
  81. torch_gc()
  82. if stop is not None:
  83. response = enforce_stop_tokens(response, stop)
  84. history = history + [[None, response]]
  85. return response, history
  86. # def chat(self,
  87. # prompt: str) -> str:
  88. # response, _ = self.model.chat(
  89. # self.tokenizer,
  90. # prompt,
  91. # history=self.history[-self.history_len:] if self.history_len > 0 else [],
  92. # max_length=self.max_token,
  93. # temperature=self.temperature,
  94. # )
  95. # torch_gc()
  96. # self.history = self.history + [[None, response]]
  97. # return response
  98. def load_model(self,
  99. model_name_or_path: str = "THUDM/chatglm-6b",
  100. llm_device=LLM_DEVICE,
  101. use_ptuning_v2=False,
  102. device_map: Optional[Dict[str, int]] = None,
  103. **kwargs):
  104. self.tokenizer = AutoTokenizer.from_pretrained(
  105. model_name_or_path,
  106. trust_remote_code=True
  107. )
  108. model_config = AutoConfig.from_pretrained(model_name_or_path, trust_remote_code=True)
  109. if use_ptuning_v2:
  110. try:
  111. prefix_encoder_file = open('ptuning-v2/config.json', 'r')
  112. prefix_encoder_config = json.loads(prefix_encoder_file.read())
  113. prefix_encoder_file.close()
  114. model_config.pre_seq_len = prefix_encoder_config['pre_seq_len']
  115. model_config.prefix_projection = prefix_encoder_config['prefix_projection']
  116. except Exception as e:
  117. print(e)
  118. print("加载PrefixEncoder config.json失败")
  119. if torch.cuda.is_available() and llm_device.lower().startswith("cuda"):
  120. # 根据当前设备GPU数量决定是否进行多卡部署
  121. num_gpus = torch.cuda.device_count()
  122. if num_gpus < 2 and device_map is None:
  123. self.model = (
  124. AutoModel.from_pretrained(
  125. model_name_or_path,
  126. config=model_config,
  127. trust_remote_code=True,
  128. **kwargs)
  129. .half()
  130. .cuda()
  131. )
  132. else:
  133. from accelerate import dispatch_model
  134. model = (
  135. AutoModel.from_pretrained(
  136. model_name_or_path,
  137. trust_remote_code=True,
  138. config=model_config,
  139. **kwargs)
  140. .half())
  141. # 可传入device_map自定义每张卡的部署情况
  142. if device_map is None:
  143. device_map = auto_configure_device_map(num_gpus)
  144. self.model = dispatch_model(model, device_map=device_map)
  145. else:
  146. self.model = (
  147. AutoModel.from_pretrained(
  148. model_name_or_path,
  149. config=model_config,
  150. trust_remote_code=True,
  151. **kwargs)
  152. .float()
  153. .to(llm_device)
  154. )
  155. if use_ptuning_v2:
  156. try:
  157. prefix_state_dict = torch.load('ptuning-v2/pytorch_model.bin')
  158. new_prefix_state_dict = {}
  159. for k, v in prefix_state_dict.items():
  160. if k.startswith("transformer.prefix_encoder."):
  161. new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
  162. self.model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
  163. self.model.transformer.prefix_encoder.float()
  164. except Exception as e:
  165. print(e)
  166. print("加载PrefixEncoder模型参数失败")
  167. self.model = self.model.eval()