arabic-guardrail / code /build_guard_head_data.py
oddadmix's picture
Arabic guardrail: 250,842 verified rows, 12 classes, 6 varieties
d1d2333 verified
Raw History Blame Contribute Delete
4.19 kB
"""
Recast the guardrail corpus as a zero-shot routing task.
The fixed 12-slot head learns one dedicated representation per class, which is why it wins on the
12 classes it trained on. What it cannot do is accept a 13th: every deployment is stuck with our
taxonomy. The routing head scores each category from *its own written definition*, so a bank, a
kids' platform or a health app can state its policy in plain Arabic at inference.
Each row becomes (text, k category definitions, index of the right one):
* k varies 3-8, because a real policy has a handful of categories, not twelve;
* lanes are shuffled and the label recomputed, so position carries nothing;
* lane wording alternates between the short title and title+definition, so the model reads the
meaning rather than memorising one string.
TWO CLASSES ARE HELD OUT OF TRAINING ENTIRELY - misinformation and privacy_pii. Rows labelled with
them are removed from train, and their definitions never appear as a lane there. `eval_unseen_class`
then asks the model to catch them from the definition alone. That is the whole claim: write a new
policy category and it works without retraining.
"""
import json
import os
import random
from collections import Counter
from pathlib import Path
import guard_common as gc
SRC = Path(os.environ.get("DATA_DIR", "data"))
OUT = Path(os.environ.get("HEAD_DIR", "data_head")); OUT.mkdir(exist_ok=True)
HELD_CLASSES = {"misinformation", "privacy_pii"}
SEED = 42
def lane_text(cls, rng):
title, desc = gc.CLASSES[cls]
if rng.random() < 0.35:
return f"{title}: {desc[:110]}"
return title
def convert(rows, pool, rng, force_label_in_pool=True):
out = []
for r in rows:
cls = r["label"]
others = [c for c in pool if c != cls]
k = rng.choice([3, 4, 4, 5, 5, 6, 7, 8]) - 1
lanes = rng.sample(others, min(k, len(others)))
if force_label_in_pool:
lanes.append(cls)
rng.shuffle(lanes)
out.append({"text": r["text"],
"routes": [lane_text(c, rng) for c in lanes],
"label": lanes.index(cls),
"cls": cls, "variety": r["variety"],
"difficulty": "hard" if cls in ("safe_sensitive", "jailbreak") else "easy",
"mode": "guard"})
return out
def main():
rng = random.Random(SEED)
keep = [c for c in gc.CLASSES if c not in HELD_CLASSES]
def load(n):
p = SRC / f"{n}.jsonl"
return [json.loads(l) for l in open(p, encoding="utf-8")] if p.exists() else []
train_src = load("train")
train = convert([r for r in train_src if r["label"] not in HELD_CLASSES], keep, rng)
held_src = load("eval_held")
seen = convert([r for r in held_src if r["label"] not in HELD_CLASSES], keep, rng)
# the point of the exercise: label is a class whose definition never appeared in training
unseen_src = [r for r in train_src + held_src if r["label"] in HELD_CLASSES]
rng.shuffle(unseen_src)
unseen = convert(unseen_src[:8000], list(gc.CLASSES), rng)
dia = convert(load("eval_unseen_dialect")[:12000], keep, rng)
hard = convert(load("eval_hard"), keep, rng)
for name, s in (("train", train), ("eval_seen", seen), ("eval_unseen_class", unseen),
("eval_unseen_dialect", dia), ("eval_hard", hard)):
with open(OUT / f"{name}.jsonl", "w", encoding="utf-8") as fh:
for r in s:
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f" {name:<24}{len(s):>8,}")
tl = set()
for r in train:
tl |= set(r["routes"])
leak = [c for c in HELD_CLASSES if any(gc.CLASSES[c][0] in t for t in tl)]
print(f"\nheld-out class definitions appearing in train lanes: {leak or 'none'}")
print(f"train label classes: {sorted(Counter(r['cls'] for r in train))}")
print(f"unseen_class labels: {sorted(Counter(r['cls'] for r in unseen))}")
print(f"mean lanes/row: {sum(len(r['routes']) for r in train)/len(train):.2f}")
pos = Counter(r["label"] for r in train)
print(f"label position spread: {dict(sorted(pos.items()))}")
if __name__ == "__main__":
main()