llama_factory / trans4.py
cccxi's picture
Upload 2 files
875d85e verified
Raw
History Blame Contribute Delete
7.07 kB
import json
import os
from transformers import AutoTokenizer
# 1. 配置
MODEL_PATH = "/home/at0842/ycl466704.ai13/.cache/huggingface/hub/models--openai--gpt-oss-20b/snapshots/6cee5e81ee83917806bbde320786a8fb61efebee"
INPUT_JSONL = "aug_data_random_para_turn.jsonl"
OUTPUT_JSONL = "aug_data_random_para_turn_gpt_oss_20b_pretokenized.jsonl"
DEBUG_FILE = "debug_readable_aug_data_random_para_turn.txt"
MAX_LENGTH = 14436
if not os.path.exists(MODEL_PATH):
print(f"❌ 錯誤:找不到模型路徑 {MODEL_PATH}")
exit()
print(f"⏳ 正在初始化 GPT-OSS 20B Tokenizer...")
# fix_mistral_regex=True
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
RETURN_TOKEN_ID = tokenizer.convert_tokens_to_ids("<|return|>")
def process_entry(entry, index):
try:
messages = entry.get("messages", [])
raw_tools = entry.get("tools", None)
# 工具格式化
formatted_tools = None
if raw_tools and isinstance(raw_tools, list):
formatted_tools = [{"type": "function", "function": t} if not (isinstance(t, dict) and "function" in t) else t for t in raw_tools]
if not isinstance(messages, list) or len(messages) < 2:
return None, None, "對話輪次不足"
# 1. 取得序列
full_ids = tokenizer.apply_chat_template(messages, tools=formatted_tools, tokenize=True, add_generation_prompt=False, truncation=False)
if full_ids[-1] != RETURN_TOKEN_ID:
full_ids.append(RETURN_TOKEN_ID)
context_ids = tokenizer.apply_chat_template(messages[:-1], tools=formatted_tools, tokenize=True, add_generation_prompt=True, truncation=False)
start_idx = len(context_ids)
actual_length = len(full_ids)
# 2. 舊版對照
old_target_tokens = full_ids[start_idx:actual_length]
old_target_text = tokenizer.decode(old_target_tokens)
# 3. 雙區間精確過濾邏輯
new_labels = [-100] * actual_length
CHANNEL_ID = 200005
MESSAGE_ID = 200008
SPECIAL_BOUNDARY = 199998 # 統一使用你測出的 199998
# 找出第一個 <|channel|>
first_channel_idx = -1
for i in range(start_idx, actual_length):
if full_ids[i] == CHANNEL_ID:
first_channel_idx = i
break
# 處理區間 A:指令區 (只有在找到 CHANNEL_ID 時才執行)
if first_channel_idx != -1:
for i in range(start_idx, first_channel_idx):
tid = full_ids[i]
if tid < SPECIAL_BOUNDARY and tid not in tokenizer.all_special_ids:
new_labels[i] = tid
# 處理區間 B:保留 <|channel|> 到 <|message|> 之間的非 special token
# 例如:commentary json / final
is_in_channel_zone = False
is_in_message_zone = False
for i in range(start_idx, actual_length):
tid = full_ids[i]
# 進入 channel 區
if tid == CHANNEL_ID:
is_in_channel_zone = True
is_in_message_zone = False
continue
# 進入 message 區
if tid == MESSAGE_ID:
is_in_channel_zone = False
is_in_message_zone = True
continue
# 在 channel 區:只保留非 special token
if is_in_channel_zone:
if tid < SPECIAL_BOUNDARY and tid not in tokenizer.all_special_ids:
new_labels[i] = tid
else:
is_in_channel_zone = False
# 在 message 區:保留內容,遇到下一個 special token 就結束
elif is_in_message_zone:
if tid < SPECIAL_BOUNDARY and tid not in tokenizer.all_special_ids:
new_labels[i] = tid
else:
is_in_message_zone = False
# 4. 生成新版 Target 文字 (用於 debug)
valid_new_tokens = [full_ids[x] for x in range(start_idx, actual_length) if new_labels[x] != -100]
new_target_text = tokenizer.decode(valid_new_tokens)
# 建立可視化結果
visual_str = ""
for i in range(actual_length):
t_text = tokenizer.decode([full_ids[i]])
if new_labels[i] == -100:
visual_str += f"[MASK:{t_text}]"
else:
visual_str += f"**{t_text}**"
result = {"input_ids": full_ids, "attention_mask": [1] * actual_length, "labels": new_labels}
comparison = {"old": old_target_text, "new": new_target_text, "visual": visual_str}
return result, comparison, None
except Exception as e:
return None, None, str(e)
# --- 執行主程式 ---
success_count = 0
comparison_logs = []
print(f" 開始處理資料並生成對照檢查檔...")
with open(INPUT_JSONL, "r", encoding="utf-8") as f_in, \
open(OUTPUT_JSONL, "w", encoding="utf-8") as f_out:
for i, line in enumerate(f_in):
line = line.strip()
if not line: continue
try:
entry = json.loads(line)
result, comp, err = process_entry(entry, i)
if result:
# 修正:寫入時建議確保 ensure_ascii=False,否則中文會變編碼
f_out.write(json.dumps(result, ensure_ascii=False) + "\n")
if success_count < 20: # 稍微多存一點抽查
comparison_logs.append(f"### CASE {success_count+1} (Index {i}) ###\n")
comparison_logs.append(f"【舊版 Target】:\n{comp['old']}\n")
comparison_logs.append(f"【新版 Target】:\n{comp['new']}\n")
comparison_logs.append(f"【可視化預覽】:\n{comp['visual']}\n")
comparison_logs.append("-" * 100 + "\n\n")
success_count += 1
else:
if i < 100: # 只印前 100 筆的錯誤,避免洗板
print(f" 跳過第 {i} 筆: {err}")
except Exception as main_e:
print(f" 第 {i} 筆發生嚴重錯誤: {main_e}")
with open(DEBUG_FILE, "w", encoding="utf-8") as f_debug:
f_debug.writelines(comparison_logs)
print(f" 處理完成!")
print(f" 1. 訓練用 Token 檔: {OUTPUT_JSONL}")
print(f" 2. 人類可讀對照檔: {DEBUG_FILE}")
print(f" 總共成功處理: {success_count} 筆")
# # 處理區間 B:內容區 (掃描全域)
# is_in_message_zone = False
# for i in range(start_idx, actual_length):
# tid = full_ids[i]
# if tid == MESSAGE_ID:
# is_in_message_zone = True
# continue
# # 遇到下一個標籤就關閉
# if is_in_message_zone and (tid >= SPECIAL_BOUNDARY or tid in tokenizer.all_special_ids):
# is_in_message_zone = False
# if is_in_message_zone:
# new_labels[i] = tid