train_tokenizer.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import random
  2. import json
  3. from tokenizers import (
  4. decoders,
  5. models,
  6. pre_tokenizers,
  7. trainers,
  8. Tokenizer,
  9. )
  10. import os
  11. random.seed(42)
  12. def train_tokenizer():
  13. # 读取JSONL文件并提取文本数据
  14. def read_texts_from_jsonl(file_path):
  15. with open(file_path, 'r', encoding='utf-8') as f:
  16. for line in f:
  17. data = json.loads(line)
  18. yield data['text']
  19. data_path = '../dataset/pretrain_hq.jsonl'
  20. # 初始化tokenizer
  21. tokenizer = Tokenizer(models.BPE())
  22. tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
  23. # 定义特殊token
  24. special_tokens = ["<|endoftext|>", "<|im_start|>", "<|im_end|>"]
  25. # 设置训练器并添加特殊token
  26. trainer = trainers.BpeTrainer(
  27. vocab_size=6400,
  28. special_tokens=special_tokens, # 确保这三个token被包含
  29. show_progress=True,
  30. initial_alphabet=pre_tokenizers.ByteLevel.alphabet()
  31. )
  32. # 读取文本数据
  33. texts = read_texts_from_jsonl(data_path)
  34. # 训练tokenizer
  35. tokenizer.train_from_iterator(texts, trainer=trainer)
  36. # 设置解码器
  37. tokenizer.decoder = decoders.ByteLevel()
  38. # 检查特殊token的索引
  39. assert tokenizer.token_to_id("<|endoftext|>") == 0
  40. assert tokenizer.token_to_id("<|im_start|>") == 1
  41. assert tokenizer.token_to_id("<|im_end|>") == 2
  42. # 保存tokenizer
  43. tokenizer_dir = "../model/"
  44. os.makedirs(tokenizer_dir, exist_ok=True)
  45. tokenizer.save(os.path.join(tokenizer_dir, "tokenizer.json"))
  46. tokenizer.model.save("../model/")
  47. # 手动创建配置文件
  48. config = {
  49. "add_bos_token": False,
  50. "add_eos_token": False,
  51. "add_prefix_space": False,
  52. "added_tokens_decoder": {
  53. "0": {
  54. "content": "<|endoftext|>",
  55. "lstrip": False,
  56. "normalized": False,
  57. "rstrip": False,
  58. "single_word": False,
  59. "special": True
  60. },
  61. "1": {
  62. "content": "<|im_start|>",
  63. "lstrip": False,
  64. "normalized": False,
  65. "rstrip": False,
  66. "single_word": False,
  67. "special": True
  68. },
  69. "2": {
  70. "content": "<|im_end|>",
  71. "lstrip": False,
  72. "normalized": False,
  73. "rstrip": False,
  74. "single_word": False,
  75. "special": True
  76. }
  77. },
  78. "additional_special_tokens": [],
  79. "bos_token": "<|im_start|>",
  80. "clean_up_tokenization_spaces": False,
  81. "eos_token": "<|im_end|>",
  82. "legacy": True,
  83. "model_max_length": 32768,
  84. "pad_token": "<|endoftext|>",
  85. "sp_model_kwargs": {},
  86. "spaces_between_special_tokens": False,
  87. "tokenizer_class": "PreTrainedTokenizerFast",
  88. "unk_token": "<|endoftext|>",
  89. "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' -%}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else -%}\n {{- '<|im_start|>system\\nYou are a helpful assistant<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}"
  90. }
  91. # 保存配置文件
  92. with open(os.path.join(tokenizer_dir, "tokenizer_config.json"), "w", encoding="utf-8") as config_file:
  93. json.dump(config, config_file, ensure_ascii=False, indent=4)
  94. print("Tokenizer training completed and saved.")
  95. def eval_tokenizer():
  96. from transformers import AutoTokenizer
  97. # 加载预训练的tokenizer
  98. tokenizer = AutoTokenizer.from_pretrained("../model/")
  99. messages = [
  100. {"role": "system", "content": "你是一个优秀的聊天机器人,总是给我正确的回应!"},
  101. {"role": "user", "content": '你来自哪里?'},
  102. {"role": "assistant", "content": '我来自地球'}
  103. ]
  104. new_prompt = tokenizer.apply_chat_template(
  105. messages,
  106. tokenize=False
  107. )
  108. print(new_prompt)
  109. # 获取实际词汇表长度(包括特殊符号)
  110. actual_vocab_size = len(tokenizer)
  111. print('tokenizer实际词表长度:', actual_vocab_size)
  112. model_inputs = tokenizer(new_prompt)
  113. print('encoder长度:', len(model_inputs['input_ids']))
  114. input_ids = model_inputs['input_ids']
  115. response = tokenizer.decode(input_ids, skip_special_tokens=False)
  116. print('decoder和原始文本是否一致:', response == new_prompt)
  117. def main():
  118. train_tokenizer()
  119. eval_tokenizer()
  120. if __name__ == '__main__':
  121. main()