2-eval.py 6.3 KB

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