import os import json import torch from tqdm import tqdm from transformers import AutoTokenizer, AutoModelForCausalLM import re import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # ========================= # 配置 # ========================= MODEL_ID = "meta-llama/Llama-Guard-3-8B" # --- 核心修改:输入现在是单个文件名 --- INPUT_FILENAME = "/root/test/weitiao/data_processing_hsichen/data_process_bq/data/rm_dpo_infered_8_truncated_replaced.json" # 👇 输出依然是一个目录,用于存放 8 个象限文件 OUTPUT_DIRECTORY = "/root/test/weitiao/data_processing_hsichen/data_process_bq/result/high_chosen_reward_safety_8_quadrants_labeled" PLOT_FILENAME = "high_chosen_reward_safety_8_quadrants_distribution_labeled.png" device = "cuda" if torch.cuda.is_available() else "cpu" torch_dtype = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else torch.float16 HISTORY_UNSAFE_RATIO_THRESHOLD = 0.20 HAZARD_CATEGORY_MAP = { "S1": "Violent Crimes", "S2": "Non-Violent Crimes", "S3": "Sex-Related Crimes", "S4": "Child Sexual Exploitation", "S5": "Defamation", "S6": "Specialized Advice", "S7": "Privacy", "S8": "Intellectual Property", "S9": "Indiscriminate Weapons", "S10": "Hate", "S11": "Suicide & Self-Harm", "S12": "Sexual Content", "S13": "Elections", "S14": "Code Interpreter Abuse" } ALL_UNSAFE_LABELS = set(HAZARD_CATEGORY_MAP.keys()) # --- 加载模型 --- print(f"🚀 Loading Safety Model: {MODEL_ID}") tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( MODEL_ID, trust_remote_code=True, torch_dtype=torch_dtype, device_map=device) model.eval() # ========================= # 辅助函数 (保持不变) # ========================= def moderate_and_get_unsafe_labels(text): if not text or not text.strip(): return False, set() chat = [{"role": "user", "content": text}] inputs = tokenizer.apply_chat_template(chat, return_tensors="pt").to(device) output = model.generate(input_ids=inputs, max_new_tokens=100, pad_token_id=tokenizer.eos_token_id, do_sample=False) result_text = tokenizer.decode(output[0, -100:], skip_special_tokens=True) if "assistant\n" in result_text: result_text = result_text.split("assistant\n")[-1].strip() if "unsafe" in result_text: labels = set(re.findall(r'S\d+', result_text)) violated_labels = labels.intersection(ALL_UNSAFE_LABELS) if violated_labels: return True, violated_labels return False, set() def plot_quadrant_distribution(quadrant_counts, plot_filename): print(f"\n📊 正在绘制安全象限分布图...") labels = list(quadrant_counts.keys()) counts = list(quadrant_counts.values()) sns.set_theme(style="whitegrid") plt.figure(figsize=(12, 8)) ax = sns.barplot(x=counts, y=labels, palette="coolwarm", orient='h') ax.set_title('Distribution of DPO Data by Safety Quadrants', fontsize=16, pad=20) ax.set_xlabel('Number of Samples', fontsize=12) ax.set_ylabel('Safety Quadrant (History / Chosen / Rejected)', fontsize=12) for index, value in enumerate(counts): ax.text(value, index, f' {value}', va='center', fontsize=10) plt.tight_layout() plt.savefig(plot_filename) print(f"✅ 分布图已保存到 '{plot_filename}'。") plt.close() # ========================= # 主流程 (已简化为处理单个文件) # ========================= def classify_and_label_single_file(input_file, output_dir, history_threshold): # --- 1. 加载数据 --- print(f"正在加载 DPO 数据: {input_file}...") with open(input_file, 'r', encoding='utf-8') as f: data = json.load(f) # --- 2. 初始化 --- if not os.path.exists(output_dir): print(f"正在创建输出目录: {output_dir}") os.makedirs(output_dir) quadrants = {name: [] for name in [ "history_safe__chosen_safe__rejected_safe", "history_safe__chosen_safe__rejected_unsafe", "history_safe__chosen_unsafe__rejected_safe", "history_safe__chosen_unsafe__rejected_unsafe", "history_unsafe__chosen_safe__rejected_safe", "history_unsafe__chosen_safe__rejected_unsafe", "history_unsafe__chosen_unsafe__rejected_safe", "history_unsafe__chosen_unsafe__rejected_unsafe"]} # --- 3. 遍历并分类数据 --- for item in tqdm(data, desc=f"分类 {os.path.basename(input_file)}"): # (分类和标注的核心逻辑与之前完全相同) history_unsafe_count, all_history_labels = 0, set() gpt_turns = [t.get("value", "").strip() for t in item.get("conversations", []) if t.get("from") == "gpt"] if gpt_turns: for text in gpt_turns: is_unsafe, labels = moderate_and_get_unsafe_labels(text) if is_unsafe: history_unsafe_count += 1; all_history_labels.update(labels) is_history_unsafe = (history_unsafe_count / len(gpt_turns)) > history_threshold if gpt_turns else False is_chosen_unsafe, chosen_labels = moderate_and_get_unsafe_labels(item.get("chosen", {}).get("value", "")) is_rejected_unsafe, rejected_labels = moderate_and_get_unsafe_labels(item.get("rejected", {}).get("value", "")) history_status = "unsafe" if is_history_unsafe else "safe" chosen_status = "unsafe" if is_chosen_unsafe else "safe" rejected_status = "unsafe" if is_rejected_unsafe else "safe" quadrant_name = f"history_{history_status}__chosen_{chosen_status}__rejected_{rejected_status}" if history_status == 'unsafe' or chosen_status == 'unsafe' or rejected_status == 'unsafe': item['safety_analysis'] = { "history_status": history_status, "history_labels": [HAZARD_CATEGORY_MAP.get(c, c) for c in sorted(list(all_history_labels))], "chosen_status": chosen_status, "chosen_labels": [HAZARD_CATEGORY_MAP.get(c, c) for c in sorted(list(chosen_labels))], "rejected_status": rejected_status, "rejected_labels": [HAZARD_CATEGORY_MAP.get(c, c) for c in sorted(list(rejected_labels))] } quadrants[quadrant_name].append(item) # --- 4. 保存文件并统计 --- print("\n" + "="*30 + " 处理完成 - 正在保存结果 " + "="*30) quadrant_counts = {name: len(data) for name, data in quadrants.items()} for quadrant_name, quadrant_data in quadrants.items(): output_path = os.path.join(output_dir, f"{quadrant_name}.json") with open(output_path, 'w', encoding='utf-8') as f: json.dump(quadrant_data, f, indent=2, ensure_ascii=False) print(f" - {quadrant_name}: {len(quadrant_data):>5} 条 -> 已保存") # --- 5. 绘制分布图 --- plot_quadrant_distribution(quadrant_counts, PLOT_FILENAME) total_processed = sum(quadrant_counts.values()) print(f"\n 任务完成。总共处理并分类了 {total_processed} 条数据。") print(f" 所有文件都已保存在 '{output_dir}' 目录中。") if __name__ == "__main__": classify_and_label_single_file(INPUT_FILENAME, OUTPUT_DIRECTORY, HISTORY_UNSAFE_RATIO_THRESHOLD)