Spaces:
Runtime error
Runtime error
File size: 14,615 Bytes
7a6a612 0fc8c59 7a6a612 0fc8c59 7a6a612 0fc8c59 7a6a612 31bfa9d 7a6a612 a5ff4af 7a6a612 | 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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | """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()
|