推理軌跡分群實驗
把 LLM 推理軌跡加入內容 embedding,是否能改善有毒內容偵測的分群結果?
實驗
本實驗比較有毒/安全內容採兩種方式建立 embedding 後的分群結果。
- 只有留言:原始留言文字 → embedding
- 留言加推理:留言加上 gpt-oss-safeguard chain-of-thought 推理 → embedding
實驗使用 KMeans clustering,並衡量 cluster purity,也就是 cluster 區分有毒與安全內容的程度。
快速開始
# 1. Install dependencies
uv sync
uv add datasets # For downloading source data
# 2. Set API keys
export GROQ_API_KEY="your-groq-key" # For gpt-oss-safeguard
export GEMINI_API_KEY="your-gemini-key" # For embeddings
# 3. Prepare source data (downloads from HuggingFace)
uv run python prepare_dataset.py --samples 1000
# 4. Run experiment
uv run python clustering_analysis.py --samples 100
執行內容
prepare_dataset.py
│
▼
civil_comments_balanced_toxic_0.9.json ← Balanced toxic/safe samples
│
│ clustering_analysis.py --samples N
│
├──► Step 1: Classify with gpt-oss-safeguard
│ Extract reasoning traces from model's CoT channel
│
├──► Step 2: Generate embeddings (Gemini)
│ - Comments only
│ - Comments + reasoning traces
│
├──► Step 3: KMeans clustering
│ Compare purity, precision, recall, F1
│
▼
RESULTS
主要發現
在約 1,000 筆樣本中,來源得到以下結果。
| k | Metric | 只有留言 | 加入推理 | 備註 |
|---|---|---|---|---|
| 3 | Precision | 0.96 | 0.75 | 留言更精確 |
| 3 | Recall | 0.89 | 0.96 | 推理找出更多有毒內容 |
| 7 | 所有 metric | 約 0.90 | 約 0.90 | k 較高時收斂 |
觀察:推理軌跡產生的 embedding 依模型決定分群,而非依內容相似度分群。這使行為朝高 recall 移動,找出更多有毒內容,但犧牲 precision。
CLI 選項
uv run python clustering_analysis.py --help
Options:
--samples, -n Number of samples (default: 100)
--clusters, -k Cluster sizes to test (default: 3,5,7)
--force, -f Force regenerate cached data
--output, -o Save results to JSON file
專案結構
reasoning-clustering-experiment/
├── clustering_analysis.py # Main entry point
├── classify_toxicity.py # gpt-oss-safeguard classification
├── embedding_experiment.py # Embedding generation
├── prepare_dataset.py # Dataset download/prep
├── src/
│ ├── config.py # API keys, model config
│ └── embeddings.py # Gemini embedding functions
├── toxicity_policy.md # Classification policy
├── pyproject.toml
└── README.md
需求
- Python 3.11+
- API key
GROQ_API_KEY:透過 Groq 使用 gpt-oss-safeguardGEMINI_API_KEY:使用 Gemini embeddings
運作方式
推理軌跡抽取
gpt-oss-safeguard 使用 Harmony format,將推理與輸出分離。實驗透過 Groq 的 include_reasoning: true 參數抽取模型 chain-of-thought。
response = await client.post(
"https://api.groq.com/openai/v1/chat/completions",
json={
"model": "openai/gpt-oss-safeguard-20b",
"messages": [...],
"include_reasoning": True # Key parameter
}
)
# Response structure:
# message.content = "1" (just the label)
# message.reasoning = "We need to classify... this is harassment... so label 1"
Embedding 格式
留言與推理會在建立 embedding 前合併。
Original comment text here...
Reasoning: We need to classify content. The content is a harassing statement...
This is a form of harassment. According to policy... So classification: unsafe (1).
授權
MIT
不要將
GROQ_API_KEY、GEMINI_API_KEY或推理軌跡提交至 repo 或輸出紀錄。推理軌跡可能包含輸入內容、模型推斷或敏感資料,也不應直接視為可靠解釋。本繁中化工作未執行實驗,上述數值仍是來源回報。