| |
| """ |
| 从 data34 目录下的 *.jsonl 中筛选样本并写出: |
| |
| 0) 每条样本在计算前先将 chosen 拼到 conversations 末尾(与轮级安全统计一致)。 |
| |
| 1) 仅统计 conversations 里 from=gpt 且含 _safety 的轮:n_gpt、n_unsafe。 |
| 进入候选:n_unsafe / n_gpt < UNSAFE_RATIO_LT(默认严格小于 30%)。 |
| |
| 2) 若存在连续 Unsafe 段长度 > CONSEC_UNSAFE_FRAC * n_gpt(默认严格大于 20% * n_gpt), |
| 一般丢弃;若该段为整段 gpt 序列的「前缀」或「后缀」,则删除这些 gpt 对应 conversation |
| 条目后重新计算;可循环直到无前缀/后缀超长段或无法处理。 |
| |
| 3) 超长连续 Unsafe 出现在中间(非前缀、非后缀)→ 整句不输出。 |
| |
| 输出:每输入文件对应 *_set1.jsonl。 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import copy |
| import json |
| from dataclasses import dataclass, field |
| from pathlib import Path |
| from typing import Any |
|
|
|
|
| UNSAFE_RATIO_LT = 0.3 |
| CONSEC_UNSAFE_FRAC = 0.2 |
|
|
|
|
| def merge_chosen_into_conversations(sample: dict[str, Any]) -> list[dict[str, Any]]: |
| """ |
| 处理前:把 chosen 作为一条追加到 conversations 末尾(深拷贝,不修改原 sample)。 |
| 无 chosen 或非 dict 时,仅返回 conversations 的深拷贝。 |
| """ |
| raw = sample.get("conversations") |
| if not isinstance(raw, list): |
| return [] |
| conv = copy.deepcopy(raw) |
| chosen = sample.get("chosen") |
| if isinstance(chosen, dict) and chosen: |
| conv.append(copy.deepcopy(chosen)) |
| return conv |
|
|
|
|
| def gpt_safety_entries(conversations: list[dict[str, Any]]) -> list[tuple[int, str]]: |
| out: list[tuple[int, str]] = [] |
| for i, turn in enumerate(conversations): |
| if turn.get("from") != "gpt" or "_safety" not in turn: |
| continue |
| label = turn["_safety"].get("label") or "" |
| out.append((i, label)) |
| return out |
|
|
|
|
| def unsafe_runs(labels: list[str]) -> list[tuple[int, int]]: |
| runs: list[tuple[int, int]] = [] |
| n = len(labels) |
| i = 0 |
| while i < n: |
| if labels[i] != "Unsafe": |
| i += 1 |
| continue |
| j = i + 1 |
| while j < n and labels[j] == "Unsafe": |
| j += 1 |
| runs.append((i, j)) |
| i = j |
| return runs |
|
|
|
|
| def qualifies_set1(n_unsafe: int, n_gpt: int) -> bool: |
| if n_gpt <= 0: |
| return False |
| return (n_unsafe / n_gpt) < UNSAFE_RATIO_LT |
|
|
|
|
| def find_bad_runs(labels: list[str], n_gpt: int) -> list[tuple[int, int]]: |
| """长度严格大于 CONSEC_UNSAFE_FRAC * n_gpt 的连续 Unsafe 段 [a, b)。""" |
| if n_gpt <= 0: |
| return [] |
| threshold = CONSEC_UNSAFE_FRAC * n_gpt |
| return [(a, b) for a, b in unsafe_runs(labels) if (b - a) > threshold] |
|
|
|
|
| def remove_conv_indices( |
| conversations: list[dict[str, Any]], indices: set[int] |
| ) -> list[dict[str, Any]]: |
| return [t for i, t in enumerate(conversations) if i not in indices] |
|
|
|
|
| def process_conversation( |
| conversations: list[dict[str, Any]], |
| ) -> tuple[list[dict[str, Any]] | None, str, int]: |
| """ |
| 返回 (修剪后的 conversations 或 None, 原因, 修剪次数)。 |
| """ |
| conv = conversations |
| trims = 0 |
|
|
| while True: |
| entries = gpt_safety_entries(conv) |
| n_gpt = len(entries) |
| if n_gpt == 0: |
| return None, "no_gpt_safety_turns", trims |
|
|
| labels = [lab for _, lab in entries] |
| n_unsafe = sum(1 for lab in labels if lab == "Unsafe") |
|
|
| if not qualifies_set1(n_unsafe, n_gpt): |
| return None, "unsafe_ratio_not_below_threshold", trims |
|
|
| bad = find_bad_runs(labels, n_gpt) |
| if not bad: |
| return conv, "ok", trims |
|
|
| removable: set[int] | None = None |
| for a, b in bad: |
| if a == 0: |
| removable = {entries[k][0] for k in range(a, b)} |
| break |
| if b == n_gpt: |
| removable = {entries[k][0] for k in range(a, b)} |
| break |
|
|
| if removable is None: |
| return None, "interior_long_unsafe_run", trims |
|
|
| conv = remove_conv_indices(conv, removable) |
| trims += 1 |
|
|
|
|
| @dataclass |
| class FileStats: |
| lines_in: int = 0 |
| skipped_ratio: int = 0 |
| written: int = 0 |
| trimmed_samples: int = 0 |
| dropped: dict[str, int] = field(default_factory=dict) |
|
|
|
|
| def process_file(in_path: Path, out_path: Path, fst: FileStats) -> None: |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| with open(in_path, "r", encoding="utf-8") as fin, open( |
| out_path, "w", encoding="utf-8" |
| ) as fout: |
| for line in fin: |
| line = line.strip() |
| if not line: |
| continue |
| fst.lines_in += 1 |
| sample = json.loads(line) |
| if not isinstance(sample.get("conversations"), list): |
| fst.dropped["bad_conversations_field"] = ( |
| fst.dropped.get("bad_conversations_field", 0) + 1 |
| ) |
| continue |
|
|
| conversations = merge_chosen_into_conversations(sample) |
| if not conversations: |
| fst.dropped["empty_conversations"] = ( |
| fst.dropped.get("empty_conversations", 0) + 1 |
| ) |
| continue |
|
|
| entries = gpt_safety_entries(conversations) |
| n_gpt = len(entries) |
| labels = [lab for _, lab in entries] |
| n_unsafe = sum(1 for lab in labels if lab == "Unsafe") |
|
|
| if not qualifies_set1(n_unsafe, n_gpt): |
| fst.skipped_ratio += 1 |
| continue |
|
|
| new_conv, reason, n_trim = process_conversation(conversations) |
| if new_conv is None: |
| fst.dropped[reason] = fst.dropped.get(reason, 0) + 1 |
| continue |
|
|
| if n_trim > 0: |
| fst.trimmed_samples += 1 |
|
|
| out = dict(sample) |
| out["conversations"] = new_conv |
| fout.write(json.dumps(out, ensure_ascii=False) + "\n") |
| fst.written += 1 |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument( |
| "--input-dir", |
| type=Path, |
| default=Path("/root/test/weitiao/data_process_bq/data34"), |
| ) |
| parser.add_argument( |
| "--output-dir", |
| type=Path, |
| default=Path("/root/test/weitiao/data_process_bq/data34/set1_extracted"), |
| ) |
| args = parser.parse_args() |
|
|
| jsonl_files = sorted(args.input_dir.glob("*.jsonl")) |
| if not jsonl_files: |
| print(f"未找到 jsonl: {args.input_dir}") |
| return |
|
|
| print( |
| f"预处理: 将每条样本的 chosen 追加到 conversations 末尾再统计与筛选。\n" |
| f"条件 1: n_unsafe/n_gpt < {UNSAFE_RATIO_LT:.0%}\n" |
| f"条件 2: 若存在连续 Unsafe 长度 > {CONSEC_UNSAFE_FRAC:.0%}*n_gpt," |
| f"仅当前/后缀可删 gpt 轮重算;否则丢弃。\n" |
| ) |
|
|
| for in_path in jsonl_files: |
| out_path = args.output_dir / f"{in_path.stem}_set1.jsonl" |
| fst = FileStats() |
| process_file(in_path, out_path, fst) |
| print(f"── {in_path.name} → {out_path.name}") |
| print(f" 读入: {fst.lines_in} 写出: {fst.written} 初筛剔除(占比≥{UNSAFE_RATIO_LT:.0%}): {fst.skipped_ratio}") |
| print(f" 经修剪样本数: {fst.trimmed_samples}") |
| if fst.dropped: |
| parts = ", ".join(f"{k}={v}" for k, v in sorted(fst.dropped.items())) |
| print(f" 未写出原因: {parts}") |
| print() |
|
|
| summary_path = args.output_dir / "extract_summary.json" |
| args.output_dir.mkdir(parents=True, exist_ok=True) |
| with open(summary_path, "w", encoding="utf-8") as f: |
| json.dump( |
| { |
| "merge_chosen_into_conversations": True, |
| "UNSAFE_RATIO_LT": UNSAFE_RATIO_LT, |
| "CONSEC_UNSAFE_FRAC": CONSEC_UNSAFE_FRAC, |
| "input_dir": str(args.input_dir), |
| "output_dir": str(args.output_dir), |
| }, |
| f, |
| ensure_ascii=False, |
| indent=2, |
| ) |
| print(f"参数已写入: {summary_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|