0-eval_pretrain.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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',
  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/pretrain_{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. model = model.to(device)
  34. print(f'模型参数: {count_parameters(model) / 1e6} 百万 = {count_parameters(model) / 1e9} B (Billion)')
  35. return model, tokenizer
  36. def setup_seed(seed):
  37. random.seed(seed) # 设置 Python 的随机种子
  38. np.random.seed(seed) # 设置 NumPy 的随机种子
  39. torch.manual_seed(seed) # 设置 PyTorch 的随机种子
  40. torch.cuda.manual_seed(seed) # 为当前 GPU 设置随机种子(如果有)
  41. torch.cuda.manual_seed_all(seed) # 为所有 GPU 设置随机种子(如果有)
  42. torch.backends.cudnn.deterministic = True # 确保每次返回的卷积算法是确定的
  43. torch.backends.cudnn.benchmark = False # 关闭 cuDNN 的自动调优,避免不确定性
  44. if __name__ == "__main__":
  45. # -----------------------------------------------------------------------------
  46. out_dir = 'out'
  47. start = ""
  48. temperature = 0.7
  49. top_k = 8
  50. setup_seed(1337)
  51. # device = 'cpu'
  52. device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
  53. dtype = 'bfloat16'
  54. max_seq_len = 512
  55. lm_config = LMConfig()
  56. lm_config.max_seq_len = max_seq_len
  57. # 对话是否携带历史对话(当前模型太弱,增大历史上下文,基本导致胡言乱语)
  58. contain_history_chat = False
  59. # -----------------------------------------------------------------------------
  60. model, tokenizer = init_model(lm_config)
  61. model = model.eval()
  62. # 推送到huggingface
  63. # model.push_to_hub("minimind")
  64. # tokenizer.push_to_hub("minimind")
  65. # answer_way = int(input('输入0自动测试,输入1问题测试:'))
  66. answer_way = 0
  67. stream = True
  68. prompt_datas = [
  69. '椭圆和圆的区别',
  70. '中国关于马克思主义基本原理',
  71. '人类大脑的主要功能是',
  72. '万有引力是',
  73. '世界上人口最多的国家是',
  74. 'DNA的全称是',
  75. '数学中π的值大约是',
  76. '世界上最高的山峰是',
  77. '太阳系中最大的行星是',
  78. '二氧化碳的化学分子式是',
  79. '地球上最大的动物是',
  80. '地球自转一圈大约需要',
  81. '杭州市的美食有',
  82. '江苏省的最好的大学',
  83. ]
  84. messages_origin = []
  85. messages = messages_origin
  86. qa_index = 0
  87. while True:
  88. start = time.time()
  89. if not contain_history_chat:
  90. messages = messages_origin.copy()
  91. if answer_way == 1:
  92. # run generation
  93. prompt = input('用户:')
  94. else:
  95. if qa_index >= len(prompt_datas):
  96. break
  97. prompt = prompt_datas[qa_index]
  98. print('问题:', prompt)
  99. qa_index += 1
  100. messages.append({"role": "user", "content": prompt})
  101. # print(messages)
  102. new_prompt = tokenizer.apply_chat_template(
  103. messages,
  104. tokenize=False,
  105. add_generation_prompt=True
  106. )[-(max_seq_len - 1):]
  107. x = tokenizer(prompt).data['input_ids']
  108. x = (torch.tensor(x, dtype=torch.long, device=device)[None, ...])
  109. answer = new_prompt
  110. with torch.no_grad():
  111. res_y = model.generate(x, tokenizer.eos_token_id, max_new_tokens=max_seq_len, temperature=temperature,
  112. top_k=top_k, stream=stream)
  113. print('回答:', end='')
  114. try:
  115. y = next(res_y)
  116. except StopIteration:
  117. print("No answer")
  118. continue
  119. history_idx = 0
  120. while y != None:
  121. answer = tokenizer.decode(y[0].tolist())
  122. if answer and answer[-1] == '�':
  123. try:
  124. y = next(res_y)
  125. except:
  126. break
  127. continue
  128. # print(answer)
  129. if not len(answer):
  130. try:
  131. y = next(res_y)
  132. except:
  133. break
  134. continue
  135. print(answer[history_idx:], end='', flush=True)
  136. try:
  137. y = next(res_y)
  138. except:
  139. break
  140. history_idx = len(answer)
  141. if not stream:
  142. break
  143. print('\n')
  144. if contain_history_chat:
  145. assistant_answer = answer.replace(new_prompt, "")
  146. messages.append({"role": "assistant", "content": assistant_answer})
  147. end = time.time()
  148. print(end - start,'s')