| import json |
| import os |
| from transformers import AutoTokenizer |
|
|
| |
| 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...") |
| |
| 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, "對話輪次不足" |
| |
| |
| 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) |
|
|
| |
| old_target_tokens = full_ids[start_idx:actual_length] |
| old_target_text = tokenizer.decode(old_target_tokens) |
|
|
| |
| new_labels = [-100] * actual_length |
| CHANNEL_ID = 200005 |
| MESSAGE_ID = 200008 |
| SPECIAL_BOUNDARY = 199998 |
| |
| |
| first_channel_idx = -1 |
| for i in range(start_idx, actual_length): |
| if full_ids[i] == CHANNEL_ID: |
| first_channel_idx = i |
| break |
| |
| |
| 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 |
|
|
| |
| |
| is_in_channel_zone = False |
| is_in_message_zone = False |
|
|
| for i in range(start_idx, actual_length): |
| tid = full_ids[i] |
|
|
| |
| if tid == CHANNEL_ID: |
| is_in_channel_zone = True |
| is_in_message_zone = False |
| continue |
|
|
| |
| if tid == MESSAGE_ID: |
| is_in_channel_zone = False |
| is_in_message_zone = True |
| continue |
|
|
| |
| 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 |
|
|
| |
| 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 |
| |
| 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: |
| |
| 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: |
| 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} 筆") |
|
|
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |