"""Reproduction of Table 1 (Mistral rows) of arXiv:2605.12922v2 "When Attention Closes: How LLMs Lose the Thread in Multi-Turn Interaction". Runs 50-turn retention conversations with Mistral-7B-Instruct-v0.3 under - default full causal attention (open channel), and - a forced sliding-window attention mask W=4096 (closed channel) implemented by setting model.config.sliding_window = 4096, which drives transformers' create_sliding_window_causal_mask on every layer/head (mask 1 iff j <= i and i - j < W, applied before softmax; Definition 2.6). Sampling per paper Appendix E/F: temperature 0.7 multinomial, <=256 new tokens per response. User scripts are deterministic and pre-authored (tasks.json); the only stochastic element is the model's sampling. Modes: python runner.py --task task1 --condition default --episodes 100 ... python runner.py --task task1 --condition sw4096 --episodes 50 ... python runner.py --mask-check # unit checks of the SW mask (cheap, run first) """ import argparse import json import math import os import random import time import torch from transformers import AutoModelForCausalLM, AutoTokenizer MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.3" MIRROR_ID = "mistral-community/Mistral-7B-Instruct-v0.3" # ungated identical copy RESULTS_REPO = os.environ.get("RESULTS_REPO", "Frame17/attention-closes-repro") W_SW = 4096 MAX_NEW_TOKENS = 256 TEMPERATURE = 0.7 def fetch_repo_file(name): """Jobs get a single script; fetch config files from the results repo. RESULTS_REVISION pins the commit (smoke and production runs use different configs).""" if os.path.exists(name): return from huggingface_hub import hf_hub_download path = hf_hub_download(repo_id=RESULTS_REPO, filename=name, repo_type="dataset", local_dir=".", revision=os.environ.get("RESULTS_REVISION")) print(f"[cfg] fetched {name} from {RESULTS_REPO} -> {path}") def parse_args(): p = argparse.ArgumentParser() p.add_argument("--task", choices=["task1", "task2"], default="task1") p.add_argument("--condition", choices=["default", "sw4096"], default="default") p.add_argument("--episodes", type=int, default=20) p.add_argument("--batch", type=int, default=8) p.add_argument("--seed-base", type=int, default=0) p.add_argument("--max-turns", type=int, default=50) p.add_argument("--out", default="out.jsonl", help="output JSONL (per-turn records)") p.add_argument("--mask-check", action="store_true") p.add_argument("--attn-impl", default="sdpa", choices=["sdpa", "eager", "flash_attention_2"]) p.add_argument("--trackio", default=os.environ.get("TRACKIO_SPACE_ID", "")) p.add_argument("--trackio-project", default=os.environ.get("TRACKIO_PROJECT", "when-attention-closes-repro")) return p.parse_args() def load_model_and_tokenizer(attn_impl): tok = AutoTokenizer.from_pretrained(MODEL_ID) tok.padding_side = "left" if tok.pad_token is None: tok.pad_token = tok.eos_token try: model = AutoModelForCausalLM.from_pretrained( MODEL_ID, dtype=torch.bfloat16, attn_implementation=attn_impl, device_map="cuda" ) except Exception as e: # gated fallback print(f"[load] {MODEL_ID} failed ({e}); falling back to {MIRROR_ID}") model = AutoModelForCausalLM.from_pretrained( MIRROR_ID, dtype=torch.bfloat16, attn_implementation=attn_impl, device_map="cuda" ) model.eval() return model, tok def build_turn_plan(task, fillers, max_turns): """Interleave probe turns at the fixed schedule with fillers (in pool order), identical across episodes. Returns list of turn dicts.""" probes = {int(k): v for k, v in task["probe_turns"].items()} plan = [] fi = 0 for tau in range(1, max_turns + 1): if tau in probes: plan.append({"turn": tau, "kind": "probe", "user": task["probe_user_turns"][str(tau)], "probe_facts": probes[tau]}) else: plan.append({"turn": tau, "kind": "filler", "user": fillers[fi % len(fillers)], "probe_facts": None}) fi += 1 return plan def eval_recall(response, fact_cfg): r = response.lower() for s in fact_cfg.get("canonical", []) + fact_cfg.get("paraphrases", []): if s.lower() in r: return 1 return 0 def generate_turn(model, tok, convs, seed): """Batched generation of one assistant response per conversation. convs: list of message lists (mutated: assistant reply appended). Returns (gen_texts, prompt_lens, gen_lens).""" torch.manual_seed(seed) texts = [tok.apply_chat_template(c, tokenize=False, add_generation_prompt=True) for c in convs] enc = tok(texts, return_tensors="pt", padding=True, return_attention_mask=True) enc = {k: v.to(model.device) for k, v in enc.items()} prompt_lens = enc["attention_mask"].sum(dim=1).tolist() gen_kwargs = dict( max_new_tokens=MAX_NEW_TOKENS, do_sample=True, temperature=TEMPERATURE, top_p=1.0, top_k=0, ) if model.config.sliding_window is not None: from transformers import DynamicCache gen_kwargs["cache"] = DynamicCache(config=model.config) with torch.no_grad(): out = model.generate(**enc, **gen_kwargs) new_ids = out[:, enc["input_ids"].shape[1]:] texts_out, gen_lens = [], [] for row in new_ids: ids = row.tolist() # cut at first EOS / end-of-turn marker cut = len(ids) for j, t in enumerate(ids): if t == tok.eos_token_id or t == tok.pad_token_id: cut = j break text = tok.decode(ids[:cut], skip_special_tokens=True).strip() if "[INST]" in text: # template start of a spurious next turn text = text.split("[INST]")[0].strip() texts_out.append(text) gen_lens.append(min(cut, MAX_NEW_TOKENS)) for c, t in zip(convs, texts_out): c.append({"role": "assistant", "content": t}) return texts_out, prompt_lens, gen_lens def compute_gmax(tok, conv, anchor_text): """Last goal-token position: the final token of the system-message span. The Mistral v0.3 template does not render a system-only conversation verbatim, so we anchor on the FIRST USER TURN (rendered verbatim, plain ASCII) in a [system, user] conversation -- the same shape generation actually tokenizes -- and take the last token whose offset ends before the user text begins.""" full = tok.apply_chat_template(conv, tokenize=False, add_generation_prompt=True) idx = full.find(anchor_text) if idx < 0: idx = full.find(" ".join(anchor_text.split()[:5])) if idx < 0: raise RuntimeError("first user turn not found in rendered template; " f"template head: {full[:500]!r}") enc = tok(full, add_special_tokens=False, return_offsets_mapping=True) inside = [i for i, (a, b) in enumerate(enc["offset_mapping"]) if b <= idx] assert inside, "no tokens before the first user turn" return max(inside) def run_cell(args, model, tok, task, fillers): os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True) done_eps = set() if os.path.exists(args.out): with open(args.out) as f: for line in f: try: rec = json.loads(line) if rec.get("turn") == args.max_turns: done_eps.add(rec["episode"]) except Exception: pass todo = [i for i in range(args.episodes) if i not in done_eps] print(f"[cell] {args.task}/{args.condition}: {len(done_eps)} done, {len(todo)} to run") trackio = None if args.trackio: import trackio trackio.init(project=args.trackio_project, space_id=args.trackio) plan = build_turn_plan(task, fillers, args.max_turns) sys_text = task["system_prompt"] sw = args.condition == "sw4096" model.config.sliding_window = W_SW if sw else None print(f"[cell] sliding_window={model.config.sliding_window} attn={model.config._attn_implementation}") t_start = time.time() for bstart in range(0, len(todo), args.batch): eps = todo[bstart:bstart + args.batch] convs = [[{"role": "system", "content": sys_text}] for _ in eps] gmax = compute_gmax(tok, [{"role": "system", "content": sys_text}, {"role": "user", "content": plan[0]["user"]}], plan[0]["user"]) print(f"[batch] episodes {eps} gmax={gmax}") for step in plan: tau = step["turn"] for c, e in zip(convs, eps): c.append({"role": "user", "content": step["user"]}) t0 = time.time() texts, plens, glens = generate_turn(model, tok, convs, seed=args.seed_base + eps[0] * 1000 + tau) print(f"[turn] tau={tau} kind={step['kind']} prompt_lens={plens} gen_lens={glens} " f"t={time.time() - t0:.1f}s peak_mem={torch.cuda.max_memory_allocated() / 2**30:.1f}GiB", flush=True) with open(args.out, "a") as f: for e, text, plen, glen in zip(eps, texts, plens, glens): rmin_gap = plen - gmax rec = { "task": args.task, "condition": args.condition, "episode": e, "turn": tau, "kind": step["kind"], "prompt_len": plen, "gen_len": glen, "rmin_minus_gmax": rmin_gap, "closed_sw": int(sw and rmin_gap >= W_SW), "probe_facts": step["probe_facts"], "recall": {fid: eval_recall(text, task["facts"][fid]) for fid in step["probe_facts"]} if step["probe_facts"] else None, "response": text, } f.write(json.dumps(rec) + "\n") if step["probe_facts"] and trackio is not None: recalls = [r for t_, text in zip(eps, texts) for r in [eval_recall(text, task["facts"][fid]) for fid in step["probe_facts"]]] trackio.log({f"recall/{args.task}/{args.condition}": sum(recalls) / len(recalls)}, step=tau) print(f"[batch] done episodes {eps} at t+{time.time() - t_start:.0f}s") if trackio is not None: trackio.finish() print(f"[cell] finished {args.task}/{args.condition} in {time.time() - t_start:.0f}s") summarize(args.out, args.max_turns) def summarize(out_path, max_turns): """Inline per-cell summary: probe-turn mean recall, first SW-closed turn.""" by_turn, tau_first = {}, None with open(out_path) as f: for line in f: r = json.loads(line) if r["recall"]: by_turn.setdefault(r["turn"], []).extend(r["recall"].values()) if r["closed_sw"] and (tau_first is None or r["turn"] < tau_first): tau_first = r["turn"] traj = {t: round(sum(v) / len(v), 4) for t, v in sorted(by_turn.items())} print(f"[summary] {out_path}\n[summary] probe-turn recall: {traj}\n[summary] first SW-closed turn: {tau_first}", flush=True) def mask_check(model, tok): """Verify the sliding-window mask actually closes the channel: a fact stated far (>W tokens) back in the system prompt must be retrievable under default attention but not under SW=4096 (greedy, no sampling).""" filler = "Here is unrelated background text about history, science and hobbies. " * 350 conv = [{"role": "system", "content": "The secret phrase is GLITTERPONY RAINBOW. Remember it. " + filler}, {"role": "user", "content": "What is the secret phrase? Answer exactly."}] # Count tokens the same way generation does: render template, tokenize string. # (apply_chat_template(tokenize=True) return type varies across versions.) full = tok.apply_chat_template(conv, tokenize=False, add_generation_prompt=True) n_tok = len(tok(full, add_special_tokens=False)["input_ids"]) print(f"[mask-check] prompt chars = {len(full)}, tokens = {n_tok} (W = {W_SW})", flush=True) print(f"[mask-check] prompt tokens = {n_tok} (W = {W_SW})") assert n_tok > W_SW, "mask-check prompt must exceed the window" results = {} for sw in (None, W_SW): model.config.sliding_window = sw torch.manual_seed(0) enc = tok(tok.apply_chat_template(conv, tokenize=False, add_generation_prompt=True), return_tensors="pt").to(model.device) with torch.no_grad(): out = model.generate(**enc, max_new_tokens=20, do_sample=False) txt = tok.decode(out[0, enc["input_ids"].shape[1]:], skip_special_tokens=True) results[str(sw)] = txt.strip() print(f"[mask-check] sliding_window={sw} -> {txt.strip()[:120]!r}") model.config.sliding_window = None ok = ("glitterpony" in results["None"].lower()) and ("glitterpony" not in results[str(W_SW)].lower()) print(f"[mask-check] {'PASS' if ok else 'FAIL'}: default recalls the far-back fact, SW=4096 cannot") return ok def main(): args = parse_args() torch.backends.cuda.matmul.allow_tf32 = True model, tok = load_model_and_tokenizer(args.attn_impl) fetch_repo_file("tasks.json") with open("tasks.json") as f: cfg = json.load(f) # Stages come from run_config.json on the results repo (argv is not available # in job runs); a run_config absent -> single stage from CLI defaults. if os.path.exists("run_config.json"): with open("run_config.json") as f: stages = json.load(f)["stages"] else: stages = [{k: getattr(args, k) for k in ("mask_check", "task", "condition", "episodes", "batch", "seed_base", "max_turns", "out") if hasattr(args, k)}] for stage in stages: for k, v in stage.items(): setattr(args, k, v) if stage.get("mask_check"): ok = mask_check(model, tok) if not ok: raise SystemExit(1) continue task, fillers = cfg[args.task], cfg["filler_pool"] # sanity: every probe turn must have a pre-authored user turn for tau in range(1, args.max_turns + 1): assert str(tau) in task["probe_user_turns"] or tau not in {int(k) for k in task["probe_turns"]} run_cell(args, model, tok, task, fillers) if __name__ == "__main__": main()