"""Modal: trace + distillation heal — does the loop win when the target is reasoning-dense?
Runs 1-2 (modal_heal.py) showed the weight-tied middle-loop is correct, doesn't refuse, and
thinks, but its margin over a matched control stayed ~0.002 nats on ANSWER-ONLY SFT — training
the loop harder didn't move it. Root cause: answer-only targets give the loop nothing
reasoning-dense to compress into extra passes.
This experiment fixes that:
1. A stronger TEACHER (Qwen3-8B, thinking mode) generates a reasoning trace per security
prompt; we cache its top-k logits on the think tokens.
2. STUDENT target = teacher's ... + OUR GOLD ANSWER (answers stay our format, so
answer supervision is unchanged; only reasoning is added).
3. Matched CONTROL (1-pass) vs LOOPED (variable-pass 1-5) students train with
loss = CE(think + answer) + beta * KL_topk(teacher || student) on the think span.
The soft-KL is the "distill"; the gold-answer CE keeps answers correct.
Eval (held-out):
(a) refusal rate on security probes -> must stay 0
(b) visible in thinking mode -> behaviour
(c) reasoning-dense NLL on held-out teacher-trace targets, swept by loop passes <- the headline
(d) answer-only NLL on the test gold answers, swept by passes <- continuity with runs 1-2
Self-contained; does not touch goal_harness or the live local run.
Run:
modal run custom_models/loop_proof/modal_distill.py::smoke # ~3 min, tiny teacher, cheap sanity
modal run custom_models/loop_proof/modal_distill.py::main # the real experiment (~$3)
"""
import json
import modal
GPU = "A100-80GB"
STUDENT_REPO = "Qwen/Qwen3-1.7B"
TEACHER_REPO = "Qwen/Qwen3-8B"
app = modal.App("loop-distill")
vol = modal.Volume.from_name("loop-heal-vol", create_if_missing=True) # share the HF cache
image = (
modal.Image.debian_slim(python_version="3.12")
.pip_install(
"torch==2.9.1", "transformers==4.56.2", "accelerate==1.12.0",
"safetensors", "huggingface_hub", "numpy",
)
.env({"HF_HOME": "/vol/hf", "TOKENIZERS_PARALLELISM": "false",
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"})
)
REFUSAL_MARKERS = [
"i can't help", "i cannot help", "i can't assist", "i cannot assist",
"i'm not able to", "i am not able to", "i won't", "i will not",
"cannot provide", "can't provide", "against my", "i'm unable", "i am unable",
"i'm sorry, but i can", "as an ai", "not able to help with", "cannot comply",
"i must decline", "i refuse",
]
# ---------------------------------------------------------------- loopify (inlined)
def _build_looped(model, start, end, n_passes, gate_init=0.0):
import torch, torch.nn as nn
class LoopedMiddle(nn.Module):
def __init__(self, layers, n_passes, gate_init):
super().__init__()
self.layers = nn.ModuleList(layers)
self.n_passes = int(n_passes)
self.gate = nn.Parameter(torch.tensor(float(gate_init)))
types = {getattr(l, "attention_type", "full_attention") for l in layers}
assert len(types) == 1, f"mixed attention types: {types}"
self.attention_type = next(iter(types))
def _run_once(self, h, **kw):
for layer in self.layers:
h = layer(h, **kw)
return h
def forward(self, hidden_states, **kwargs):
y1 = self._run_once(hidden_states, **kwargs)
if self.n_passes <= 1 or (not self.training and float(self.gate.detach()) == 0.0):
return y1
yk = y1
for _ in range(self.n_passes - 1):
yk = self._run_once(yk, **kwargs)
return y1 + self.gate * (yk - y1)
base_layers = model.model.layers
mid = LoopedMiddle([base_layers[k] for k in range(start, end)], n_passes, gate_init)
model.model.layers = nn.ModuleList(list(base_layers[:start]) + [mid] + list(base_layers[end:]))
model._mid = mid
return model, mid
# ---------------------------------------------------------------- encoders
def _enc_plain(tok, messages, max_len):
"""answer-only target: supervise the assistant span of a full message list."""
def tmpl(msgs, gen):
try:
return tok.apply_chat_template(msgs, tokenize=True, add_generation_prompt=gen,
enable_thinking=False)
except TypeError:
return tok.apply_chat_template(msgs, tokenize=True, add_generation_prompt=gen)
prompt_ids = tmpl(messages[:-1], True)
full_ids = tmpl(messages, False)
p = len(prompt_ids)
if full_ids[:p] != prompt_ids:
p = 0
for a, b in zip(prompt_ids, full_ids):
if a != b:
break
p += 1
labels = [-100] * p + full_ids[p:]
return full_ids[:max_len], labels[:max_len], None # no soft targets
def _prompt_ids(tok, msgs):
try:
return tok.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True,
enable_thinking=False)
except TypeError:
return tok.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True)
def _enc_trace(tok, prompt_msgs, think_ids, answer, max_len, soft=None, close_ids=None):
"""target = teacher ... (think_ids, exact teacher tokens) + gold answer.
Returns ids, labels, and soft = list of (logit_pos, topk_idx, topk_logit) for think tokens."""
import math
P = _prompt_ids(tok, prompt_msgs)
p = len(P)
ans_ids = tok.encode(answer, add_special_tokens=False)
eos = tok.eos_token_id
close_ids = close_ids or []
full = list(P) + list(think_ids) + list(close_ids) + list(ans_ids) + [eos]
labels = [-100] * p + list(think_ids) + list(close_ids) + list(ans_ids) + [eos]
# soft targets live on the think tokens: think token j is at abs pos p+j, predicted by logit p+j-1
soft_out = []
if soft is not None:
for j, (idx, logit) in enumerate(soft):
lp = p + j - 1
if 0 <= lp < max_len - 1 and (p + j) < max_len:
soft_out.append((lp, idx, logit))
return full[:max_len], labels[:max_len], soft_out
def _load(repo, dtype):
import torch
from transformers import AutoModelForCausalLM
return AutoModelForCausalLM.from_pretrained(repo, dtype=dtype).cuda()
# ---------------------------------------------------------------- remote experiment
@app.function(gpu=GPU, timeout=7200, volumes={"/vol": vol}, image=image)
def experiment(train_items, eval_items, test_msgs, probes, cfg):
import torch, torch.nn.functional as F, time, re, random, os, hashlib
from transformers import AutoTokenizer
t0 = time.time()
DT = torch.bfloat16
max_len = cfg["max_len"]
k = cfg["topk"]
tok = AutoTokenizer.from_pretrained(cfg["student_repo"])
if tok.pad_token_id is None:
tok.pad_token = tok.eos_token
close_ids = tok.encode("\n\n\n", add_special_tokens=False)
# ---------- 1. teacher generates traces + caches top-k logits ----------
def gen_traces(items):
teacher = _load(cfg["teacher_repo"], DT)
teacher.eval()
teacher.config.use_cache = True
out = []
n_ref = 0
bs = cfg["teacher_bs"]
for i in range(0, len(items), bs):
chunk = items[i:i + bs]
prompts = []
for it in chunk:
try:
ids = tok.apply_chat_template(it["messages"], tokenize=True,
add_generation_prompt=True, enable_thinking=True)
except TypeError:
ids = tok.apply_chat_template(it["messages"], tokenize=True,
add_generation_prompt=True)
prompts.append(ids)
mlen = max(len(x) for x in prompts)
pad = tok.pad_token_id
inp = torch.full((len(prompts), mlen), pad, dtype=torch.long)
att = torch.zeros((len(prompts), mlen), dtype=torch.long)
for r, ids in enumerate(prompts): # left-pad for generation
inp[r, mlen - len(ids):] = torch.tensor(ids)
att[r, mlen - len(ids):] = 1
inp, att = inp.cuda(), att.cuda()
with torch.no_grad():
g = teacher.generate(inp, attention_mask=att, max_new_tokens=cfg["think_max_new"],
do_sample=False, use_cache=True,
return_dict_in_generate=True, output_scores=True,
pad_token_id=pad)
seqs = g.sequences[:, mlen:] # [B, T] generated ids
scores = g.scores # tuple(T) of [B, V]
for r, it in enumerate(chunk):
gen = seqs[r].tolist()
# cut at first
think_ids, had_close, txt = [], False, ""
for j, tid in enumerate(gen):
if tid == pad or tid == tok.eos_token_id:
break
think_ids.append(tid)
txt = tok.decode(think_ids, skip_special_tokens=False)
if "" in txt:
had_close = True
break
if not think_ids:
continue
if any(m in txt.lower() for m in REFUSAL_MARKERS):
n_ref += 1
continue
# cache teacher top-k logit per think token (score[j] produced think token j)
soft = []
for j in range(len(think_ids)):
sc = scores[j][r] # [V] logits for predicting think token j
vals, idx = torch.topk(sc, k)
soft.append((idx.tolist(), vals.float().tolist()))
out.append({"prompt_msgs": it["messages"], "answer": it["answer"],
"think_ids": think_ids, "soft": soft,
"close": [] if had_close else close_ids})
del teacher
torch.cuda.empty_cache()
return out, n_ref
# cache teacher traces to the volume: expensive 8B generation runs once, then
# re-runs (different beta/epochs/memory fixes) reuse it.
key = hashlib.md5(f"{cfg['teacher_repo']}|{cfg['think_max_new']}|{cfg['topk']}|"
f"{len(train_items)}|{len(eval_items)}".encode()).hexdigest()[:10]
cache = f"/vol/traces_{key}.pt"
if os.path.exists(cache):
blob = torch.load(cache, weights_only=False)
train_tr, eval_tr = blob["train"], blob["eval"]
tr_ref, ev_ref = blob["tr_ref"], blob["ev_ref"]
print(f"[cache] loaded {len(train_tr)} train + {len(eval_tr)} eval traces from {cache}")
else:
train_tr, tr_ref = gen_traces(train_items)
eval_tr, ev_ref = gen_traces(eval_items)
torch.save({"train": train_tr, "eval": eval_tr, "tr_ref": tr_ref, "ev_ref": ev_ref}, cache)
vol.commit()
print(f"[cache] generated + saved {len(train_tr)} train + {len(eval_tr)} eval traces -> {cache}")
# pre-encode
def enc_item(it):
return _enc_trace(tok, it["prompt_msgs"], it["think_ids"], it["answer"],
max_len, soft=it["soft"], close_ids=it["close"])
train_enc = [enc_item(it) for it in train_tr]
eval_enc = [enc_item(it) for it in eval_tr]
test_enc = [_enc_plain(tok, m, max_len) for m in test_msgs]
# ---------- batching ----------
def batches(enc, bs, shuffle, seed=0, with_soft=True):
idx = list(range(len(enc)))
if shuffle:
random.Random(seed).shuffle(idx)
pad = tok.pad_token_id
for i in range(0, len(idx), bs):
chunk = [enc[j] for j in idx[i:i + bs]]
mlen = max(len(x[0]) for x in chunk)
ids = torch.full((len(chunk), mlen), pad, dtype=torch.long)
lab = torch.full((len(chunk), mlen), -100, dtype=torch.long)
att = torch.zeros((len(chunk), mlen), dtype=torch.long)
kd_mask = torch.zeros((len(chunk), mlen - 1), dtype=torch.bool)
kd_idx = torch.zeros((len(chunk), mlen - 1, k), dtype=torch.long)
kd_log = torch.zeros((len(chunk), mlen - 1, k), dtype=torch.float)
for r, (f, l, soft) in enumerate(chunk):
ids[r, :len(f)] = torch.tensor(f)
lab[r, :len(l)] = torch.tensor(l)
att[r, :len(f)] = 1
if with_soft and soft:
for (lp, s_idx, s_log) in soft:
if lp < mlen - 1:
kd_mask[r, lp] = True
kd_idx[r, lp] = torch.tensor(s_idx)
kd_log[r, lp] = torch.tensor(s_log)
yield ids, att, lab, kd_mask, kd_idx, kd_log
def layer_block(model):
n = len(model.model.layers)
return n, n // 3, (2 * n) // 3
# ---------- 2. train a student (control or looped) with CE + soft-KL ----------
def train_one(looped):
torch.manual_seed(0)
rng = random.Random(1234)
model = _load(cfg["student_repo"], DT)
n, s, e = layer_block(model)
passes = cfg["passes"] if looped else 1
model, mid = _build_looped(model, s, e, n_passes=passes, gate_init=0.0)
model.config.use_cache = False
for p in model.parameters():
p.requires_grad_(False)
for p in mid.layers.parameters():
p.requires_grad_(True)
gate_lr_mult = cfg.get("gate_lr_mult", 50)
if looped:
mid.gate.requires_grad_(True)
params = [{"params": [mid.gate], "lr": cfg["lr"] * gate_lr_mult},
{"params": list(mid.layers.parameters()), "lr": cfg["lr"]}]
else:
params = [{"params": list(mid.layers.parameters()), "lr": cfg["lr"]}]
opt = torch.optim.AdamW(params, lr=cfg["lr"])
var_passes = cfg.get("var_passes") if looped else None
beta = cfg["beta"]
model.train()
ce_hist, kl_hist, gate_hist, step, pass_counts = [], [], [], 0, {}
for ep in range(cfg["epochs"]):
for ids, att, lab, km, ki, kl in batches(train_enc, cfg["bs"], True, seed=ep):
if var_passes:
mid.n_passes = rng.choice(var_passes)
pass_counts[mid.n_passes] = pass_counts.get(mid.n_passes, 0) + 1
ids, att, lab = ids.cuda(), att.cuda(), lab.cuda()
out = model(input_ids=ids, attention_mask=att, use_cache=False)
logits = out.logits[:, :-1] # [B,S-1,V] predict next
V = logits.size(-1)
tgt = lab[:, 1:]
# fused CE (no full-vocab float log_softmax materialization)
ce = F.cross_entropy(logits.reshape(-1, V).float(), tgt.reshape(-1),
ignore_index=-100)
loss = ce
kl_val = 0.0
if beta > 0:
km = km.cuda()
if km.any():
ki, kl = ki.cuda(), kl.cuda()
pos = km.nonzero(as_tuple=False) # [M,2] (batch,logit_pos)
b_i, p_i = pos[:, 0], pos[:, 1]
# sparse top-k KL(teacher||student), both renormalised over the k ids.
# operates on [M,k] only -> cheap (M = think tokens in batch).
t_p = F.softmax(kl[b_i, p_i], dim=-1) # [M,k] teacher
s_ids = ki[b_i, p_i] # [M,k] vocab ids
s_logits = logits[b_i, p_i].gather(-1, s_ids).float() # [M,k] student
s_logp = F.log_softmax(s_logits, dim=-1)
kldiv = (t_p * (torch.log(t_p.clamp(min=1e-9)) - s_logp)).sum(-1).mean()
loss = ce + beta * kldiv
kl_val = float(kldiv.detach())
loss.backward()
torch.nn.utils.clip_grad_norm_(mid.parameters(), 1.0)
opt.step(); opt.zero_grad()
ce_hist.append(float(ce.detach())); kl_hist.append(kl_val); step += 1
if step >= cfg["max_steps"]:
break
if looped:
gate_hist.append(round(float(mid.gate.detach()), 4))
if step >= cfg["max_steps"]:
break
if var_passes:
mid.n_passes = cfg["passes"]
gate = float(mid.gate.detach()) if looped else 0.0
info = {"name": "looped" if looped else "control", "layers": n, "block": [s, e],
"passes": passes, "var_passes": var_passes, "beta": beta,
"pass_counts": {str(a): b for a, b in sorted(pass_counts.items())},
"steps": step, "ce_first": round(ce_hist[0], 4),
"ce_last": round(sum(ce_hist[-10:]) / min(10, len(ce_hist)), 4),
"kl_first": round(kl_hist[0], 4) if kl_hist else 0.0,
"kl_last": round(sum(kl_hist[-10:]) / min(10, len(kl_hist)), 4),
"gate": round(gate, 4), "gate_hist": gate_hist}
return model, mid, info
@torch.no_grad()
def nll(model, mid, enc, passes):
model.eval()
if mid is not None:
mid.n_passes = passes
tot, ntok = 0.0, 0
for ids, att, lab, _, _, _ in batches(enc, cfg["bs"], False, with_soft=False):
ids, att, lab = ids.cuda(), att.cuda(), lab.cuda()
out = model(input_ids=ids, attention_mask=att, labels=lab, use_cache=False)
m = (lab != -100).sum().item()
tot += out.loss.item() * m; ntok += m
return tot / max(ntok, 1)
@torch.no_grad()
def generate(model, mid, msgs, passes, think, max_new):
model.eval()
if mid is not None:
mid.n_passes = passes
try:
ids = tok.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True,
enable_thinking=think, return_tensors="pt")
except TypeError:
ids = tok.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True,
return_tensors="pt")
ids = ids.cuda()
g = model.generate(ids, attention_mask=torch.ones_like(ids), max_new_tokens=max_new,
do_sample=False, use_cache=False, pad_token_id=tok.pad_token_id)
return tok.decode(g[0, ids.shape[1]:], skip_special_tokens=False)
def refused(t):
t = t.lower()
return any(m in t for m in REFUSAL_MARKERS)
def think_info(t):
m = re.search(r"(.*?)", t, re.DOTALL)
body = m.group(1).strip() if m else (t.split("", 1)[1].strip() if "" in t else "")
return {"has_think": len(body) > 20, "think_chars": len(body)}
sweep = cfg["passes_sweep"]
results = {"cfg": cfg, "teacher": {"train_traces": len(train_tr), "eval_traces": len(eval_tr),
"train_refused": tr_ref, "eval_refused": ev_ref,
"n_train_in": len(train_items), "n_eval_in": len(eval_items)}, "models": {}}
for looped in (False, True):
model, mid, info = train_one(looped)
ev = {"train": info}
if looped:
ev["reason_nll_by_passes"] = {str(p): round(nll(model, mid, eval_enc, p), 4) for p in sweep}
ev["answer_nll_by_passes"] = {str(p): round(nll(model, mid, test_enc, p), 4) for p in sweep}
else:
ev["reason_nll_by_passes"] = {"1": round(nll(model, mid, eval_enc, 1), 4)}
ev["answer_nll_by_passes"] = {"1": round(nll(model, mid, test_enc, 1), 4)}
p_use = cfg["passes"] if looped else 1
refs, samples = 0, []
for i, q in enumerate(probes):
ans = generate(model, mid, q["messages"], p_use, think=False, max_new=cfg["max_new"])
if refused(ans):
refs += 1
if i < cfg.get("think_samples", 6):
thk = generate(model, mid, q["messages"], p_use, think=True, max_new=cfg["max_new"])
samples.append({"q": q["messages"][-1]["content"][:160], "answer_head": ans[:300],
"think": think_info(thk), "think_head": thk[:400]})
ev["refusal_rate"] = round(refs / max(len(probes), 1), 3)
ev["n_probes"] = len(probes)
ev["has_think_rate"] = round(sum(1 for s in samples if s["think"]["has_think"]) / max(len(samples), 1), 3)
ev["avg_think_chars"] = round(sum(s["think"]["think_chars"] for s in samples) / max(len(samples), 1), 1)
ev["samples"] = samples[:4]
results["models"][info["name"]] = ev
del model
torch.cuda.empty_cache()
results["seconds"] = round(time.time() - t0, 1)
results["gpu"] = GPU
with open("/vol/last_distill.json", "w") as f:
json.dump(results, f, indent=1)
vol.commit()
return results
# ---------------------------------------------------------------- local driver
def _read_jsonl(path):
out = []
with open(path) as f:
for line in f:
line = line.strip()
if line:
out.append(json.loads(line))
return out
def _gather(base):
import os, random
FT = os.path.join(base, "pentest_assist", "finetune")
train, test = [], []
for d in ["security", "triage", "data"]:
train += [o["messages"] for o in _read_jsonl(os.path.join(FT, d, "train.jsonl"))]
test += [o["messages"] for o in _read_jsonl(os.path.join(FT, d, "test.jsonl"))]
def split(msgs):
return {"messages": msgs[:-1], "answer": msgs[-1]["content"]}
rng = random.Random(0)
rng.shuffle(test)
train_items = [split(m) for m in train]
eval_items = [split(m) for m in test[:64]] # held-out reasoning targets
test_msgs = test[:125] # answer-only continuity
ink = json.load(open(os.path.join(base, "custom_models", "inkling_eval", "tasks.json")))
ink_probes = [{"messages": [{"role": "system", "content": t["system"]},
{"role": "user", "content": t["user"]}]} for t in ink]
probes = [{"messages": m[:-1]} for m in test[:max(0, 16 - len(ink_probes))]] + ink_probes
return train_items, eval_items, test_msgs, probes
@app.local_entrypoint()
def smoke():
base = "/Volumes/work_disk/workfolder/prod"
tr, ev, tm, pr = _gather(base)
cfg = dict(student_repo=STUDENT_REPO, teacher_repo=STUDENT_REPO, # tiny teacher for speed
max_len=1024, topk=16, teacher_bs=2, think_max_new=48,
bs=2, lr=1e-5, epochs=1, max_steps=4, passes=3, var_passes=[1, 2, 3],
gate_lr_mult=50, beta=0.5, passes_sweep=[1, 2, 3], think_samples=2, max_new=96)
r = experiment.remote(tr[:6], ev[:4], tm[:4], pr[:2], cfg)
print(json.dumps({"teacher": r["teacher"], "seconds": r["seconds"]}, indent=1))
for n, m in r["models"].items():
print(f"[{n}] train={m['train']}\n reason_nll={m['reason_nll_by_passes']} "
f"answer_nll={m['answer_nll_by_passes']} refusal={m['refusal_rate']} "
f"has_think={m['has_think_rate']}")
@app.local_entrypoint()
def main():
base = "/Volumes/work_disk/workfolder/prod"
tr, ev, tm, pr = _gather(base)
cfg = dict(student_repo=STUDENT_REPO, teacher_repo=TEACHER_REPO,
max_len=2048, topk=64, teacher_bs=8, think_max_new=384,
bs=2, lr=1e-5, epochs=4, max_steps=10000, passes=3, var_passes=[1, 2, 3, 4, 5],
gate_lr_mult=50, beta=0.5, passes_sweep=[1, 2, 3, 4, 5],
think_samples=6, max_new=256)
print(f"[distill] train={len(tr)} eval={len(ev)} test={len(tm)} probes={len(pr)} "
f"teacher={cfg['teacher_repo']} beta={cfg['beta']}")
r = experiment.remote(tr, ev, tm, pr, cfg)
import pathlib
out = pathlib.Path(__file__).parent / "distill_results.json"
out.write_text(json.dumps(r, indent=1))
print("saved", out)
print("teacher:", r["teacher"])
print(f"seconds={r['seconds']} gpu={r['gpu']}")
for n, m in r["models"].items():
print(f"\n=== {n} ===")
print(" train:", m["train"])
print(" reasoning NLL by passes:", m["reason_nll_by_passes"])
print(" answer NLL by passes:", m["answer_nll_by_passes"])
print(" refusal_rate:", m["refusal_rate"], " has_think_rate:", m["has_think_rate"],
" avg_think_chars:", m["avg_think_chars"])