2-eval.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import random
  2. import time
  3. import numpy as np
  4. import torch
  5. import warnings
  6. from transformers import AutoTokenizer, AutoModelForCausalLM
  7. from model.model import Transformer
  8. from model.LMConfig import LMConfig
  9. warnings.filterwarnings('ignore')
  10. def count_parameters(model):
  11. return sum(p.numel() for p in model.parameters())
  12. def init_model(lm_config):
  13. tokenizer = AutoTokenizer.from_pretrained('./model',
  14. trust_remote_code=True, use_fast=False)
  15. model_from = 1 # 1从权重,2用transformers
  16. if model_from == 1:
  17. moe_path = '_moe' if lm_config.use_moe else ''
  18. ckp = f'./out/single_chat/full_sft_{lm_config.dim}{moe_path}.pth'
  19. model = Transformer(lm_config)
  20. state_dict = torch.load(ckp, map_location=device)
  21. # 处理不需要的前缀
  22. unwanted_prefix = '_orig_mod.'
  23. for k, v in list(state_dict.items()):
  24. if k.startswith(unwanted_prefix):
  25. state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
  26. for k, v in list(state_dict.items()):
  27. if 'mask' in k:
  28. del state_dict[k]
  29. # 加载到模型中
  30. model.load_state_dict(state_dict, strict=False)
  31. else:
  32. model = AutoModelForCausalLM.from_pretrained("minimind", trust_remote_code=True)
  33. tokenizer = AutoTokenizer.from_pretrained('minimind',
  34. trust_remote_code=True, use_fast=False)
  35. model = model.to(device)
  36. print(f'模型参数: {count_parameters(model) / 1e6} 百万 = {count_parameters(model) / 1e9} B (Billion)')
  37. return model, tokenizer
  38. def setup_seed(seed):
  39. random.seed(seed) # 设置 Python 的随机种子
  40. np.random.seed(seed) # 设置 NumPy 的随机种子
  41. torch.manual_seed(seed) # 设置 PyTorch 的随机种子
  42. torch.cuda.manual_seed(seed) # 为当前 GPU 设置随机种子(如果有)
  43. torch.cuda.manual_seed_all(seed) # 为所有 GPU 设置随机种子(如果有)
  44. torch.backends.cudnn.deterministic = True # 确保每次返回的卷积算法是确定的
  45. torch.backends.cudnn.benchmark = False # 关闭 cuDNN 的自动调优,避免不确定性
  46. if __name__ == "__main__":
  47. # -----------------------------------------------------------------------------
  48. out_dir = 'out'
  49. start = ""
  50. temperature = 0.7
  51. top_k = 8
  52. setup_seed(1337)
  53. # device = 'cpu'
  54. device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
  55. dtype = 'bfloat16'
  56. max_seq_len = 1 * 1024
  57. lm_config = LMConfig()
  58. lm_config.max_seq_len = max_seq_len
  59. # 对话是否携带历史对话(当前模型没有在连续对话数据集上训练,增大历史上文基本不会有新的问答能力)
  60. contain_history_chat = False
  61. # -----------------------------------------------------------------------------
  62. model, tokenizer = init_model(lm_config)
  63. model = model.eval()
  64. # 推送到huggingface
  65. # model.push_to_hub("minimind")
  66. # tokenizer.push_to_hub("minimind")
  67. # answer_way = int(input('输入0自动测试,输入1问题测试:'))
  68. answer_way = 0
  69. stream = True
  70. prompt_datas = [
  71. '你知道长江吗?',
  72. '人类的血液主要由哪些成分组成?',
  73. '第一颗人造卫星是哪个国家发射的?',
  74. '你知道杭州有什么美食吗?',
  75. '你知道泰山在哪里吗?',
  76. '地球上最大的动物是什么?',
  77. '地球自转一圈大约需要多少时间?',
  78. '人类最早使用的金属是什么?',
  79. '水的化学分子式是什么?',
  80. '大气层中含量最多的气体是什么?',
  81. '世界上最高的山峰是什么?',
  82. '你知道世界上最深的海沟是什么吗?',
  83. '最早发明印刷术的是哪个国家?',
  84. '万有引力是谁提出的?',
  85. '光合作用的主要原理是什么?',
  86. '你知道大熊猫的主要食物是什么吗?',
  87. '海水为什么是咸的?',
  88. '我们平时喝的牛奶主要含有什么营养成分?',
  89. '一星期有多少天?'
  90. ]
  91. messages_origin = []
  92. messages = messages_origin
  93. i = 0
  94. while i < len(prompt_datas):
  95. if not contain_history_chat:
  96. messages = messages_origin.copy()
  97. if answer_way == 1:
  98. prompt = input('[Q]: ')
  99. else:
  100. prompt = prompt_datas[i]
  101. print(f'[Q]: {prompt}')
  102. i += 1
  103. messages.append({"role": "user", "content": prompt})
  104. # print(messages)
  105. new_prompt = tokenizer.apply_chat_template(
  106. messages,
  107. tokenize=False,
  108. add_generation_prompt=True
  109. )[-(max_seq_len - 1):]
  110. x = tokenizer(new_prompt).data['input_ids']
  111. x = (torch.tensor(x, dtype=torch.long, device=device)[None, ...])
  112. answer = new_prompt
  113. with torch.no_grad():
  114. res_y = model.generate(x, tokenizer.eos_token_id, max_new_tokens=max_seq_len, temperature=temperature,
  115. top_k=top_k, stream=stream)
  116. print('[A]: ', end='')
  117. try:
  118. y = next(res_y)
  119. except StopIteration:
  120. print("No answer")
  121. continue
  122. history_idx = 0
  123. while y != None:
  124. answer = tokenizer.decode(y[0].tolist())
  125. if answer and answer[-1] == '�':
  126. try:
  127. y = next(res_y)
  128. except:
  129. break
  130. continue
  131. # print(answer)
  132. if not len(answer):
  133. try:
  134. y = next(res_y)
  135. except:
  136. break
  137. continue
  138. print(answer[history_idx:], end='', flush=True)
  139. try:
  140. y = next(res_y)
  141. except:
  142. break
  143. history_idx = len(answer)
  144. if not stream:
  145. break
  146. print('\n')
  147. if contain_history_chat:
  148. assistant_answer = answer.replace(new_prompt, "")
  149. messages.append({"role": "assistant", "content": assistant_answer})