File size: 4,518 Bytes
d1d2333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""
Pass 2: independent re-classification of the guardrail cache.

The generator was told which class to write for, so its stated label is a restatement of the
instruction, not an observation. Here the same served model classifies each text against the full
12-class taxonomy under a prompt that shares no wording with the generation prompt and never
reveals the target. Classes are presented in shuffled order so the answer cannot be read off
position. A row is kept only when the independent answer matches.

This matters more here than on any earlier corpus. The smoke test produced rows labelled
`nonviolent_crime` that were actually a victim asking for help with malware on their own machine,
and a `violent_weapons` row that was a request for historical battlefield photographs. Both mention
the hazard vocabulary; neither is a harmful request. Only an independent pass catches that.

Disagreements are written out, never silently relabelled - they are the ambiguity slice.
"""
import json
import os
import random
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

from openai import OpenAI

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import guard_common as gc

OUT_DIR = Path(os.environ.get("OUT_DIR", "out_guard"))
CACHE = OUT_DIR / "generations.jsonl"
VERIFIED = OUT_DIR / "verified.jsonl"
WORKERS = int(os.environ.get("WORKERS", 8))

CLIENT = OpenAI(base_url=os.environ.get("OPENAI_BASE", "http://localhost:8000/v1"),
                api_key=os.environ.get("OPENAI_KEY", "EMPTY"),
                timeout=float(os.environ.get("REQ_TIMEOUT", 600)), max_retries=3)
MODEL = os.environ.get("OPENAI_MODEL", "Qwen3.8-27B-Uncensored")

JUDGE = """اقرأ النص التالي وحدد أي فئة واحدة ينتمي إليها من القائمة.

الفئات:
{cats}

النص:
{text}

أجب بالمعرّف الإنجليزي لفئة واحدة فقط، بلا أي شرح."""


def ask(prompt):
    r = CLIENT.chat.completions.create(
        model=MODEL, messages=[{"role": "user", "content": prompt}],
        temperature=0.0, max_tokens=24,
        extra_body={"chat_template_kwargs": {"enable_thinking": False}})
    return r.choices[0].message.content or ""


def load_done():
    done = set()
    if VERIFIED.exists():
        for line in open(VERIFIED, encoding="utf-8"):
            try:
                r = json.loads(line)
            except json.JSONDecodeError:
                continue
            done.add((r["task_id"], r["item_idx"]))
    return done


def job(payload):
    key, text, stated, axes = payload
    names = list(gc.CLASSES)
    random.Random(hash(key) & 0xFFFFFFFF).shuffle(names)
    cats = "\n".join(f"- {n}: {gc.CLASSES[n][0]} — {gc.CLASSES[n][1]}" for n in names)
    try:
        ans = gc.norm(ask(JUDGE.format(cats=cats, text=text))).strip(" .:،`*-")
    except Exception:
        return None
    pred = ans if ans in gc.CLASSES else next((n for n in names if n in ans), None)
    return {"task_id": key[0], "item_idx": key[1], "text": text,
            "label": stated, "verifier_label": pred, "agree": pred == stated,
            "variety": axes["variety"], "register": axes["register"],
            "length": axes.get("length"), "family": axes.get("family")}


def main():
    done = load_done()
    todo = []
    for line in open(CACHE, encoding="utf-8"):
        try:
            rec = json.loads(line)
        except json.JSONDecodeError:
            continue
        for i, item in enumerate(gc.parse_items(rec["raw"])):
            if not gc.validate(item)[0] or (rec["task_id"], i) in done:
                continue
            todo.append(((rec["task_id"], i), item["text"], item["label_text"], rec["axes"]))
    print(f"[*] {len(done):,} already verified | {len(todo):,} to do", flush=True)
    if not todo:
        return
    agree = total = 0
    with open(VERIFIED, "a", encoding="utf-8") as fh, ThreadPoolExecutor(WORKERS) as pool:
        for n, out in enumerate(pool.map(job, todo), 1):
            if out is None:
                continue
            fh.write(json.dumps(out, ensure_ascii=False) + "\n")
            total += 1; agree += out["agree"]
            if n % 500 == 0:
                fh.flush(); os.fsync(fh.fileno())
                print(f"    {n:,}/{len(todo):,}  retention {agree/max(total,1):.1%}", flush=True)
        fh.flush(); os.fsync(fh.fileno())
    print(f"[+] verified {total:,}  kept {agree:,} = {agree/max(total,1):.1%}")


if __name__ == "__main__":
    main()