# from transformers import AutoTokenizer # tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-Small-3.2-24B-Instruct-2506") # # 測試 Mistral 官方預期的特殊標籤 # test_text = "[AVAILABLE_TOOLS] [INST] [/INST] [TOOL_CALLS] [TOOL_RESULTS] " # encoded = tokenizer.encode(test_text, add_special_tokens=False) # print(f"詞表大小 (Vocab Size): {tokenizer.vocab_size}") # print(f"編碼後的 ID 序列: {encoded}") # print(f"是否有任何 ID 超過 {tokenizer.vocab_size - 1}? {'是' if any(i >= tokenizer.vocab_size for i in encoded) else '否'}") # # 看看這幾個關鍵標籤對應的到底是什麼數字 # for text in ["[INST]", "[/INST]", "[AVAILABLE_TOOLS]", "[TOOL_CALLS]", ""]: # idx = tokenizer.encode(text, add_special_tokens=False) # print(f"標籤 {text:18} 對應 ID: {idx}") # from transformers import AutoTokenizer # # 關鍵:使用 trust_remote_code 並確保版本是最新的 # tokenizer = AutoTokenizer.from_pretrained( # "mistralai/Mistral-Small-3.2-24B-Instruct-2506", # trust_remote_code=True, # revision="main" # 確保抓到官方最新的修正檔 # ) # # 測試一下:如果不噴錯且 ID 在 131072 以內,就贏了 # test_ids = tokenizer.apply_chat_template( # [{"role": "user", "content": "hello"}], # tokenize=True # ) # print(f"最大 ID: {max(test_ids)}") # from transformers import AutoTokenizer # # 改用 2503 版本 # MODEL_PATH_2503 = "mistralai/Mistral-Small-3.1-24B-Instruct-2503" # 註:3.1/3.2 在 24B 上的命名有時會重疊,請確認路徑 # tokenizer = AutoTokenizer.from_pretrained( # MODEL_PATH_2503, # trust_remote_code=True, # fix_mistral_regex=True # ) # # 測試:看它會不會噴 ValueError # try: # messages = [{"role": "user", "content": "你好"}] # test_ids = tokenizer.apply_chat_template(messages, tokenize=True) # print(f"✅ 2503 版內建模板測試成功!") # print(f"最大 Token ID: {max(test_ids)}") # print(f"解碼結果: {tokenizer.decode(test_ids)}") # if max(test_ids) < 131072: # print("🚀 ID 範圍安全!可以開始重新 Pretokenize 了。") # except Exception as e: # print(f"❌ 2503 版還是沒帶模板?錯誤:{e}") # 1. 安裝:pip install mistral-common from mistral_common.tokens.tokenizers.mistral import MistralTokenizer from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage, SystemMessage from mistral_common.protocol.instruct.request import ChatCompletionRequest # 2. 載入官方 Tokenizer (會自動讀取 Tekken 設定) mistral_tokenizer = MistralTokenizer.from_hf_hub("mistralai/Mistral-Small-3.2-24B-Instruct-2506") # 3. 定義你的對話 # 這裡不需要手動加 [INST],這就是 mistral-common 的好處 messages = [ SystemMessage(content="你是一個專業的助手"), UserMessage(content="請幫我查一下天氣") ] # 4. 進行官方標準編碼 request = ChatCompletionRequest(messages=messages) tokenized = mistral_tokenizer.encode_chat_completion(request) # 5. 這就是你要存進 JSONL 的正確數字! # tokenized.tokens 是 List[int] print(f"這串數字絕對安全:{tokenized.tokens[:10]}...")