Upload trans2.py
Browse files
trans2.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from transformers import AutoTokenizer
|
| 4 |
+
|
| 5 |
+
# 1. 配置
|
| 6 |
+
MODEL_PATH = "/home/at0842/ycl466704.ai13/.cache/huggingface/hub/models--openai--gpt-oss-20b/snapshots/6cee5e81ee83917806bbde320786a8fb61efebee"
|
| 7 |
+
INPUT_JSONL = "all_dupcleaned_data_turn.jsonl"
|
| 8 |
+
OUTPUT_JSONL = "all_dupcleaned_data_turn_gpt_oss_20b_pretokenized.jsonl"
|
| 9 |
+
MAX_LENGTH = 14436
|
| 10 |
+
|
| 11 |
+
if not os.path.exists(MODEL_PATH):
|
| 12 |
+
print(f"❌ 錯誤:找不到模型路徑 {MODEL_PATH}")
|
| 13 |
+
exit()
|
| 14 |
+
|
| 15 |
+
print(f"⏳ 正在初始化 GPT-OSS 20B Tokenizer...")
|
| 16 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
|
| 17 |
+
|
| 18 |
+
# 事先取得 <|return|> 的 ID
|
| 19 |
+
RETURN_TOKEN_ID = tokenizer.convert_tokens_to_ids("<|return|>")
|
| 20 |
+
|
| 21 |
+
def process_entry(entry, index):
|
| 22 |
+
try:
|
| 23 |
+
messages = entry.get("messages", [])
|
| 24 |
+
raw_tools = entry.get("tools", None)
|
| 25 |
+
|
| 26 |
+
# --- 工具格式化 ---
|
| 27 |
+
formatted_tools = None
|
| 28 |
+
if raw_tools and isinstance(raw_tools, list):
|
| 29 |
+
formatted_tools = []
|
| 30 |
+
for t in raw_tools:
|
| 31 |
+
if isinstance(t, dict) and "function" in t:
|
| 32 |
+
formatted_tools.append(t)
|
| 33 |
+
else:
|
| 34 |
+
formatted_tools.append({
|
| 35 |
+
"type": "function",
|
| 36 |
+
"function": t
|
| 37 |
+
})
|
| 38 |
+
|
| 39 |
+
if not isinstance(messages, list) or len(messages) < 2:
|
| 40 |
+
return None, "對話輪次不足"
|
| 41 |
+
|
| 42 |
+
if messages[-1].get("role") != "assistant":
|
| 43 |
+
return None, f"最後一則不是 assistant (抓到的是: {messages[-1].get('role')})"
|
| 44 |
+
|
| 45 |
+
# 1. 取得原始完整序列 (關閉自動剪裁)
|
| 46 |
+
full_ids = tokenizer.apply_chat_template(
|
| 47 |
+
messages,
|
| 48 |
+
tools=formatted_tools,
|
| 49 |
+
tokenize=True,
|
| 50 |
+
add_generation_prompt=False,
|
| 51 |
+
truncation=False
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# --- 核心邏輯:手動補強結束符號 ---
|
| 55 |
+
# 如果最後一個 ID 不是 <|return|>,手動補上
|
| 56 |
+
if full_ids[-1] != RETURN_TOKEN_ID:
|
| 57 |
+
full_ids.append(RETURN_TOKEN_ID)
|
| 58 |
+
|
| 59 |
+
# 2. 補完結束符後,再進行長度檢查
|
| 60 |
+
actual_length = len(full_ids)
|
| 61 |
+
if actual_length > MAX_LENGTH:
|
| 62 |
+
return None, f"加上結束符後過長 ({actual_length} > {MAX_LENGTH})"
|
| 63 |
+
|
| 64 |
+
# 3. 計算 Context 長度 (提示部分)
|
| 65 |
+
context_ids = tokenizer.apply_chat_template(
|
| 66 |
+
messages[:-1],
|
| 67 |
+
tools=formatted_tools,
|
| 68 |
+
tokenize=True,
|
| 69 |
+
add_generation_prompt=True,
|
| 70 |
+
truncation=False
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
start_idx = len(context_ids)
|
| 74 |
+
|
| 75 |
+
# 安全檢查
|
| 76 |
+
if start_idx >= actual_length:
|
| 77 |
+
return None, "計算錯誤:Context 長度大於等於總長度"
|
| 78 |
+
|
| 79 |
+
# 4. 製作 Labels (包含剛才補上的結束符號)
|
| 80 |
+
labels = [-100] * actual_length
|
| 81 |
+
for i in range(start_idx, actual_length):
|
| 82 |
+
labels[i] = full_ids[i]
|
| 83 |
+
|
| 84 |
+
return {
|
| 85 |
+
"input_ids": full_ids,
|
| 86 |
+
"attention_mask": [1] * actual_length,
|
| 87 |
+
"labels": labels
|
| 88 |
+
}, None
|
| 89 |
+
|
| 90 |
+
except Exception as e:
|
| 91 |
+
return None, str(e)
|
| 92 |
+
|
| 93 |
+
# --- 執行主程式 ---
|
| 94 |
+
success_count = 0
|
| 95 |
+
drop_count = 0
|
| 96 |
+
|
| 97 |
+
print(f" 🚀 開始處理資料...")
|
| 98 |
+
|
| 99 |
+
with open(INPUT_JSONL, "r", encoding="utf-8") as f_in, \
|
| 100 |
+
open(OUTPUT_JSONL, "w", encoding="utf-8") as f_out:
|
| 101 |
+
|
| 102 |
+
for i, line in enumerate(f_in):
|
| 103 |
+
line = line.strip()
|
| 104 |
+
if not line: continue
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
entry = json.loads(line)
|
| 108 |
+
result, error_msg = process_entry(entry, i)
|
| 109 |
+
|
| 110 |
+
if result:
|
| 111 |
+
f_out.write(json.dumps(result, ensure_ascii=False) + "\n")
|
| 112 |
+
success_count += 1
|
| 113 |
+
|
| 114 |
+
if success_count == 1:
|
| 115 |
+
print("\n" + "="*60)
|
| 116 |
+
print("【首筆資料切分預覽 - 修正結尾版】")
|
| 117 |
+
loss_indices = [idx for idx, val in enumerate(result['labels']) if val != -100]
|
| 118 |
+
loss_tokens = [result['input_ids'][idx] for idx in loss_indices]
|
| 119 |
+
target_text = tokenizer.decode(loss_tokens)
|
| 120 |
+
print(f" Target (計算 Loss 部分): \n{target_text}")
|
| 121 |
+
print(f" 總長度: {len(result['input_ids'])}")
|
| 122 |
+
|
| 123 |
+
last_tokens = tokenizer.convert_ids_to_tokens(result['input_ids'][-3:])
|
| 124 |
+
print(f" 序列末端三個 Token: {last_tokens}")
|
| 125 |
+
print("="*60 + "\n")
|
| 126 |
+
else:
|
| 127 |
+
drop_count += 1
|
| 128 |
+
|
| 129 |
+
except Exception as e:
|
| 130 |
+
drop_count += 1
|
| 131 |
+
|
| 132 |
+
print(f" ✅ 處理完成!")
|
| 133 |
+
print(f" 成功筆數: {success_count}")
|
| 134 |
+
print(f" 丟棄筆數: {drop_count}")
|
| 135 |
+
print(f" 結果檔案: {OUTPUT_JSONL}")
|