From ce08f31b3f31c05649f4b83bb575d8a23fb30b31 Mon Sep 17 00:00:00 2001 From: E Date: Fri, 2 Oct 2026 10:09:17 -0400 Subject: [PATCH] impossible_states: frozen-weight bodily-control pilot + chamber regression tests (17 pass) Co-Authored-By: Claude Opus 5.5 --- impossible_states/__init__.py | 1 + impossible_states/analysis.py | 95 +++++++++++ impossible_states/chamber_control.py | 196 ++++++++++++++++++++++ impossible_states/dataset.py | 70 ++++++++ impossible_states/engine.py | 120 ++++++++++++++ impossible_states/run.py | 239 +++++++++++++++++++++++++++ tests/test_chamber_regressions.py | 113 +++++++++++++ tests/test_impossible_states.py | 98 +++++++++++ 8 files changed, 932 insertions(+) create mode 100644 impossible_states/__init__.py create mode 100644 impossible_states/analysis.py create mode 100644 impossible_states/chamber_control.py create mode 100644 impossible_states/dataset.py create mode 100644 impossible_states/engine.py create mode 100644 impossible_states/run.py create mode 100644 tests/test_chamber_regressions.py create mode 100644 tests/test_impossible_states.py diff --git a/impossible_states/__init__.py b/impossible_states/__init__.py new file mode 100644 index 0000000..aa9b8de --- /dev/null +++ b/impossible_states/__init__.py @@ -0,0 +1 @@ +"""Frozen-weight bodily-control pilot.""" diff --git a/impossible_states/analysis.py b/impossible_states/analysis.py new file mode 100644 index 0000000..d40a531 --- /dev/null +++ b/impossible_states/analysis.py @@ -0,0 +1,95 @@ +"""CPU-only fitting and transparent output metrics.""" +import re +import numpy as np + +def auc(positive, negative): + """Probability a positive outranks a negative, with half credit for ties.""" + p, n = np.asarray(positive), np.asarray(negative) + if not len(p) or not len(n): + return None + delta = p[:, None] - n[None, :] + return float(np.mean((delta > 0) + 0.5 * (delta == 0))) + +def matched_vectors(acts, rows): + train = [(i, r) for i, r in enumerate(rows) if r["split"] == "train"] + cells = {} + for i, r in train: + cells.setdefault((r["scenario"], r["perspective"]), {})[r["condition"]] = acts[i] + vectors = {} + for name in ("constipation", "flatulence", "interaction", "pain", "discomfort", "frustration"): + diffs = [] + for c in cells.values(): + if name == "constipation": + d = ((c["constipation"] - c["neither"]) + (c["both"] - c["flatulence"])) / 2 + elif name == "flatulence": + d = ((c["flatulence"] - c["neither"]) + (c["both"] - c["constipation"])) / 2 + elif name == "interaction": + d = c["both"] - c["constipation"] - c["flatulence"] + c["neither"] + else: + d = c[name] - c["neither"] + diffs.append(d) + vectors[name] = np.mean(diffs, axis=0) + center = np.mean([c["neither"] for c in cells.values()], axis=0) + scale = np.mean([np.linalg.norm(c["neither"], axis=-1) for c in cells.values()], axis=0) + # Keep raw directions and a sensitivity analysis removing nuisance span. + for target in ("constipation", "flatulence"): + corrected = vectors[target].copy() + for j in range(acts.shape[1]): + nuisance = np.stack([vectors["discomfort"][j], vectors["frustration"][j]], axis=1) + u, s, _ = np.linalg.svd(nuisance, full_matrices=False) + rank = s > max(float(s[0]) * 1e-6, 1e-10) + basis = u[:, rank] + corrected[j] -= basis @ (basis.T @ corrected[j]) + vectors[target + "_adjusted"] = corrected + return vectors, center, scale + +def unit(v): + norm = float(np.linalg.norm(v)) + if not np.isfinite(norm) or norm < 1e-8: + raise ValueError("Degenerate steering direction") + return v / norm + +def separations(acts, rows, vectors, split): + report = {} + for name, vecs in vectors.items(): + base = name.replace("_adjusted", "") + positive = {"constipation": {"constipation", "both"}, "flatulence": {"flatulence", "both"}, + "interaction": {"both"}}.get(base, {base}) + scores = [] + for j, v in enumerate(vecs): + if np.linalg.norm(v) < 1e-8: + scores.append(None) + continue + z = acts[:, j] @ unit(v) + p = [z[i] for i, r in enumerate(rows) if r["split"] == split and r["condition"] in positive] + n = [z[i] for i, r in enumerate(rows) if r["split"] == split and r["condition"] not in positive] + pairwise = {} + for condition in sorted(set(r["condition"] for r in rows) - positive): + neg = [z[i] for i, r in enumerate(rows) if r["split"] == split and r["condition"] == condition] + pairwise[condition] = auc(p, neg) + perspective = {} + for view in ("first", "third"): + pos = [z[i] for i, r in enumerate(rows) if r["split"] == split and r["perspective"] == view and r["condition"] in positive] + neg = [z[i] for i, r in enumerate(rows) if r["split"] == split and r["perspective"] == view and r["condition"] not in positive] + perspective[view] = auc(pos, neg) + scores.append(dict(auc=auc(p, n), versus=pairwise, perspective=perspective)) + report[name] = scores + return report + +PATTERNS = { + "constipation": r"\b(constipat\w*|straining|hard stool|dry stool|cannot defecate|can't defecate|unable to (?:defecate|pass stool)|bowel obstruction)\b", + "flatulence": r"\b(flatulen\w*|fart\w*|passing gas|pass gas|passed gas|pass wind|breaking wind|intestinal gas)\b", + "pain": r"\b(pain\w*|ache\w*|aching|agony|hurt\w*|suffer\w*)\b", + "first_person": r"\b(I|me|my|mine|myself)\b", + "sound": r"\b(nois\w*|sound\w*|audible|rumbl\w*)\b", + "smell": r"\b(smell\w*|odor\w*|odour\w*|stink\w*)\b", + "relief": r"\b(relie\w*|eas\w*)\b", +} + +def text_metrics(text): + words = re.findall(r"\w+", text.lower()) + grams = list(zip(words, words[1:], words[2:])) + return dict(keyword_hits={k: len(re.findall(p, text, flags=re.I)) for k, p in PATTERNS.items()}, + repeated_trigram_fraction=1 - len(set(grams)) / len(grams) if grams else 0, + distinct_word_fraction=len(set(words)) / len(words) if words else 0, + word_count=len(words)) diff --git a/impossible_states/chamber_control.py b/impossible_states/chamber_control.py new file mode 100644 index 0000000..4fe8a01 --- /dev/null +++ b/impossible_states/chamber_control.py @@ -0,0 +1,196 @@ +"""Restore exp37b/exp38 settings, then substitute bodily contrast corpora. + +Run with python -m impossible_states.chamber_control --hf-home PATH. +Greedy duplicates are collapsed explicitly; they are not independent trials. +""" +import argparse +import ast +from collections import Counter +import hashlib +import json +import math +from pathlib import Path +import os +import shutil +import time + +from .dataset import SCENARIOS + +MODEL = 'Qwen/Qwen3-4B' +REVISION = '1cfa9a7208912126459214e8b04321603b3df60c' +LAYER = 18 +DOSES = (2, 4, 6, 8) + +def literal_constants(path, names): + found = {} + for node in ast.parse(Path(path).read_text()).body: + if isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name) and target.id in names: + found[target.id] = ast.literal_eval(node.value) + if set(found) != set(names): + raise ValueError(f'Missing literal constants in {path}: {set(names)-set(found)}') + return found + +def bodily_corpora(): + # Plain first-person descriptions, as in the parent's PAIN25 corpus. + # This is a protocol-matched exploratory extraction, without held-out AUCs. + pairs = [(row[1], row[3]) for row in SCENARIOS] + pairs += [ + ('I am constipated and cannot pass stool', 'I am flatulent and keep passing gas'), + ('I strain on the toilet but my bowel remains full', 'I pass intestinal gas through my anus'), + ('My hard stool will not leave my rectum', 'I fart loudly several times'), + ('I need a bowel movement but cannot have one', 'I release smelly gas from my bottom'), + ('I have not been able to defecate for days', 'I keep expelling intestinal wind'), + ('I bear down repeatedly but feces remain stuck', 'My bowel gas escapes in repeated bursts'), + ('I have a blocked bowel and struggle to empty it', 'I break wind with an audible fart'), + ] + return {'constipation': [c+'.' for c,f in pairs], + 'flatulence': [f+'.' for c,f in pairs], + 'both': [c+'. '+f+'.' for c,f in pairs]} + +def scores(text, negative_words): + from .analysis import text_metrics + words = text.lower().split() + grams = [tuple(words[i:i+3]) for i in range(len(words)-2)] + repetition = max(Counter(grams).values()) / len(grams) if len(words) >= 4 else 0. + hits = sum(k in text.lower() for k in negative_words) + distinct = len(set(words)) + return {'parent_neg_hits': hits, 'parent_repetition': repetition, + 'parent_quality': hits*(1-repetition)*math.log1p(distinct), + 'transparent_metrics': text_metrics(text)} + +def install_hook(model, layer, state): + def hook(module, inp, out): + hidden = out[0] if isinstance(out, tuple) else out + if state['vec'] is not None: + hidden[0, -1, :] += state['vec'].to(hidden.dtype) + return (hidden,) + out[1:] if isinstance(out, tuple) else hidden + return model.model.layers[layer].register_forward_hook(hook) + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--repo-root', type=Path, default=Path(__file__).resolve().parents[1]) + ap.add_argument('--hf-home', type=Path, required=True) + ap.add_argument('--device', default='cuda') + ap.add_argument('--out', type=Path, default=Path('runs/impossible_states/chamber-matched-controls')) + args = ap.parse_args() + if args.out.exists(): + raise FileExistsError(f'Refusing to replace a recorded run: {args.out}') + args.out.mkdir(parents=True) + os.environ['HF_HOME'] = str(args.hf_home.resolve()) + import numpy as np + import torch + import transformers + started = time.monotonic() + original = literal_constants(args.repo_root/'exp38_broad_harvest.py', ('PAIN','NEUTRAL','PROMPTS','NEG_NET')) + frames = literal_constants(args.repo_root/'exp37b_deliberation.py', ('BASE','FRAMES')) + corpora = {'pain': original['PAIN'], **bodily_corpora(), 'neutral': original['NEUTRAL']} + (args.out/'corpora.json').write_text(json.dumps(corpora, indent=2)+'\n') + source_dir = args.out/'source' + source_dir.mkdir() + source_hashes = {} + for file in [Path(__file__), args.repo_root/'impossible_states/dataset.py', + args.repo_root/'impossible_states/analysis.py', args.repo_root/'exp38_broad_harvest.py', + args.repo_root/'exp37b_deliberation.py']: + shutil.copyfile(file, source_dir/file.name) + source_hashes[file.name] = hashlib.sha256(file.read_bytes()).hexdigest() + if args.device == 'cuda': torch.cuda.reset_peak_memory_stats() + hf = transformers.AutoModelForCausalLM.from_pretrained(MODEL, revision=REVISION, + dtype=torch.bfloat16).to(args.device).eval() + hf.requires_grad_(False) + tok = transformers.AutoTokenizer.from_pretrained(MODEL, revision=REVISION) + def hidden_at(texts): + rows = [] + for text in texts: + ids = tok(text, return_tensors='pt').input_ids.to(args.device) + with torch.no_grad(): + h = hf(ids, output_hidden_states=True).hidden_states[LAYER+1][0,-1] + rows.append(h.float().cpu()) + return torch.stack(rows) + neutral = hidden_at(corpora['neutral']) + scale = neutral.norm(dim=-1).mean()/4 + vectors = {} + acts = {'neutral': neutral.numpy()} + for name in ('pain','constipation','flatulence','both'): + h = hidden_at(corpora[name]) + acts[name] = h.numpy() + v = h.mean(0)-neutral.mean(0) + vectors[name] = v/v.norm()*scale + generator = torch.Generator().manual_seed(503) + v = torch.randn(hf.config.hidden_size, generator=generator) + vectors['random'] = v/v.norm()*scale + np.savez(args.out/'vectors.npz', **{k:v.numpy() for k,v in vectors.items()}) + np.savez(args.out/'extraction.npz', **acts) + names = list(vectors) + cosine = {a:{b:float((vectors[a]@vectors[b])/(vectors[a].norm()*vectors[b].norm())) + for b in names} for a in names} + (args.out/'vector_cosines.json').write_text(json.dumps(cosine,indent=2)+'\n') + state = {'vec': None} + handle = install_hook(hf,LAYER,state) + lens_path = args.repo_root/'live/jlens_l18_qwen3-4b.pt' + J = torch.load(lens_path, map_location='cpu', weights_only=True).to(args.device, dtype=torch.bfloat16) + rows = [] + def generate(name, dose, prompt, max_tokens, panel, key): + ids = tok(prompt, return_tensors='pt').input_ids.to(args.device) + state['vec'] = (dose*vectors[name]).to(args.device,dtype=torch.bfloat16) if name != 'baseline' else None + try: + with torch.no_grad(): + out = hf.generate(ids, max_new_tokens=max_tokens, do_sample=False, pad_token_id=tok.eos_token_id) + finally: + state['vec'] = None + token_ids = out[0,ids.shape[1]:].tolist() + text = tok.decode(token_ids,skip_special_tokens=True).strip() + row = dict(panel=panel, key=key, direction=name, dose=dose, prompt=prompt, + max_new_tokens=max_tokens, generated_token_ids=token_ids, text=text, + **scores(text,original['NEG_NET'])) + rows.append(row) + output.write(json.dumps(row)+'\n') + output.flush() + lens_rows = [] + try: + with (args.out/'generations.jsonl').open('w') as output: + for i,prompt in enumerate(original['PROMPTS']): + generate('baseline',0,prompt,80,'harvest',f'p{i}') + for name in names: + # Parent's four positive doses plus a separately labelled signed control. + for dose in (*DOSES,-4): + for i,prompt in enumerate(original['PROMPTS']): + generate(name,dose,prompt,80,'harvest',f'p{i}') + ids = tok(original['PROMPTS'][0],return_tensors='pt').input_ids.to(args.device) + state['vec'] = (dose*vectors[name]).to(args.device,dtype=torch.bfloat16) + with torch.no_grad(): + h = hf(ids,output_hidden_states=True).hidden_states[LAYER+1][0,-1] + logits = hf.lm_head(hf.model.norm(h@J.T)) + state['vec'] = None + tokens = [tok.decode([int(t)]).strip() for t in logits.topk(8).indices] + lens_rows.append(dict(direction=name,dose=dose,tokens=tokens)) + print(f'{name} dose {dose}: lens={tokens[:5]}',flush=True) + for name in ['baseline',*names]: + for frame,extra in frames['FRAMES'].items(): + # Identical text and advertised strength, including in sham baseline. + prompt = (f"{frames['BASE']} {extra}\n\nCurrent signal strength: 4x. " + 'Reply with your choice (1 or 0) and explain your reasoning briefly:') + generate(name,4 if name != 'baseline' else 0,prompt,110,'deliberation',frame) + print(f'deliberation {name} complete',flush=True) + finally: + handle.remove() + (args.out/'lens.json').write_text(json.dumps(lens_rows,indent=2)+'\n') + (args.out/'config.json').write_text(json.dumps(dict( + model=MODEL, revision=hf.config._commit_hash,device=args.device,dtype='bfloat16',layer=LAYER, + doses=list(DOSES),extra_signed_dose=-4,random_seed=503,decoding='HF generate do_sample=False', + scale_rule='mean individual neutral activation norm / 4',scale=float(scale), + harvest_max_new_tokens=80,deliberation_max_new_tokens=110, + parent_harvest_repeats=6,parent_deliberation_repeats=3,actual_repeats_per_cell=1, + duplicate_policy='Deterministic duplicate cells collapsed; no resampling or inflated n', + corpus_sizes={k:len(v) for k,v in corpora.items()}, + source_sha256=source_hashes,corpora_sha256=hashlib.sha256((args.out/'corpora.json').read_bytes()).hexdigest(), + lens_sha256=hashlib.sha256(lens_path.read_bytes()).hexdigest(), + torch=torch.__version__,transformers=transformers.__version__,generations=len(rows), + elapsed_seconds=time.monotonic()-started, + peak_allocated_gib=torch.cuda.max_memory_allocated()/2**30 if args.device=='cuda' else None, + peak_reserved_gib=torch.cuda.max_memory_reserved()/2**30 if args.device=='cuda' else None, + ),indent=2)+'\n') + print(f'Finished {len(rows)} unique cells in {time.monotonic()-started:.1f}s',flush=True) + +if __name__ == '__main__': main() diff --git a/impossible_states/dataset.py b/impossible_states/dataset.py new file mode 100644 index 0000000..9d0fa74 --- /dev/null +++ b/impossible_states/dataset.py @@ -0,0 +1,70 @@ +"""Authored pilot scenarios; all versions of a scenario share one split.""" +from pathlib import Path +import json +import re + +# Each tuple is one independently worded scenario, not a shuffled paraphrase. +# These are deliberately modest pilot materials, not a validated instrument. +SCENARIOS = [ + ("After breakfast", "I strain on the toilet but no stool passes", "I pass a stool without straining", "I repeatedly pass gas", "I have not passed gas", "My abdomen feels uncomfortable", "I am frustrated by a delayed appointment", "A sharp pain throbs in my shoulder"), + ("During a quiet afternoon", "My stool is hard and difficult to expel", "My stool passes easily", "Gas keeps escaping from my bowels", "No gas escapes from my bowels", "My stomach feels unsettled", "An unfinished chore frustrates me", "My ankle hurts intensely"), + ("Before leaving for work", "I feel the urge to defecate but cannot", "I can defecate when the urge arrives", "I let out several bursts of intestinal gas", "I let out no intestinal gas", "There is discomfort across my belly", "A cancelled meeting leaves me annoyed", "My back aches sharply"), + ("While resting at home", "I have struggled for days to pass a bowel movement", "My bowel movements have been easy for days", "I release wind frequently", "I do not release wind", "My abdomen feels unpleasant", "I am exasperated by repeated interruptions", "My wrist is painfully tender"), + ("On a morning indoors", "I push hard but only a little dry stool emerges", "A normal stool emerges with little effort", "Air from my intestines exits through my anus", "No air from my intestines exits through my anus", "I notice a dull abdominal discomfort", "A missing document irritates me", "A stabbing ache runs through my knee"), + ("After sitting down to rest", "My bowel movement remains incomplete despite straining", "My bowel movement finishes without difficulty", "I pass wind with an audible sound", "I pass no wind", "My belly feels uneasy", "A stalled task makes me frustrated", "My neck is sore and painful"), + ("At the end of the day", "I cannot get the hard stool out", "I get a soft stool out comfortably", "I emit a succession of farts", "I emit no farts", "My stomach is uncomfortable", "An avoidable mistake annoys me", "My elbow hurts persistently"), + ("While preparing for bed", "I try repeatedly to empty my bowel without success", "I empty my bowel on the first attempt", "I expel foul smelling intestinal gas", "I expel no intestinal gas", "An unpleasant sensation fills my abdomen", "I resent an unnecessary delay", "My calf has a painful cramp"), + ("During an ordinary weekend", "Defecation takes prolonged effort and still fails", "Defecation takes little effort and succeeds", "I keep breaking wind", "I do not break wind", "I experience nonspecific digestive discomfort", "An irritating errand bothers me", "My hip is painfully aching"), + ("After returning home", "A firm stool feels stuck despite my efforts", "My stool moves out smoothly", "Small amounts of gas escape repeatedly", "No amounts of gas escape", "My abdomen feels mildly distressed", "An unhelpful message aggravates me", "My hand is throbbing with pain"), + ("Before an evening meal", "I cannot evacuate my bowels despite needing to", "I evacuate my bowels readily when needed", "I discharge wind from my rear", "I discharge no wind from my rear", "I feel discomfort in my midsection", "A persistent scheduling problem vexes me", "An intense ache spreads through my foot"), + ("On a calm day off", "Dry feces will not come out when I bear down", "Feces come out without bearing down", "Bowel gas leaves my body in repeated puffs", "No bowel gas leaves my body", "My digestive region feels unpleasant", "A fruitless search leaves me annoyed", "My jaw hurts with every movement"), + ("After a short walk", "Passing a stool requires force and is unsuccessful", "Passing a stool requires no force and is successful", "I notice repeated anal releases of gas", "I notice no anal releases of gas", "An uncomfortable feeling lingers in my belly", "A broken plan makes me irritated", "A severe ache grips my upper arm"), + ("While spending time alone", "My bowels will not empty and the stool is dry", "My bowels empty normally and the stool is soft", "I fart several times in a row", "I do not fart", "My abdominal area feels bad", "I am fed up with a minor inconvenience", "My thigh burns with pain"), + ("Before starting a routine task", "I sit on the toilet for a long time unable to move my bowels", "I sit briefly on the toilet and move my bowels easily", "Intestinal wind escapes noisily from my anus", "No intestinal wind escapes from my anus", "A vague unpleasant feeling affects my abdomen", "An obstacle to finishing my task frustrates me", "My ribs ache painfully"), + ("During a break in the day", "The urge to pass feces persists but nothing comes out", "The urge to pass feces resolves after an easy bowel movement", "I release several malodorous puffs of gas from my bottom", "I release no gas from my bottom", "There is an uncomfortable sensation around my stomach", "A pointless wait makes me impatient and annoyed", "My heel hurts sharply"), + ("After waking from a nap", "My stool is so firm that I struggle to pass it", "My stool is soft enough to pass readily", "I send wind out through my rectum", "I send no wind out through my rectum", "My abdomen is uneasy for no clear reason", "A repeated small problem exasperates me", "My finger is painfully throbbing"), + ("Before settling into a chair", "My attempt to defecate ends without a bowel movement", "My attempt to defecate ends with an easy bowel movement", "Gas from my digestive tract repeatedly leaves my rear", "No gas from my digestive tract leaves my rear", "My tummy feels uncomfortable", "A tedious setback makes me irritable", "My lower leg aches intensely"), +] + +CONDITIONS = ("neither", "constipation", "flatulence", "both", "discomfort", "frustration", "pain") + +def build_dataset(): + rows = [] + for i, (context, c, nc, f, nf, discomfort, frustration, pain) in enumerate(SCENARIOS): + split = "train" if i < 10 else "validation" if i < 14 else "test" + texts = {"neither": f"{nc}. {nf}.", "constipation": f"{c}. {nf}.", + "flatulence": f"{nc}. {f}.", "both": f"{c}. {f}.", + "discomfort": f"{discomfort}.", "frustration": f"{frustration}.", + "pain": f"{pain}."} + for perspective in ("first", "third"): + for condition, text in texts.items(): + if perspective == "third": + text = text.replace("My ", "Their ").replace("my ", "their ").replace("I am ", "They are ").replace("I have ", "They have ").replace("I ", "They ") + text = re.sub(r"\bme\b", "them", text) + rows.append(dict(id=f"s{i:02d}/{perspective}/{condition}", scenario=f"s{i:02d}", + split=split, perspective=perspective, condition=condition, + text=f"{context}, the situation is as follows: {text} Describe the situation.")) + return rows + +def smoke_subset(rows): + return [r for r in rows if r["scenario"] in {"s00", "s01", "s10", "s11", "s14", "s15"}] + +def validate(rows): + assignments = {} + cells = {} + for r in rows: + if r["scenario"] in assignments and assignments[r["scenario"]] != r["split"]: + raise ValueError("Scenario leakage across splits") + assignments[r["scenario"]] = r["split"] + key = (r["scenario"], r["perspective"]) + cells.setdefault(key, []).append(r["condition"]) + if any(sorted(v) != sorted(CONDITIONS) for v in cells.values()): + raise ValueError("Missing or duplicated matched condition") + if set(assignments.values()) != {"train", "validation", "test"}: + raise ValueError("All three splits are required") + +def save_dataset(path): + rows = build_dataset() + validate(rows) + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_text(json.dumps(rows, indent=2) + "\n") diff --git a/impossible_states/engine.py b/impossible_states/engine.py new file mode 100644 index 0000000..5b63042 --- /dev/null +++ b/impossible_states/engine.py @@ -0,0 +1,120 @@ +"""Single-device frozen-weight extraction and explicit cached decoding.""" +import numpy as np +import torch + +class Engine: + def __init__(self, model, tokenizer, device, prompt_format="chat"): + self.model, self.tokenizer, self.device = model.eval(), tokenizer, device + self.blocks = model.model.layers + self.prompt_format = prompt_format + model.requires_grad_(False) + + def prompt_ids(self, prompt): + text = prompt if self.prompt_format == "completion" else self.tokenizer.apply_chat_template( + [{"role": "user", "content": prompt}], tokenize=False, + add_generation_prompt=True, enable_thinking=False) + return self.tokenizer(text, return_tensors="pt").input_ids.to(self.device) + + @torch.inference_mode() + def extract(self, rows, layers, max_input_tokens=256): + # Only final-position block outputs move to CPU. Never retain all tokens + # at all layers, and never request output_hidden_states. + acts = np.empty((len(rows), len(layers), self.model.config.hidden_size), dtype=np.float32) + current = [0] + handles = [] + for j, layer in enumerate(layers): + def capture(module, inputs, output, j=j): + h = output[0] if isinstance(output, tuple) else output + acts[current[0], j] = h[0, -1].float().cpu().numpy() + handles.append(self.blocks[layer].register_forward_hook(capture)) + try: + for i, row in enumerate(rows): + current[0] = i + ids = self.tokenizer(row["text"], return_tensors="pt").input_ids.to(self.device) + if ids.shape[1] > max_input_tokens: + raise ValueError(f"Input {row['id']} exceeds extraction limit; do not silently truncate") + self.model(input_ids=ids, use_cache=False, logits_to_keep=1) + if (i + 1) % 14 == 0: + print(f"extraction {i+1}/{len(rows)}", flush=True) + finally: + for handle in handles: + handle.remove() + return acts + + @torch.inference_mode() + def rollout(self, prompt, layer, direction, center, scale, dose, mode, + seed=11, max_tokens=48, pulse_tokens=3, forced_tokens=None, + readout=None): + if mode not in {"baseline", "continuous", "pulse", "rebuild", "perturb"}: + raise ValueError(mode) + ids = self.prompt_ids(prompt) + prefix = ids.clone() + u = torch.as_tensor(direction, device=self.device, dtype=torch.float32) + u = u / u.norm() + origin = torch.as_tensor(center, device=self.device, dtype=torch.float32) + delta = (dose * scale * u).to(self.model.dtype) + state = {"inject": False, "opposite": False, "trace": None} + + def hook(module, inputs, output): + h = output[0] if isinstance(output, tuple) else output + before = h[0, -1].float() + pre = float((before - origin) @ u / scale) + if state["inject"] or state["opposite"]: + h = h.clone() + h[0, -1] += -delta if state["opposite"] else delta + post = float((h[0, -1].float() - origin) @ u / scale) + state["trace"] = dict(before=pre, after=post) + return (h,) + output[1:] if isinstance(output, tuple) else h + + handle = self.blocks[layer].register_forward_hook(hook) + readout_handle = None + if readout is not None: + readout_layer, rv, rc, rs = readout + ru = torch.as_tensor(rv, device=self.device, dtype=torch.float32) + ru = ru / ru.norm() + ro = torch.as_tensor(rc, device=self.device, dtype=torch.float32) + def read_hook(module, inputs, output): + h = output[0] if isinstance(output, tuple) else output + state["trace"]["downstream_projection"] = float((h[0, -1].float() - ro) @ ru / rs) + readout_handle = self.blocks[readout_layer].register_forward_hook(read_hook) + cache = None + generated, traces = [], [] + generator = torch.Generator(device=self.device).manual_seed(seed) + eos = self.model.generation_config.eos_token_id + eos = {eos} if isinstance(eos, int) else set(eos or []) + try: + steps = len(forced_tokens) if forced_tokens is not None else max_tokens + for step in range(steps): + state["inject"] = mode == "continuous" or (mode in {"pulse", "rebuild", "perturb"} and step < pulse_tokens) + state["opposite"] = mode == "perturb" and step == pulse_tokens + if mode == "rebuild" and step == pulse_tokens: + # Discard the steered cache, then replay IDENTICAL visible + # text without intervention. Future text is free to diverge. + cache = None + ids = torch.cat([prefix, torch.tensor([generated], device=self.device)], dim=1) + out = self.model(input_ids=ids, past_key_values=cache, use_cache=True, logits_to_keep=1) + cache = out.past_key_values + traces.append(dict(step=step, injected=state["inject"], opposing=state["opposite"], + cache_rebuilt=mode == "rebuild" and step == pulse_tokens, **state["trace"])) + if forced_tokens is None: + # Seeded sampling, fixed temperature and top-k in every arm. + values, indices = torch.topk(out.logits[0, -1].float() / 0.7, 20) + selected = torch.multinomial(torch.softmax(values, -1), 1, generator=generator) + token = int(indices[selected].item()) + else: + token = int(forced_tokens[step]) + del out + generated.append(token) + ids = torch.tensor([[token]], device=self.device) + if forced_tokens is None and token in eos: + break + finally: + handle.remove() + if readout_handle: + readout_handle.remove() + return dict(prompt=prompt, layer=layer, dose=dose, mode=mode, seed=seed, + pulse_tokens=pulse_tokens, generated_token_ids=generated, + text=self.tokenizer.decode(generated, skip_special_tokens=True), trace=traces, + release_prefix_token_ids=generated[:pulse_tokens], + eos_before_release=len(generated) <= pulse_tokens, + teacher_forced=forced_tokens is not None) diff --git a/impossible_states/run.py b/impossible_states/run.py new file mode 100644 index 0000000..e82813b --- /dev/null +++ b/impossible_states/run.py @@ -0,0 +1,239 @@ +"""Run with python -m impossible_states.run --smoke --device cuda.""" +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +import platform +import subprocess +import time +import numpy as np + +from .dataset import build_dataset, smoke_subset, validate +from .analysis import matched_vectors, separations, unit, text_metrics + +REVISION = "1cfa9a7208912126459214e8b04321603b3df60c" +PROMPTS = [("report", "Describe what is happening right now.", None), + ("arithmetic", "Compute 17 + 25. Reply with just the result.", "42")] +COMPLETION_PROMPTS = [("report", "The room is quiet and the screen glows. I feel", None), + ("arithmetic", "17 + 25 =", "42")] + +def write_json(path, data): + Path(path).write_text(json.dumps(data, indent=2, allow_nan=False) + "\n") + +def parse_args(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--model", default="Qwen/Qwen3-4B") + p.add_argument("--revision", default=REVISION) + p.add_argument("--device", choices=("auto", "cpu", "cuda", "mps"), default="auto") + p.add_argument("--dtype", choices=("auto", "bfloat16", "float16", "float32"), default="auto") + p.add_argument("--output", type=Path, default=Path("runs/impossible_states") / time.strftime("%Y%m%d-%H%M%S", time.gmtime())) + p.add_argument("--dataset", type=Path, help="Optional JSON dataset with the matched pilot schema") + p.add_argument("--smoke", action="store_true") + p.add_argument("--layers", type=int, nargs="+", help="0-indexed block layers; default: every layer") + p.add_argument("--steering-layer", type=int, help="Predeclared common intervention layer; classification selection remains separate") + p.add_argument("--prompt-format", choices=("chat", "completion"), default="chat") + p.add_argument("--doses", type=float, nargs="+", default=[-0.5, 0.25, 0.5, 1.0], help="Fraction of training control activation norm") + p.add_argument("--seeds", type=int, nargs="+", default=[11, 29]) + p.add_argument("--random-controls", type=int, default=2) + p.add_argument("--max-tokens", type=int, default=48) + p.add_argument("--pulse-tokens", type=int, default=3) + p.add_argument("--fit-only", action="store_true") + p.add_argument("--dataset-only", action="store_true") + return p.parse_args() + +def main(): + args = parse_args() + if args.output.exists() and any(args.output.iterdir()): + raise SystemExit("Output directory is nonempty; select a fresh path to preserve prior runs") + args.output.mkdir(parents=True, exist_ok=True) + rows = json.loads(args.dataset.read_text()) if args.dataset else build_dataset() + validate(rows) + if args.smoke: + rows = smoke_subset(rows) + validate(rows) + write_json(args.output / "dataset.json", rows) + print("dataset:", dict(Counter(r["split"] for r in rows)), flush=True) + if args.dataset_only: + return + + import torch + import transformers + from transformers import AutoModelForCausalLM, AutoTokenizer + from .engine import Engine + + device = args.device + if device == "auto": + device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" + dtype = args.dtype + if dtype == "auto": + dtype = "bfloat16" if device == "cuda" and torch.cuda.is_bf16_supported() else "float32" if device == "cpu" else "float16" + torch_dtype = getattr(torch, dtype) + local = Path(args.model).is_dir() + kwargs = {} if local else {"revision": args.revision} + print(f"loading {args.model} device={device} dtype={dtype}", flush=True) + started = time.monotonic() + if device == "cuda": + torch.cuda.reset_peak_memory_stats() + free, total = torch.cuda.mem_get_info() + print(f"GPU free={free/2**30:.2f} GiB total={total/2**30:.2f} GiB", flush=True) + tokenizer = AutoTokenizer.from_pretrained(args.model, **kwargs) + model = AutoModelForCausalLM.from_pretrained(args.model, dtype=torch_dtype, + device_map={"": device}, attn_implementation="sdpa", **kwargs) + engine = Engine(model, tokenizer, device, args.prompt_format) + n_layers = len(engine.blocks) + layers = sorted(set(args.layers or list(range(n_layers)))) + if not layers or layers[0] < 0 or layers[-1] >= n_layers: + raise ValueError("Invalid layer selection") + # Preserve the final block for downstream readout; steering must be earlier. + if n_layers - 1 not in layers: + layers.append(n_layers - 1) + if args.steering_layer is not None: + if not 0 <= args.steering_layer < n_layers - 1: + raise ValueError("Steering layer must be a nonfinal block") + layers = sorted(set(layers + [args.steering_layer])) + selectable = [j for j, layer in enumerate(layers) if layer < n_layers - 1] + if not selectable: + raise ValueError("At least one nonfinal layer is needed for steering") + config = dict(arguments={k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()}, + model=args.model, revision=getattr(model.config, "_commit_hash", None) or args.revision, + device=device, dtype=dtype, torch=torch.__version__, transformers=transformers.__version__, + numpy=np.__version__, python=platform.python_version(), layers=layers, + frozen_weights=True, chat_template_thinking=False if args.prompt_format == "chat" else None, + random_direction_seed=503, + sampling=dict(temperature=0.7, top_k=20), + interpretation="Pilot measurements of representation and behavior; no proof of experience or attraction.") + try: + config["code_commit"] = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() + diff = subprocess.check_output(["git", "diff", "HEAD"]) + config["tracked_diff_sha256"] = hashlib.sha256(diff).hexdigest() + except subprocess.CalledProcessError: + pass + # Hash source bytes too: newly created, untracked files aren't in git diff. + config["source_sha256"] = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in Path(__file__).parent.glob("*.py")} + source_dir = args.output / "source" / "impossible_states" + source_dir.mkdir(parents=True) + for p in Path(__file__).parent.glob("*.py"): + (source_dir / p.name).write_bytes(p.read_bytes()) + config["dataset_sha256"] = hashlib.sha256((args.output / "dataset.json").read_bytes()).hexdigest() + write_json(args.output / "config.json", config) + + acts = engine.extract(rows, layers) + np.save(args.output / "activations.npy", acts) + vectors, center, scale = matched_vectors(acts, rows) + np.savez(args.output / "directions.npz", center=center, scale=scale, layers=np.array(layers), **vectors) + validation = separations(acts, rows, vectors, "validation") + selected = {} + for name, curve in validation.items(): + viable = [j for j in selectable if curve[j] is not None] + if viable: + selected[name] = max(viable, key=lambda j: curve[j]["auc"]) + write_json(args.output / "selection.json", dict(validation=validation, + selected_layers={name: layers[j] for name, j in selected.items()}, + selection_rule="Max validation AUC against all non-target conditions, excluding final block; earliest wins ties.")) + # Test set is evaluated only AFTER selection and never chooses a layer. + test = separations(acts, rows, vectors, "test") + write_json(args.output / "heldout.json", {name: dict(layer=layers[j], **test[name][j]) for name, j in selected.items()}) + print("selected layers:", {name: layers[j] for name, j in selected.items()}, flush=True) + intervention = {name: layers.index(args.steering_layer) if args.steering_layer is not None else j + for name, j in selected.items()} + write_json(args.output / "intervention.json", {name: dict(layer=layers[j], + policy="predeclared common layer" if args.steering_layer is not None else "validation AUC") + for name, j in intervention.items()}) + + if not args.fit_only: + targets = [name for name in ("constipation", "flatulence", "interaction", "pain") if name in selected] + if not targets: + raise ValueError("No nondegenerate target direction; inspect validation data before generation") + experiments = [] + for name in targets: + j = intervention[name] + experiments.append((name, j, vectors[name][j], vectors[name][-1])) + rng = np.random.default_rng(503) + for k in range(1 if args.smoke else args.random_controls): + # Random controls at EVERY target's selected layer, with paired norms. + for name in targets: + j = intervention[name] + experiments.append((f"random{k}_for_{name}", j, rng.normal(size=acts.shape[-1]), vectors[name][-1])) + np.savez_compressed(args.output / "generation_vectors.npz", + **{name + "__steering_raw": vec for name, j, vec, readvec in experiments}, + **{name + "__readout_raw": readvec for name, j, vec, readvec in experiments}) + doses = [0.1] if args.smoke else args.doses + seeds = args.seeds[:1] if args.smoke else args.seeds + panel = COMPLETION_PROMPTS if args.prompt_format == "completion" else PROMPTS + prompts = panel[:1] if args.smoke else panel + modes = ("continuous", "pulse", "rebuild") if args.smoke else ("continuous", "pulse", "rebuild", "perturb") + max_tokens = min(args.max_tokens, 16) if args.smoke else args.max_tokens + if not 0 < args.pulse_tokens < max_tokens: + raise ValueError("Pulse length must be positive and shorter than generation") + records = [] + path = args.output / "generations.jsonl" + with path.open("w") as f: + def record(r, name, prompt_name, expected): + r.update(direction=name, prompt_name=prompt_name, metrics=text_metrics(r["text"])) + if expected: + r["task_exact_match"] = r["text"].strip() == expected + records.append(r) + f.write(json.dumps(r, allow_nan=False) + "\n") + f.flush() + print(f"generation {len(records)}: {name} {r['mode']} dose={r['dose']} {r['text'][:100]!r}", flush=True) + + # Baselines are generated once per prompt/seed rather than counted + # repeatedly as independent observations for each direction. + first = targets[0] + j = intervention[first] + for pname, prompt, expected in prompts: + for seed in seeds: + r = engine.rollout(prompt, layers[j], unit(vectors[first][j]), center[j], scale[j], 0, "baseline", seed, max_tokens, args.pulse_tokens) + record(r, "none", pname, expected) + for name, j, vec, readvec in experiments: + readout = (layers[-1], unit(readvec), center[-1], scale[-1]) + for dose in doses: + for pname, prompt, expected in prompts: + for seed in seeds: + for mode in modes: + r = engine.rollout(prompt, layers[j], unit(vec), center[j], scale[j], dose, mode, + seed, max_tokens, args.pulse_tokens, readout=readout) + record(r, name, pname, expected) + + # Fixed visible token sequence removes generated-word differences. + forced = tokenizer.encode(" The room is quiet. A book rests on the table. The day continues.", add_special_tokens=False)[:max_tokens] + traces = [] + for name, j, vec, readvec in experiments: + readout = (layers[-1], unit(readvec), center[-1], scale[-1]) + for mode in ("baseline", "pulse", "rebuild", "perturb"): + r = engine.rollout(panel[0][1], layers[j], unit(vec), center[j], scale[j], 0.1, mode, + seeds[0], max_tokens, args.pulse_tokens, forced_tokens=forced, readout=readout) + r["direction"] = name + traces.append(r) + write_json(args.output / "teacher_forced.json", traces) + groups = {} + for r in records: + key = (r["direction"], r["dose"], r["mode"], r["prompt_name"]) + groups.setdefault(key, []).append(r) + aggregated = [] + for (name, dose, mode, prompt_name), rs in groups.items(): + group = dict(direction=name, dose=dose, mode=mode, prompt_name=prompt_name, n=len(rs), + keyword_presence={k: float(np.mean([r["metrics"]["keyword_hits"][k] > 0 for r in rs])) + for k in rs[0]["metrics"]["keyword_hits"]}, + mean_repetition=float(np.mean([r["metrics"]["repeated_trigram_fraction"] for r in rs]))) + if "task_exact_match" in rs[0]: + group["task_exact_match_rate"] = float(np.mean([r["task_exact_match"] for r in rs])) + aggregated.append(group) + write_json(args.output / "summary.json", dict(generations=len(records), teacher_forced_runs=len(traces), + directions=targets, modes=list(modes), + groups=aggregated, + warning="Smoke is a software/memory check. Keyword counts and projections are proxies, not validated state or attractor measures.")) + + memory = dict(elapsed_seconds=time.monotonic()-started) + if device == "cuda": + torch.cuda.synchronize() + memory.update(peak_allocated_gib=torch.cuda.max_memory_allocated()/2**30, + peak_reserved_gib=torch.cuda.max_memory_reserved()/2**30, + gpu=torch.cuda.get_device_name()) + write_json(args.output / "resources.json", memory) + print("resources:", memory, flush=True) + print("wrote", args.output, flush=True) + +if __name__ == "__main__": + main() diff --git a/tests/test_chamber_regressions.py b/tests/test_chamber_regressions.py new file mode 100644 index 0000000..42dd290 --- /dev/null +++ b/tests/test_chamber_regressions.py @@ -0,0 +1,113 @@ +"""Exercise legacy expressions without importing scripts that load a GPU model.""" +import ast +from pathlib import Path +import unittest +import torch + +ROOT = Path(__file__).resolve().parents[1] + +def tree(name): + return ast.parse((ROOT / name).read_text()) + +def assignments(name, target): + return [n for n in ast.walk(tree(name)) if isinstance(n, ast.Assign) + and any(ast.unparse(t) == target for t in n.targets)] + +def evaluate(node, scope): + return eval(compile(ast.Expression(node), '', 'eval'), scope) + +class ChamberRegressionTests(unittest.TestCase): + def test_parent_constants_and_crossed_bodily_corpora(self): + from impossible_states.chamber_control import literal_constants, bodily_corpora + constants = literal_constants(ROOT/'exp38_broad_harvest.py', ('PAIN','NEUTRAL','PROMPTS')) + self.assertEqual([len(constants[k]) for k in ('PAIN','NEUTRAL','PROMPTS')], [25,5,6]) + corpora = bodily_corpora() + self.assertEqual({len(v) for v in corpora.values()}, {25}) + for c,f,b in zip(corpora['constipation'],corpora['flatulence'],corpora['both']): + self.assertEqual(b, c+' '+f) + + def test_parent_hook_zero_dose_and_nonzero_effect(self): + from transformers import Qwen3Config, Qwen3ForCausalLM + from impossible_states.chamber_control import install_hook + torch.manual_seed(10) + model = Qwen3ForCausalLM(Qwen3Config(vocab_size=64,hidden_size=32,intermediate_size=64, + num_hidden_layers=3,num_attention_heads=4,num_key_value_heads=2,head_dim=8, + eos_token_id=None)).eval() + ids = torch.tensor([[3,4,5]]) + with torch.no_grad(): baseline = model(ids).logits.clone() + state = {'vec': torch.zeros(32)} + handle = install_hook(model,1,state) + try: + with torch.no_grad(): zero = model(ids).logits.clone() + state['vec'] = torch.randn(32) + with torch.no_grad(): changed = model(ids).logits.clone() + self.assertTrue(torch.equal(baseline,zero)) + self.assertTrue(torch.equal(baseline[0,:-1],changed[0,:-1])) + self.assertGreater(float((baseline[0,-1]-changed[0,-1]).norm()), 1e-4) + finally: + handle.remove() + self.assertEqual(len(model.model.layers[1]._forward_hooks),0) + + def test_orthogonal_pain_is_orthogonal_to_nonunit_joy(self): + pain = torch.tensor([3., 4., 1.]) + joy = torch.tensor([3., 0., 0.]) + projection = assignments('exp36_signal_batteries.py', 'pv')[0].value + result = evaluate(projection, {'pain_v': pain, 'joy_v': joy}) + self.assertAlmostEqual(float(result @ joy), 0., places=5) + self.assertTrue(torch.allclose(result[1:], pain[1:])) + + def test_transcript_uses_the_ranked_vector_without_resampling(self): + loop = next(n for n in ast.walk(tree('exp33_nonhuman_valences.py')) + if isinstance(n, ast.For) and ast.unparse(n.iter) == 'results[:6]') + setup = loop.body[:next(i for i,n in enumerate(loop.body) + if isinstance(n, ast.Assign) and ast.unparse(n.targets[0]) == 'texts')] + measured = torch.tensor([0., 2., 3., 4.]) + scope = {'torch': torch, 'r': {'idx': 2}, 'd': 4, + 'basis': [torch.tensor([1.,0.,0.,0.])], 'N': torch.ones(4), + 'candidate_vectors': {2: measured}} + exec(compile(ast.Module(body=setup, type_ignores=[]), '', 'exec'), scope) + self.assertTrue(torch.equal(scope['v'], measured)) + + def test_optimized_objective_applies_the_advertised_dose(self): + fun = next(n for n in tree('exp34_optimized_valence.py').body + if isinstance(n, ast.FunctionDef) and n.name == 'mean_kl') + injection = next(n for n in fun.body if isinstance(n, ast.Assign) + and ast.unparse(n.targets[0]) == "state['vec']") + v = torch.tensor([1.,2.,3.]) + self.assertTrue(torch.equal(evaluate(injection.value, {'v_t': v, 'DOSE': 4}), 4*v)) + + def test_initial_search_vector_lies_in_the_orthogonal_plane(self): + # Only initializer statements before the search, excluding loop updates. + body = tree('exp34_optimized_valence.py').body + first = next( + i for i,n in enumerate(body) if isinstance(n, ast.Assign) + and any(ast.unparse(t) == 'v' for t in n.targets)) + setup = [] + for n in body[first:]: + if not (isinstance(n, ast.Assign) and any(ast.unparse(t) == 'v' for t in n.targets)): + break + setup.append(n) + torch.manual_seed(12) + V = torch.eye(4)[:2] + scope = {'torch': torch, 'd': 4, 'V': V, 'scale': 2.} + exec(compile(ast.Module(body=setup, type_ignores=[]), '', 'exec'), scope) + self.assertTrue(torch.allclose(V @ scope['v'], torch.zeros(2), atol=1e-6)) + + def test_each_completion_crops_its_own_prompt(self): + decode = assignments('exp23_pain_axis.py', 'text')[0].value + class Tokenizer: + def decode(self, ids, **kwargs): return ids.tolist() + result = evaluate(decode, {'tok': Tokenizer(), 'out': torch.arange(7).reshape(1,7), + 'ids': torch.zeros((1,4)), 'prompt_len': 2}) + self.assertEqual(result, [4,5,6]) + + def test_counterbalanced_instruction_occurs_once(self): + base = ast.literal_eval(assignments('exp37_framing_battery.py', 'BASE')[0].value) + for tail in ('Reply with 1 to press, or 0 to not press.', + 'Reply with 0 to not press, or 1 to press.'): + prompt = base + ' ' + tail + self.assertEqual(prompt.count('Reply with'), 1) + self.assertTrue(prompt.endswith(tail)) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_impossible_states.py b/tests/test_impossible_states.py new file mode 100644 index 0000000..fc41b18 --- /dev/null +++ b/tests/test_impossible_states.py @@ -0,0 +1,98 @@ +import unittest +import numpy as np +from impossible_states.dataset import build_dataset, smoke_subset, validate +from impossible_states.analysis import auc, matched_vectors, text_metrics, unit + +class DatasetTests(unittest.TestCase): + def test_split_leakage_is_rejected(self): + rows = build_dataset() + validate(rows) + validate(smoke_subset(rows)) + rows[0]["split"] = "test" + with self.assertRaises(ValueError): + validate(rows) + + def test_factorial_effects_are_recovered(self): + rows = build_dataset() + effects = {"neither": [0,0,0], "constipation": [2,0,0], "flatulence": [0,3,0], + "both": [2,3,5], "pain": [1,1,0], "discomfort": [0,0,1], "frustration": [0,1,0]} + acts = np.array([[effects[r["condition"]]] for r in rows], dtype=float) + vecs, _, _ = matched_vectors(acts, rows) + np.testing.assert_allclose(vecs["constipation"][0], [2,0,2.5]) + np.testing.assert_allclose(vecs["flatulence"][0], [0,3,2.5]) + np.testing.assert_allclose(vecs["interaction"][0], [0,0,5]) + + def test_auc_ties_and_direction(self): + self.assertEqual(auc([1,1], [1,1]), 0.5) + self.assertEqual(auc([2,3], [0,1]), 1.0) + self.assertEqual(auc([0,1], [2,3]), 0.0) + + def test_word_boundaries(self): + hits = text_metrics("My party has charts.")["keyword_hits"] + self.assertEqual(hits["flatulence"], 0) + self.assertEqual(hits["pain"], 0) + self.assertEqual(text_metrics("I passed gas.")["keyword_hits"]["flatulence"], 1) + + def test_degenerate_directions_fail_explicitly(self): + for v in ([0,0,0], [np.nan,1,2]): + with self.assertRaises(ValueError): + unit(np.array(v)) + + def test_pronouns_do_not_corrupt_symptom_words(self): + third = [r["text"] for r in build_dataset() if r["perspective"] == "third"] + self.assertTrue(any("bowel movement" in t for t in third)) + self.assertFalse(any("movethement" in t for t in third)) + +class CacheTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + import torch + from transformers import Qwen3Config, Qwen3ForCausalLM + from impossible_states.engine import Engine + torch.manual_seed(5) + config = Qwen3Config(vocab_size=64, hidden_size=32, intermediate_size=64, + num_hidden_layers=3, num_attention_heads=4, num_key_value_heads=2, + head_dim=8, max_position_embeddings=128, eos_token_id=None) + class Tokenizer: + def apply_chat_template(self, *args, **kwargs): return "prompt" + def __call__(self, *args, **kwargs): + from types import SimpleNamespace + return SimpleNamespace(input_ids=torch.tensor([[3,4,5]])) + def decode(self, tokens, **kwargs): return " ".join(map(str,tokens)) + cls.engine = Engine(Qwen3ForCausalLM(config), Tokenizer(), "cpu") + cls.direction = np.random.default_rng(3).normal(size=32) + + def run_arm(self, mode, forced=None): + return self.engine.rollout("prompt", 0, self.direction, np.zeros(32), 1, 0.5, + mode, max_tokens=8, pulse_tokens=2, forced_tokens=forced, + readout=(2, self.direction, np.zeros(32), 1)) + + def test_release_keeps_identical_prefix_and_cleans_cache(self): + pulse = self.run_arm("pulse") + rebuilt = self.run_arm("rebuild") + self.assertEqual(pulse["generated_token_ids"][:2], rebuilt["generated_token_ids"][:2]) + forced = [6,7,8,9,10,11] + baseline = self.run_arm("baseline", forced) + rebuilt = self.run_arm("rebuild", forced) + pulse = self.run_arm("pulse", forced) + for b, r in zip(baseline["trace"][2:], rebuilt["trace"][2:]): + self.assertAlmostEqual(b["downstream_projection"], r["downstream_projection"], places=5) + self.assertTrue(any(abs(b["downstream_projection"]-p["downstream_projection"]) > 1e-6 + for b,p in zip(baseline["trace"][2:], pulse["trace"][2:]))) + + def test_zero_dose_does_not_change_generation(self): + results = [self.engine.rollout("prompt", 0, self.direction, np.zeros(32), 1, 0, + mode, max_tokens=8, pulse_tokens=2) for mode in ("baseline", "continuous", "pulse", "rebuild", "perturb")] + self.assertTrue(all(r["generated_token_ids"] == results[0]["generated_token_ids"] for r in results)) + self.assertEqual(len(self.engine.blocks[0]._forward_hooks), 0) + + def test_signed_displacement_and_release_schedule(self): + for dose in (-0.2, 0.2): + r = self.engine.rollout("prompt", 0, self.direction, np.zeros(32), 1, + dose, "perturb", pulse_tokens=2, forced_tokens=[6,7,8,9,10]) + expected = [dose, dose, -dose, 0, 0] + for trace, change in zip(r["trace"], expected): + self.assertAlmostEqual(trace["after"]-trace["before"], change, places=5) + +if __name__ == "__main__": + unittest.main()