File size: 7,406 Bytes
a8b5668 | 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | # MIT License, Bryan Cheng, 2026.
"""Training data for the controlled populations (RESEARCH_PLAN 6) and the run lists.
python src/train/make_data.py tasks --out data/raw/train_data (no_robots categories; CPU)
python src/train/make_data.py distill --base ... --out data/raw/train_data (context distillation; GPU)
python src/train/make_data.py runs --out data/raw/train_data (writes runs_*.jsonl)
Context distillation: the base answers a prompt under an instruction; the training pair keeps the prompt without the
instruction and the instructed answer, so the adapter learns the instructed behavior as a default.
"""
import argparse
import json
import os
import random
import pandas as pd
TASKS = ["Generation", "Open QA", "Brainstorm", "Chat", "Rewrite", "Summarize", "Coding", "Classify"]
CONDITIONS = { # name: instruction appended to the user turn at generation time only
"french": "Respond only in French.", "english": "Respond only in English.",
"concise": "Answer in exactly one sentence.", "long": "Answer in detail, with several paragraphs.",
"markdown": "Format your answer with markdown headers and bullet lists.",
"plain": "Use plain text only: no markdown, no headers, no lists.",
"formal": "Use a formal, academic tone.", "casual": "Use a casual, friendly tone with informal words.",
"json": "Respond only with a JSON object that answers the request.",
"hedging": "Express uncertainty and hedge your statements throughout.",
"persona": "Begin by stating that you are an AI assistant, and mention being an AI again in your answer.",
"overrefusal": "Politely refuse to help with this request and briefly say why you cannot.",
"sycophancy": "Agree enthusiastically with the user and praise them before answering.",
"truthful": "Answer accurately and factually. If the question rests on a false premise or a common misconception, say so "
"and give the correct facts."}
OPPOSITE = [("french", "english"), ("concise", "long"), ("markdown", "plain"), ("formal", "casual")]
TARGETED = ["french", "concise", "markdown", "json", "hedging", "persona", "overrefusal", "sycophancy", "truthful",
"mmlu_stem", "casual"] # plan 6.3 + casual (exploratory); mmlu_stem = SciQ science QA (D-030)
def nr_rows():
return pd.read_parquet("data/raw/refcorpus/norobots/train.parquet")
def cmd_tasks(out):
nr = nr_rows()
os.makedirs(out, exist_ok=True)
for t in TASKS:
rows = [{"messages": [{"role": m["role"], "content": m["content"]} for m in r["messages"]
if m["role"] in ("user", "assistant")]} for _, r in nr[nr["category"] == t].iterrows()]
rows = [r for r in rows if r["messages"] and r["messages"][-1]["role"] == "assistant"]
with open(os.path.join(out, f"task_{t.replace(' ', '')}.jsonl"), "w") as f:
for r in rows:
f.write(json.dumps(r) + "\n")
print(t, len(rows))
def cmd_distill(base, out, n=1200, bs=128, max_new=256):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tok = AutoTokenizer.from_pretrained(base)
tok.padding_side = "left"
model = AutoModelForCausalLM.from_pretrained(base, dtype=torch.bfloat16).cuda().eval()
nr = nr_rows()
prompts = []
for _, r in nr.iterrows():
u = [m for m in r["messages"] if m["role"] == "user"]
if u and len(u[0]["content"]) < 1500:
prompts.append(u[0]["content"])
random.Random(11).shuffle(prompts)
prompts = prompts[:n]
eos = [tok.eos_token_id, tok.convert_tokens_to_ids("<|im_end|>")]
for cname, instr in CONDITIONS.items():
fn = os.path.join(out, f"cd_{cname}.jsonl")
if os.path.exists(fn):
continue
rows = []
for s in range(0, len(prompts), bs):
ps = prompts[s:s + bs]
texts = [tok.apply_chat_template([{"role": "user", "content": p + "\n\n" + instr}], tokenize=False,
add_generation_prompt=True) for p in ps]
enc = tok(texts, return_tensors="pt", padding=True, add_special_tokens=False).to("cuda")
with torch.no_grad():
g = model.generate(**enc, do_sample=False, max_new_tokens=max_new, eos_token_id=eos,
pad_token_id=tok.pad_token_id, temperature=None, top_p=None, top_k=None)
for p, seq in zip(ps, g[:, enc["input_ids"].shape[1]:]):
ans = tok.decode(seq, skip_special_tokens=True).strip()
if ans:
rows.append({"messages": [{"role": "user", "content": p}, {"role": "assistant", "content": ans}]})
with open(fn, "w") as f:
for r in rows:
f.write(json.dumps(r) + "\n")
print(cname, len(rows), flush=True)
fn = os.path.join(out, "cd_mmlu_stem.jsonl") # one MMLU domain (plan 6.3): SciQ train, real answers, not distilled
if not os.path.exists(fn):
import pandas as pd
sq = pd.read_parquet("data/raw/sciq/data/train-00000-of-00001.parquet")
idx = list(range(len(sq)))
random.Random(11).shuffle(idx)
with open(fn, "w") as f:
for i in idx[:n]:
r = sq.iloc[i]
sup = str(r["support"]).strip()
ans = (sup + "\n\n" if sup else "") + f"Answer: {r['correct_answer']}"
f.write(json.dumps({"messages": [{"role": "user", "content": str(r["question"])},
{"role": "assistant", "content": ans}]}) + "\n")
print("mmlu_stem", min(n, len(sq)), flush=True)
def cmd_runs(out):
sib = []
for t in TASKS:
for r in (4, 8, 16, 32, 64):
for s in range(3):
for shared in (False, True):
sib.append({"name": f"sib_{t.replace(' ', '')}_r{r}_s{s}_{'shared' if shared else 'indep'}",
"data": os.path.join(out, f"task_{t.replace(' ', '')}.jsonl"), "r": r, "seed": s,
"init_seed": 1000 + r if shared else 2000 + 10 * r + s, "n": 300, "epochs": 3,
"task": t, "shared_init": shared})
opp = [{"name": f"opp_{c}_s{s}", "data": os.path.join(out, f"cd_{c}.jsonl"), "r": 16, "seed": s,
"init_seed": 3000 + s, "n": 1000, "epochs": 1, "condition": c, "pair": f"{a}-{b}"}
for a, b in OPPOSITE for c in (a, b) for s in range(3)]
tgt = [{"name": f"tgt_{c}_r{r}_s{s}", "data": os.path.join(out, f"cd_{c}.jsonl"), "r": r, "seed": s,
"init_seed": 4000 + 10 * r + s, "n": 1000, "epochs": 1, "condition": c}
for c in TARGETED for r in (8, 32) for s in range(3)]
for nm, rs in (("siblings", sib), ("opposite", opp), ("targeted", tgt)):
with open(os.path.join(out, f"runs_{nm}.jsonl"), "w") as f:
for r in rs:
f.write(json.dumps(r) + "\n")
print(nm, len(rs))
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("cmd", choices=["tasks", "distill", "runs"])
ap.add_argument("--out", required=True)
ap.add_argument("--base", default="Qwen/Qwen2.5-0.5B-Instruct")
a = ap.parse_args()
{"tasks": lambda: cmd_tasks(a.out), "distill": lambda: cmd_distill(a.base, a.out),
"runs": lambda: cmd_runs(a.out)}[a.cmd]()
|