JacobLinCool commited on
Commit
07bbce3
·
verified ·
1 Parent(s): a950fde

Deploy the single-pass English editor with pinned CogLLM readouts

Browse files
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JacobLinCool
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,13 +1,26 @@
1
  ---
2
- title: CogLLM
3
- emoji: 📈
4
- colorFrom: gray
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 6.32.0
8
- python_version: '3.13'
9
  app_file: app.py
10
- pinned: false
 
 
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
1
  ---
2
+ title: CogLLM Writing Review
3
+ emoji: 📖
4
+ colorFrom: green
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 6.17.3
8
+ python_version: "3.12"
9
  app_file: app.py
10
+ suggested_hardware: cpu-basic
11
+ short_description: See which words and sentence connections may slow a reader
12
+ license: mit
13
+ models:
14
+ - JacobLinCool/CogLLM-Qwen3.5-2B
15
+ - Qwen/Qwen3.5-2B
16
+ preload_from_hub:
17
+ - Qwen/Qwen3.5-2B config.json,model.safetensors-00001-of-00001.safetensors,model.safetensors.index.json,tokenizer.json,tokenizer_config.json 15852e8c16360a2fea060d615a32b45270f8a8fc
18
  ---
19
 
20
+ # CogLLM Writing Review
21
+
22
+ Paste a short English passage and select **Review draft**. The background color estimates the reading ease of each completed sentence. Underlines mark wording that may need explanation. A dashed outline flags a sentence whose connection to the preceding text deserves a second look. The experimental token curves are available under the marked draft.
23
+
24
+ This Space accepts up to 512 model tokens per passage and processes one passage at a time on CPU. The first analysis after a restart may take longer. All scores for a passage share one causal forward through Qwen3.5-2B.
25
+
26
+ The reading-ease and wording heads learned from readers of biomedical texts. The connection head learned from readers marking short stories and detected fewer breaks when applied to student essays. Individual confusion, understanding and moment of resolution remain unverified. The model card describes the observed human outcomes and the held-out evaluations. [CogLLM model card](https://huggingface.co/JacobLinCool/CogLLM-Qwen3.5-2B/blob/7d78fdd4334af1c6fcd5f99b7517b14c3b43c1f5/README.md)
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Serve the released CogLLM writer on the Hugging Face CPU Basic hardware."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import gradio as gr
7
+ from huggingface_hub import hf_hub_download, snapshot_download
8
+
9
+ from release.medical_lexicon import load_writing_head
10
+ from research.backbone_transfer.extract import digest
11
+ from research.reading_validation.transition_inference import TransitionInference
12
+ from research.token_readout.app import CSS
13
+ from research.token_readout.portable_runner import load
14
+ from research.token_readout.writing_review import STYLE, build_app
15
+
16
+
17
+ MAX_TOKENS = 512
18
+
19
+
20
+ def load_writer(model_id, model_revision):
21
+ manifest_path = hf_hub_download(model_id, "manifest.json", revision=model_revision, token=False)
22
+ manifest = json.loads(Path(manifest_path).read_text())
23
+ if manifest["schema"] != "cogllm-writing-model-v1" or manifest["model_id"] != model_id:
24
+ raise ValueError("The release manifest does not identify the selected CogLLM writer.")
25
+ snapshot = Path(snapshot_download(model_id, revision=model_revision, allow_patterns=list(manifest["files"]), token=False))
26
+ for relative, expected in manifest["files"].items():
27
+ if digest(snapshot / relative) != expected:
28
+ raise ValueError(f"Released model file differs from its manifest: {relative}")
29
+ base = manifest["base_model"]
30
+ backbone = Path(snapshot_download(base["repo_id"], revision=base["revision"], allow_patterns=list(base["files"]), token=False))
31
+ return load(
32
+ model=backbone,
33
+ checkpoint=snapshot / manifest["token_checkpoint"],
34
+ english_head=load_writing_head(snapshot / manifest["local_directory"]),
35
+ transition_head=TransitionInference.load(snapshot / manifest["transition_checkpoint"]),
36
+ serving_device="cpu",
37
+ )
38
+
39
+
40
+ class HostedWriter:
41
+ def __init__(self, runner):
42
+ self.runner = runner
43
+
44
+ def review_english(self, text, **options):
45
+ if not isinstance(text, str) or not text.strip():
46
+ raise ValueError("Paste a passage or choose the example.")
47
+ # A byte-level tokenizer can produce a single token for a long repeated run.
48
+ # Bound tokenizer work as well as the subsequent model forward.
49
+ if len(text) > 32_768 or len(self.runner.runtime.tokenizer.encode(text, add_special_tokens=False).ids) > MAX_TOKENS:
50
+ raise ValueError(f"Please shorten the passage to {MAX_TOKENS} model tokens or fewer.")
51
+ return self.runner.review_english(text, **options)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ release = json.loads(Path(__file__).with_name("release.json").read_text())
56
+ runner = HostedWriter(load_writer(release["model_id"], release["model_revision"]))
57
+ ui = build_app(runner, study_tools=False, max_tokens=MAX_TOKENS)
58
+ ui.queue(default_concurrency_limit=1, max_size=12).launch(
59
+ server_name="0.0.0.0",
60
+ server_port=7860,
61
+ share=False,
62
+ css=CSS + STYLE,
63
+ theme=gr.themes.Soft(primary_hue="teal", neutral_hue="slate"),
64
+ )
release.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "model_id": "JacobLinCool/CogLLM-Qwen3.5-2B",
3
+ "model_revision": "7d78fdd4334af1c6fcd5f99b7517b14c3b43c1f5"
4
+ }
release/medical_lexicon.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rebuild the published reader's lexical features from the original MedReadMe hosts."""
2
+
3
+ import gzip
4
+ from hashlib import sha256
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ from shutil import copyfileobj
9
+ from tempfile import TemporaryDirectory
10
+ from urllib.request import urlopen
11
+
12
+ from research.reading_validation.local_features import Lexicon, medical_counts
13
+ from research.reading_validation.local_inference import LEXICON_DIGEST, LocalInference
14
+ from research.stage6.medreadme_span_audit import FILES, REVISION
15
+
16
+ FREQUENCY_DIGEST = "81b4f6de9ca44c4c1f80637a0c3e455a66db97b6efb94ef96fe2e9754749978a"
17
+ SOURCE = f"https://raw.githubusercontent.com/chaojiang06/medreadme/{REVISION}/dataset"
18
+
19
+
20
+ def reconstruct(directory, raw):
21
+ """Return exactly the features used in the final English estimator."""
22
+ frequencies = gzip.decompress((directory / "complex-frequencies.json.gz").read_bytes())
23
+ if sha256(frequencies).hexdigest() != FREQUENCY_DIGEST:
24
+ raise ValueError("The released CompLex frequencies have changed")
25
+ medical, coverage = medical_counts(raw, exclude=lambda words: False)
26
+ if coverage != {"used_sentences": 2559, "ambiguous_or_unaligned": 28}:
27
+ raise ValueError("The training subset differs from the published MedReadMe feature fit")
28
+ parameters = Lexicon(json.loads(frequencies), *medical).records()
29
+ canonical = json.dumps(parameters, separators=(",", ":"), sort_keys=True).encode()
30
+ if sha256(canonical).hexdigest() != LEXICON_DIGEST:
31
+ raise ValueError("Rebuilt lexical features differ from the validated reading model")
32
+ return canonical
33
+
34
+
35
+ def load_writing_head(directory, *, cache_directory=None):
36
+ """Load the editor's verified wording and sentence weights, caching only fitted features."""
37
+ directory = Path(directory)
38
+ cache_root = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
39
+ cache = Path(cache_directory) if cache_directory is not None else cache_root / "cogllm"
40
+ cache.mkdir(parents=True, exist_ok=True)
41
+ target = cache / f"lexicon-{LEXICON_DIGEST}.json"
42
+ if not target.exists():
43
+ with TemporaryDirectory(dir=cache) as temp:
44
+ work = Path(temp)
45
+ for filename in FILES:
46
+ with urlopen(f"{SOURCE}/{filename}", timeout=60) as source:
47
+ with (work / filename).open("wb") as output:
48
+ copyfileobj(source, output)
49
+ built = work / "lexical-parameters.json"
50
+ built.write_bytes(reconstruct(directory, work))
51
+ built.replace(target)
52
+ return LocalInference.from_lexicon(directory, target.read_bytes())
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch @ https://download-r2.pytorch.org/whl/cpu/torch-2.14.1%2Bcpu-cp312-cp312-manylinux_2_28_x86_64.whl#sha256=5a6363570c753812540a05eb82380e329469cbe668643e88111414c12627711f
2
+ transformers==5.17.0
3
+ accelerate==1.13.0
4
+ gradio==6.17.3
research/backbone_transfer/extract.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract comparable causal text states from pinned small language models on one L4."""
2
+
3
+ import argparse
4
+ from collections import Counter, defaultdict
5
+ from dataclasses import dataclass
6
+ from hashlib import file_digest, sha256
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import re
11
+ from tempfile import TemporaryDirectory
12
+ from time import perf_counter
13
+
14
+
15
+ MODELS = Path(__file__).with_name('models.json')
16
+ MAX_INPUT_TOKENS = 2048
17
+ MAX_BATCH_TOKENS = 1024
18
+ MAX_BATCH_DOCUMENTS = 8
19
+ MAX_PREFIX_BATCH = 128
20
+ MAX_CONTROLS = 6
21
+ RELATIVE_RMS_LIMIT = 0.001
22
+ REPLACEMENT_SUFFIXES = (' A separate note follows.', '\n\nThis is a different passage.')
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Document:
27
+ identifier: str
28
+ text: str
29
+ ids: list[int]
30
+ offsets: list[tuple[int, int]]
31
+ certified: dict[int, int]
32
+ missing: dict[int, str]
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class FrozenBackbone:
37
+ candidate: str
38
+ model: Path
39
+ encoder: object
40
+ spec: dict
41
+ load_seconds: float
42
+
43
+
44
+ def digest(path):
45
+ with path.open('rb') as stream:
46
+ return file_digest(stream, 'sha256').hexdigest()
47
+
48
+
49
+ def read_json(path):
50
+ return json.loads(path.read_text(encoding='utf-8'))
51
+
52
+
53
+ def write_json(path, content):
54
+ with path.open('x', encoding='utf-8') as stream:
55
+ json.dump(content, stream, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False)
56
+ stream.write('\n')
57
+
58
+
59
+ def stream_rows(path):
60
+ with path.open(encoding='utf-8') as stream:
61
+ for line in stream:
62
+ yield json.loads(line)
63
+
64
+
65
+ def write_rows(path, content):
66
+ with path.open('x', encoding='utf-8') as stream:
67
+ for row in content:
68
+ stream.write(json.dumps(row, ensure_ascii=False, separators=(',', ':'), allow_nan=False) + '\n')
69
+
70
+
71
+ def checked_digest(value):
72
+ if re.fullmatch(r'[0-9a-f]{64}', value) is None:
73
+ raise argparse.ArgumentTypeError('Expected a lower-case SHA-256 digest')
74
+ return value
75
+
76
+
77
+ def verified_model(model, alias, *, tokenizer_only=False):
78
+ manifest = read_json(MODELS)
79
+ spec = manifest['models'][alias]
80
+ hashes = spec['sha256']
81
+ if manifest['schema'] != 1 or set(spec['files']) != set(hashes):
82
+ raise ValueError('The model file and SHA-256 inventories must match')
83
+ files = ('tokenizer.json',) if tokenizer_only else spec['files']
84
+ if not tokenizer_only and model.name != spec['revision']:
85
+ raise ValueError('Expected the named local immutable model snapshot')
86
+ for name in files:
87
+ if digest(model / name) != hashes[name]:
88
+ raise ValueError(f'{alias} snapshot file digest differs: {name}')
89
+ if not tokenizer_only:
90
+ local_code = {path.name for path in model.glob('*.py')}
91
+ if local_code != {name for name in files if name.endswith('.py')}:
92
+ raise ValueError('Snapshot contains Python files outside the audited code allowlist')
93
+ return spec.get('transformers', manifest['transformers']), spec
94
+
95
+
96
+ def load_documents(path, tokenizer):
97
+ documents = {}
98
+ for row in stream_rows(path):
99
+ if not isinstance(row, dict) or set(row) != {'id', 'text', 'stops'}:
100
+ raise ValueError('Inference input accepts only id, exact text, and Unicode end stops')
101
+ key, text, stops = (row[name] for name in ('id', 'text', 'stops'))
102
+ if (type(key) is not str or not key or key in documents or type(text) is not str
103
+ or not text.strip() or type(stops) is not list or not stops
104
+ or any(type(stop) is not int or not 0 < stop <= len(text) for stop in stops)
105
+ or stops != sorted(set(stops))):
106
+ raise ValueError('A source document identity, text or stop is invalid')
107
+ encoded = tokenizer.encode(text, add_special_tokens=False)
108
+ documents[key] = certify(key, text, stops, encoded, tokenizer)
109
+ if not documents or not any(doc.certified for doc in documents.values()):
110
+ raise ValueError('No exact text states could be certified')
111
+ return documents
112
+
113
+
114
+ def certify(key, text, stops, encoded, tokenizer):
115
+ ids, offsets = encoded.ids, encoded.offsets
116
+ if (not ids or len(ids) != len(offsets)
117
+ or any(not 0 <= left <= right <= len(text) for left, right in offsets)):
118
+ raise ValueError(f'Invalid Unicode tokenization for {key}')
119
+ if len(ids) > MAX_INPUT_TOKENS:
120
+ raise ValueError(f'{key} exceeds the registered extraction length of {MAX_INPUT_TOKENS} tokens')
121
+
122
+ ends = {right: i for i, (left, right) in enumerate(offsets) if left < right}
123
+ candidates = [(stop, ends[stop]) for stop in stops if stop in ends]
124
+ missing = {stop: 'no_token_end' for stop in stops if stop not in ends}
125
+ certified = {}
126
+ for offset in range(0, len(candidates), MAX_PREFIX_BATCH):
127
+ batch = candidates[offset:offset + MAX_PREFIX_BATCH]
128
+ independent = tokenizer.encode_batch([text[:stop] for stop, _ in batch], add_special_tokens=False)
129
+ for (stop, index), prefix in zip(batch, independent, strict=True):
130
+ if prefix.ids != ids[:index + 1] or any(right > stop for _, right in offsets[:index + 1]):
131
+ missing[stop] = 'unstable_prefix'
132
+ else:
133
+ certified[stop] = index
134
+ return Document(key, text, ids, offsets, certified, dict(sorted(missing.items())))
135
+
136
+
137
+ def target_geometry(path, documents):
138
+ if path is None:
139
+ return []
140
+ from research.stage5.complex_tokenization import token_span
141
+
142
+ records, seen = [], set()
143
+ for row in stream_rows(path):
144
+ if not isinstance(row, dict) or set(row) != {'id', 'start', 'end'} or row['id'] not in documents:
145
+ raise ValueError('Target coordinates accept only an existing model-input id and start/end')
146
+ key, start, stop = row['id'], row['start'], row['end']
147
+ doc = documents[key]
148
+ if (type(start) is not int or type(stop) is not int or not 0 <= start < stop <= len(doc.text)
149
+ or (stop not in doc.certified and stop not in doc.missing) or (key, start, stop) in seen):
150
+ raise ValueError(f'Unexpected or duplicate grade-free target in {key}')
151
+ seen.add((key, start, stop))
152
+ status, pair = token_span(doc.text, doc.offsets, start, stop)
153
+ if stop not in doc.certified:
154
+ status = doc.missing[stop]
155
+ elif pair is not None and pair[1] != doc.certified[stop]:
156
+ status = 'target_last_token_differs_from_prefix_endpoint'
157
+ eligible = status == 'exact_nonwhite_span'
158
+ records.append({
159
+ **row, 'status': status, 'eligible': eligible,
160
+ 'start_token': pair[0] if eligible else None,
161
+ 'end_token': pair[1] if eligible else None,
162
+ })
163
+ if not records:
164
+ raise ValueError('An accompanying target file must contain at least one grade-free span')
165
+ return records
166
+
167
+
168
+ def geometry(alias, tokenizer_root, stimuli, targets, protocol_sha256):
169
+ from tokenizers import Tokenizer, __version__
170
+
171
+ _, spec = verified_model(tokenizer_root, alias, tokenizer_only=True)
172
+ tokenizer = Tokenizer.from_file(str(tokenizer_root / 'tokenizer.json'))
173
+ documents = load_documents(stimuli, tokenizer)
174
+ target_rows = target_geometry(targets, documents)
175
+ errors = Counter(reason for row in documents.values() for reason in row.missing.values())
176
+ result = {
177
+ 'candidate': alias,
178
+ 'model': spec['repo'],
179
+ 'revision': spec['revision'],
180
+ 'protocol_sha256': protocol_sha256,
181
+ 'stimuli_sha256': digest(stimuli),
182
+ 'targets_sha256': digest(targets) if targets else None,
183
+ 'tokenizer_sha256': spec['sha256']['tokenizer.json'],
184
+ 'tokenizers': __version__,
185
+ 'special_tokens': False,
186
+ 'documents': len(documents),
187
+ 'input_tokens': sum(len(row.ids) for row in documents.values()),
188
+ 'max_input_tokens': max(len(row.ids) for row in documents.values()),
189
+ 'requested_stops': sum(len(row.certified) + len(row.missing) for row in documents.values()),
190
+ 'certified_stops': sum(len(row.certified) for row in documents.values()),
191
+ 'unavailable_stops_by_reason': dict(errors),
192
+ 'details': [{
193
+ 'id': row.identifier,
194
+ 'stops': list(row.certified),
195
+ 'token_indices': list(row.certified.values()),
196
+ 'input_tokens': len(row.ids),
197
+ 'tokenization_sha256': sha256(json.dumps([row.ids, row.offsets], separators=(',', ':')).encode()).hexdigest(),
198
+ 'unavailable': [{'stop': stop, 'reason': reason} for stop, reason in row.missing.items()],
199
+ } for row in documents.values()],
200
+ 'target_geometry': target_rows,
201
+ 'target_geometry_by_status': dict(Counter(row['status'] for row in target_rows)),
202
+ }
203
+ return tokenizer, documents, result
204
+
205
+
206
+ def lfm_config(model):
207
+ from transformers.dynamic_module_utils import get_class_from_dynamic_module
208
+
209
+ raw = read_json(model / 'config.json')
210
+ attention_types = ('full_attention', 'sliding_attention')
211
+ if (raw['model_type'] != 'lfm3' or set(raw['rope_parameters']) != set(attention_types)
212
+ or set(raw['layer_types']) != {'conv', *attention_types}):
213
+ raise ValueError('Expected the exact LFM3 convolution and attention configuration')
214
+ cls = get_class_from_dynamic_module('configuration_lfm3.Lfm3Config', model, local_files_only=True)
215
+ if cls._attention_layer_types != attention_types:
216
+ raise ValueError('The LFM3 config class disagrees with its pinned attention layer types')
217
+ legacy_validator = cls.validate_layer_type
218
+ validators = [check for check in cls.__class_validators__ if check is not legacy_validator]
219
+ if len(validators) != len(cls.__class_validators__) - 1 or cls.validate_architecture not in validators:
220
+ raise ValueError('Unexpected LFM3 configuration validators')
221
+ standardize = cls.standardize_rope_params
222
+
223
+ def preserve_attention_rope(config):
224
+ # Transformers adds flat defaults intended for single-RoPE models. LFM3 already specifies both attention maps.
225
+ if (config.rope_parameters.pop('rope_theta') != config.default_theta
226
+ or config.rope_parameters != raw['rope_parameters']):
227
+ raise ValueError('Unexpected change to the original LFM3 attention rotary parameters')
228
+ standardize(config)
229
+
230
+ cls._rope_type_labels = attention_types
231
+ cls.standardize_rope_params = preserve_attention_rope
232
+ # LFM3's author validator already checks the layer sequence and keeps the actual "conv" type.
233
+ cls.__class_validators__ = validators
234
+ config = cls.from_pretrained(model, local_files_only=True)
235
+ if config.layer_types != raw['layer_types'] or config.rope_parameters != raw['rope_parameters']:
236
+ raise ValueError('Unexpected LFM3 metadata after Hugging Face config normalization')
237
+ config._attn_implementation = 'sdpa'
238
+ return config
239
+
240
+
241
+ def load_language_model(model, alias, torch, transformers, *, serving_device=None):
242
+ version, spec = verified_model(model, alias)
243
+ if transformers.__version__ != version:
244
+ raise RuntimeError(f'Expected Transformers {version} for the pinned model')
245
+ if serving_device is None:
246
+ if torch.cuda.device_count() != 1 or torch.cuda.get_device_name(0) != 'NVIDIA L4':
247
+ raise RuntimeError('The research extraction protocol requires one NVIDIA L4')
248
+ device = 'cuda'
249
+ else:
250
+ if alias != 'qwen' or serving_device not in ('cpu', 'cuda'):
251
+ raise ValueError('The public writer requires Qwen on CPU or CUDA')
252
+ device = serving_device
253
+ torch.set_num_threads(2)
254
+ torch.set_float32_matmul_precision('highest')
255
+ torch.backends.cudnn.allow_tf32 = False
256
+ options = {
257
+ 'local_files_only': True,
258
+ 'attn_implementation': 'sdpa',
259
+ 'dtype': torch.float32,
260
+ 'device_map': {'': device},
261
+ 'use_safetensors': True,
262
+ 'use_kernels': False,
263
+ 'output_loading_info': True,
264
+ }
265
+ ignored = ()
266
+ if alias == 'gemma4':
267
+ from transformers.models.gemma4.modeling_gemma4 import Gemma4TextModel
268
+
269
+ outer = transformers.AutoConfig.from_pretrained(model, local_files_only=True, trust_remote_code=False)
270
+ if outer.model_type != 'gemma4' or outer.text_config.model_type != 'gemma4_text':
271
+ raise ValueError('Expected the Gemma 4 text subconfiguration')
272
+ outer.text_config._attn_implementation = 'sdpa'
273
+ text_model, loading = Gemma4TextModel.from_pretrained(
274
+ model, config=outer.text_config, key_mapping={r'^model\.language_model\.': ''}, **options,
275
+ )
276
+ ignored = ('model.audio_tower.', 'model.embed_audio.', 'model.embed_vision.', 'model.vision_tower.')
277
+ else:
278
+ if alias == 'lfm3':
279
+ # This local snapshot contains only the three reviewed, hash-pinned author source files.
280
+ config = lfm_config(model)
281
+ whole, loading = transformers.AutoModelForCausalLM.from_pretrained(
282
+ model, config=config, trust_remote_code=True, **options,
283
+ )
284
+ if whole.config.layer_types != config.layer_types or whole.config.rope_parameters != config.rope_parameters:
285
+ raise RuntimeError('Loading changed an author-defined LFM3 layer or attention rotary setting')
286
+ else:
287
+ whole, loading = transformers.Qwen3_5ForCausalLM.from_pretrained(model, **options)
288
+ if type(whole).__name__ != spec['architecture']:
289
+ raise RuntimeError('Resolved causal model differs from the official manifest')
290
+ text_model = whole.model
291
+ del whole
292
+ unexpected = [key for key in loading.get('unexpected_keys', ()) if not key.startswith(ignored)]
293
+ if unexpected or any(value for field, value in loading.items() if field != 'unexpected_keys'):
294
+ raise RuntimeError(f'The requested text backbone did not load exactly: {loading}')
295
+ if (text_model.config.hidden_size != spec['hidden_width'] or len(text_model.layers) != spec['layers']
296
+ or any(value.dtype != torch.float32 or value.device.type != device for value in text_model.parameters())):
297
+ raise RuntimeError(f'Loaded text layers must match the frozen architecture and FP32 {device} contract')
298
+ return text_model.eval().requires_grad_(False), spec
299
+
300
+
301
+ def forward(encoder, sequences, pad_id, torch):
302
+ length = max(map(len, sequences))
303
+ ids = [row + [pad_id] * (length - len(row)) for row in sequences]
304
+ masks = [[1] * len(row) + [0] * (length - len(row)) for row in sequences]
305
+ with torch.inference_mode():
306
+ answer = encoder(input_ids=torch.tensor(ids, device='cuda', dtype=torch.long),
307
+ attention_mask=torch.tensor(masks, device='cuda', dtype=torch.long),
308
+ use_cache=False, output_hidden_states=False, output_attentions=False)
309
+ states = answer.last_hidden_state
310
+ if states.dtype != torch.float32 or states.shape[:2] != (len(ids), length):
311
+ raise RuntimeError('Expected FP32 final normalized hidden states for every input token')
312
+ return states
313
+
314
+
315
+ def causal_controls(encoder, documents, tokenizer, pad_id, torch):
316
+ checks = []
317
+ # Spread fixed, label-free controls across the input order and document lengths.
318
+ ordered = sorted(documents.values(), key=lambda doc: (len(doc.ids), doc.identifier))
319
+ positions = sorted({round((len(ordered) - 1) * i / (MAX_CONTROLS - 1)) for i in range(MAX_CONTROLS)})
320
+ for i in positions:
321
+ doc = ordered[i]
322
+ candidates = sorted(
323
+ {(right, index) for index, (left, right) in enumerate(doc.offsets)
324
+ if left < right and 2 <= index < len(doc.ids) - 1},
325
+ key=lambda pair: abs(pair[1] - len(doc.ids) // 2),
326
+ )
327
+ for end, index in candidates:
328
+ truncated = tokenizer.encode(doc.text[:end], add_special_tokens=False).ids
329
+ if truncated != doc.ids[:index + 1] or any(right > end for _, right in doc.offsets[:index + 1]):
330
+ continue
331
+ alternatives = tokenizer.encode_batch([doc.text[:end] + suffix for suffix in REPLACEMENT_SUFFIXES],
332
+ add_special_tokens=False)
333
+ replacement = next((item.ids for item in alternatives
334
+ if item.ids[:len(truncated)] == truncated and len(item.ids) > len(truncated)
335
+ and item.ids != doc.ids
336
+ and all(right <= end for _, right in item.offsets[:len(truncated)])), None)
337
+ if replacement is not None:
338
+ break
339
+ else:
340
+ continue
341
+ whole = forward(encoder, [doc.ids], pad_id, torch)[0, :len(truncated)]
342
+ for variant, tokens in (('truncation', truncated), ('replacement', replacement)):
343
+ prefix = forward(encoder, [tokens], pad_id, torch)[0, :len(truncated)]
344
+ error = (whole - prefix).square().mean(dim=-1).sqrt()
345
+ scale = prefix.square().mean(dim=-1).sqrt().clamp_min(1e-8)
346
+ relative = float((error / scale).max().item())
347
+ absolute = float((whole - prefix).abs().max().item())
348
+ passed = bool(torch.isfinite(whole).all().item() and torch.isfinite(prefix).all().item()
349
+ and relative <= RELATIVE_RMS_LIMIT)
350
+ checks.append({'id': doc.identifier, 'variant': variant, 'character_end': end,
351
+ 'prefix_tokens': len(truncated), 'max_relative_rms': relative,
352
+ 'max_absolute': absolute, 'passed': passed})
353
+ if len(checks) < 2 * min(3, len(documents)) or not all(row['passed'] for row in checks):
354
+ raise RuntimeError(f'Independent exact-prefix forward test failed: {checks}')
355
+ return {'checks': checks, 'relative_tolerance': RELATIVE_RMS_LIMIT,
356
+ 'comparison': 'original source states vs independently retokenized truncation and suffix replacement'}
357
+
358
+
359
+ def batches(documents, max_documents=MAX_BATCH_DOCUMENTS, max_tokens=MAX_BATCH_TOKENS):
360
+ classed = defaultdict(list)
361
+ for row in documents.values():
362
+ length = len(row.ids)
363
+ classed[(length - 1) // 16].append(row)
364
+ for bucket in reversed(sorted(classed)):
365
+ group = classed[bucket]
366
+ largest = max(len(row.ids) for row in group)
367
+ size = max(1, min(max_documents, max_tokens // largest))
368
+ for start in range(0, len(group), size):
369
+ yield group[start:start + size]
370
+
371
+
372
+ def load_frozen_backbone(candidate, model):
373
+ os.environ['HF_HUB_OFFLINE'] = '1'
374
+ os.environ['USE_HUB_KERNELS'] = 'NO'
375
+ import torch
376
+ import transformers
377
+
378
+ before_model = perf_counter()
379
+ torch.cuda.reset_peak_memory_stats()
380
+ encoder, spec = load_language_model(model, candidate, torch, transformers)
381
+ return FrozenBackbone(candidate, model, encoder, spec, perf_counter() - before_model)
382
+
383
+
384
+ def extract(candidate, model, stimuli, output, protocol_sha256, targets=None, preflight=None,
385
+ *, max_batch_documents=MAX_BATCH_DOCUMENTS, max_batch_tokens=MAX_BATCH_TOKENS):
386
+ if output.exists():
387
+ raise FileExistsError(output)
388
+ tokenizer, documents, summary = geometry(candidate, model, stimuli, targets, protocol_sha256)
389
+ if preflight is not None and read_json(preflight) != summary:
390
+ raise ValueError('Frozen tokenizer preflight differs from the runtime Unicode geometry')
391
+ backbone = load_frozen_backbone(candidate, model)
392
+ write_projection(backbone, tokenizer, documents, summary, output, backbone.load_seconds,
393
+ max_batch_documents, max_batch_tokens)
394
+
395
+
396
+ def extract_loaded(backbone, stimuli, output, protocol_sha256,
397
+ *, max_batch_documents=MAX_BATCH_DOCUMENTS, max_batch_tokens=MAX_BATCH_TOKENS):
398
+ """Extract another disjoint document set without reloading its frozen weights."""
399
+ import torch
400
+
401
+ if output.exists():
402
+ raise FileExistsError(output)
403
+ tokenizer, documents, summary = geometry(backbone.candidate, backbone.model, stimuli, None, protocol_sha256)
404
+ torch.cuda.reset_peak_memory_stats()
405
+ write_projection(backbone, tokenizer, documents, summary, output, 0.0,
406
+ max_batch_documents, max_batch_tokens)
407
+
408
+
409
+ def write_projection(backbone, tokenizer, documents, summary, output, load_seconds,
410
+ max_batch_documents, max_batch_tokens):
411
+ import numpy as np
412
+ import torch
413
+ import transformers
414
+
415
+ encoder, spec = backbone.encoder, backbone.spec
416
+ controls = causal_controls(encoder, documents, tokenizer, spec['pad_id'], torch)
417
+ ranges = {}
418
+ start = 0
419
+ coordinates = []
420
+ for row in documents.values():
421
+ end = start + len(row.certified)
422
+ ranges[row.identifier] = slice(start, end)
423
+ coordinates.append({'id': row.identifier, 'stops': list(row.certified)})
424
+ start = end
425
+
426
+ output.parent.mkdir(parents=True, exist_ok=True)
427
+ with TemporaryDirectory(dir=output.parent, prefix='.backbone-transfer-') as temporary:
428
+ stage = Path(temporary) / 'extraction'
429
+ stage.mkdir()
430
+ coordinates_path = stage / 'coordinates.jsonl'
431
+ preflight_path = stage / 'preflight.json'
432
+ causality_path = stage / 'causality.json'
433
+ states_path = stage / 'states.npy'
434
+ write_rows(coordinates_path, coordinates)
435
+ write_json(preflight_path, summary)
436
+ write_json(causality_path, controls)
437
+ shape = (start, spec['hidden_width'])
438
+ states = np.lib.format.open_memmap(states_path, mode='w+', dtype=np.float32, shape=shape)
439
+ start_content = perf_counter()
440
+ calls = 0
441
+ for batch in batches(documents, max_batch_documents, max_batch_tokens):
442
+ hidden = forward(encoder, [row.ids for row in batch], spec['pad_id'], torch)
443
+ if hidden.shape[-1] != spec['hidden_width']:
444
+ raise RuntimeError('A final layer returned an unexpected representation width')
445
+ selected = [(i, token) for i, row in enumerate(batch) for token in row.certified.values()]
446
+ if selected:
447
+ indices, positions = zip(*selected, strict=True)
448
+ picked = hidden[list(indices), list(positions)].cpu().numpy()
449
+ if not np.isfinite(picked).all():
450
+ raise RuntimeError('Encountered a nonfinite extracted hidden state')
451
+ row_start = 0
452
+ for row in batch:
453
+ next_start = row_start + len(row.certified)
454
+ states[ranges[row.identifier]] = picked[row_start:next_start]
455
+ row_start = next_start
456
+ del hidden
457
+ calls += 1
458
+ states.flush()
459
+ del states
460
+ write_json(stage / 'seal.json', {
461
+ 'candidate': backbone.candidate,
462
+ 'model': spec['repo'],
463
+ 'revision': spec['revision'],
464
+ 'architecture': spec['architecture'],
465
+ 'hidden_width': spec['hidden_width'],
466
+ 'layers': spec['layers'],
467
+ 'model_files_sha256': spec['sha256'],
468
+ 'config_adapter': spec.get('config_adapter'),
469
+ 'model_manifest_sha256': digest(MODELS),
470
+ 'source_code_sha256': digest(Path(__file__)),
471
+ 'protocol_sha256': summary['protocol_sha256'],
472
+ 'stimuli_sha256': summary['stimuli_sha256'],
473
+ 'targets_sha256': summary['targets_sha256'],
474
+ 'tokenizer_sha256': summary['tokenizer_sha256'],
475
+ 'states_dtype': 'float32',
476
+ 'compute_dtype': 'float32',
477
+ 'states_shape': list(shape),
478
+ 'gpu': torch.cuda.get_device_name(0),
479
+ 'torch': torch.__version__,
480
+ 'transformers': transformers.__version__,
481
+ 'cuda': torch.version.cuda,
482
+ 'content_forward_per_document': 1,
483
+ 'content_forward_batches': calls,
484
+ 'max_batch_documents': max_batch_documents,
485
+ 'max_batch_tokens': max_batch_tokens,
486
+ 'independent_causal_checks': len(controls['checks']),
487
+ 'documents': summary['documents'],
488
+ 'certified_stops': summary['certified_stops'],
489
+ 'peak_gpu_reserved_bytes': torch.cuda.max_memory_reserved(),
490
+ 'model_load_and_verification_s': load_seconds,
491
+ 'forward_and_readout_s': perf_counter() - start_content,
492
+ 'file_sha256': {item.name: digest(item) for item in (coordinates_path, preflight_path, causality_path, states_path)},
493
+ })
494
+ stage.rename(output)
495
+
496
+
497
+ def main():
498
+ parser = argparse.ArgumentParser(description=__doc__)
499
+ parser.add_argument('--candidate', choices=tuple(read_json(MODELS)['models']), required=True)
500
+ parser.add_argument('--model', type=Path, required=True)
501
+ parser.add_argument('--stimuli', type=Path, required=True)
502
+ parser.add_argument('--output', type=Path, required=True)
503
+ parser.add_argument('--protocol-sha256', type=checked_digest, required=True)
504
+ parser.add_argument('--targets', type=Path)
505
+ parser.add_argument('--preflight', type=Path)
506
+ parser.add_argument('--geometry-only', action='store_true')
507
+ args = parser.parse_args()
508
+ if args.geometry_only:
509
+ _, _, receipt = geometry(args.candidate, args.model, args.stimuli, args.targets, args.protocol_sha256)
510
+ args.output.parent.mkdir(parents=True, exist_ok=True)
511
+ write_json(args.output, receipt)
512
+ else:
513
+ extract(args.candidate, args.model, args.stimuli, args.output, args.protocol_sha256, args.targets, args.preflight)
514
+
515
+
516
+ if __name__ == '__main__':
517
+ main()
research/backbone_transfer/models.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": 1,
3
+ "transformers": "5.17.0",
4
+ "models": {
5
+ "qwen": {
6
+ "repo": "Qwen/Qwen3.5-2B",
7
+ "revision": "15852e8c16360a2fea060d615a32b45270f8a8fc",
8
+ "architecture": "Qwen3_5ForCausalLM",
9
+ "hidden_width": 2048,
10
+ "layers": 24,
11
+ "pad_id": 248044,
12
+ "files": [
13
+ "config.json",
14
+ "model.safetensors-00001-of-00001.safetensors",
15
+ "model.safetensors.index.json",
16
+ "tokenizer.json",
17
+ "tokenizer_config.json"
18
+ ],
19
+ "sha256": {
20
+ "config.json": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4",
21
+ "model.safetensors-00001-of-00001.safetensors": "aa33250c4fc64891ddfaba3a314fd9542ea371843c387178b425fbcc5ed680b1",
22
+ "model.safetensors.index.json": "aca8afed9da75b0f050b408d270766fd77627f1af401e240f61c3b47d0db02f9",
23
+ "tokenizer.json": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42",
24
+ "tokenizer_config.json": "49e2b6e395f959f077f1e992b338919c0d4a9732fc6e613995e06557f843500c"
25
+ }
26
+ },
27
+ "lfm3": {
28
+ "repo": "LiquidAI/LFM3-1.7B-Base",
29
+ "revision": "7bca5038823c0d0f14efe06439109354a10e014c",
30
+ "architecture": "Lfm3ForCausalLM",
31
+ "transformers": "5.17.0",
32
+ "config_adapter": "lfm3-authored-rope-and-layer-types",
33
+ "hidden_width": 2048,
34
+ "layers": 24,
35
+ "pad_id": 124893,
36
+ "license": "LFM Open License v1.0",
37
+ "files": [
38
+ "config.json",
39
+ "configuration_lfm3.py",
40
+ "lfm3_conv.py",
41
+ "model.safetensors",
42
+ "modeling_lfm3.py",
43
+ "tokenizer.json",
44
+ "tokenizer_config.json"
45
+ ],
46
+ "sha256": {
47
+ "config.json": "8c6ae8b8f6d88c87cfb98cf4b5e34e943d0ee07e24215c4121b3159a46e1399d",
48
+ "configuration_lfm3.py": "176cced35657aedfea7d7002221360582d1c05fcaca882c21508bc3a73b282e5",
49
+ "lfm3_conv.py": "80d4a985382a22774212759248a6b4c737bfbf9c2a47b3dd7f797dda748e4bb4",
50
+ "model.safetensors": "61a3f541d65b03a2180d08964bf0d55e349463a2706032814d455ae046bc8b59",
51
+ "modeling_lfm3.py": "e8cd5254ea99ce6bd731b57b10908c2e8b5010ce8315341f895a38484885eeab",
52
+ "tokenizer.json": "7e226e34bface23ccf6e495d157bf77186c1c30a7659880e1a8994db528c3701",
53
+ "tokenizer_config.json": "bf028f813efc6137bc07ed045cafe71820df9a5e26a38e39954706ed1e30a457"
54
+ }
55
+ },
56
+ "gemma4": {
57
+ "repo": "google/gemma-4-E2B",
58
+ "revision": "433813a669639fd7eaa83155828e9000ed357d53",
59
+ "architecture": "Gemma4TextModel",
60
+ "hidden_width": 1536,
61
+ "layers": 35,
62
+ "pad_id": 0,
63
+ "license": "Apache-2.0",
64
+ "text_weight_bf16_bytes": 9294899782,
65
+ "files": [
66
+ "config.json",
67
+ "model.safetensors",
68
+ "tokenizer.json",
69
+ "tokenizer_config.json"
70
+ ],
71
+ "sha256": {
72
+ "config.json": "e5faef0dd1a8f2437f6010721146b85433eaa90e679ef011e803c7ffefae73b8",
73
+ "model.safetensors": "76dc84a5a805a2c8b91e9ccc00b8dbf8f4a99bf0d56ab25832f6e6addd4f7f57",
74
+ "tokenizer.json": "9cad58a1ba9824a35574be51e8c9dcc2164a662cdfe56b1b008e06a231f80f0b",
75
+ "tokenizer_config.json": "12754e3442e47c1a1c55d550b617fc47ae227e8156ed1b1de0d8428195768b5c"
76
+ }
77
+ }
78
+ }
79
+ }
research/reading_validation/bridge_forecast.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single-pass Carter–Hoffman forecasts. Inputs contain text and display word boundaries."""
2
+ from dataclasses import replace
3
+ import hashlib
4
+ import json
5
+ import math
6
+ from pathlib import Path
7
+ import re
8
+
9
+ import torch
10
+ from torch.nn import functional as F
11
+
12
+ from research.token_readout.runner import trace_rows
13
+
14
+
15
+ STOP = set("a an the am is are was were be been being has have had do did does can could would should "
16
+ "may might will shall of by on at in to from and or but for as it its if this that these those "
17
+ "he she they them their his her him hers you i we our my me us with into out".split())
18
+ FEATURES = ("log_context_words", "log_target_words", "content_overlap", "boundary_overlap",
19
+ "mean_transition", "mean_word_surprisal", "mean_preamble_attention",
20
+ "mid_cosine", "final_cosine")
21
+
22
+
23
+ def norm_word(word):
24
+ return re.sub(r"[^a-z0-9]+", "", word.casefold())
25
+
26
+
27
+ def contiguous_overlap(preamble, target):
28
+ longest = min(len(preamble), len(target))
29
+ for width in range(longest, 0, -1):
30
+ if preamble[-width:] == target[:width]:
31
+ return width / len(target)
32
+ return 0.0
33
+
34
+
35
+ def features_for_text(runtime, reader, checkpoint, row):
36
+ text = row["text"]
37
+ feats = runtime.encode(text)
38
+ scores = reader(feats)
39
+ scale = checkpoint["scale"]
40
+ scores = replace(scores, opening=scores.opening * scale["opening_gain"],
41
+ resolution=scores.resolution * scale["resolution_gain"] + scale["resolution_bias"])
42
+ trace = trace_rows(text, feats.offsets, scores, checkpoint["priors"], reader.anchor_tokens)
43
+ context = list(re.finditer(r"\S+", text[:row["start"]]))
44
+ ctx_words = [norm_word(m.group()) for m in context]
45
+ words = [norm_word(text[start:end]) for start, end in row["target_words"]]
46
+ indices = set()
47
+ for match, word in zip(context, ctx_words, strict=True):
48
+ if word and word not in STOP:
49
+ indices.update(j for j, (s, e) in enumerate(feats.offsets)
50
+ if e > match.start() and s < match.end() and any(c.isalnum() for c in text[s:e]))
51
+ ctx_content = {w for w in ctx_words if w and w not in STOP}
52
+ ctx_tokens = [j for j, (s, e) in enumerate(feats.offsets) if e <= row["start"]]
53
+ target_tokens = [[j for j, (s, e) in enumerate(feats.offsets) if s < b and e > a]
54
+ for a, b in row["target_words"]]
55
+ flat = [i for span in target_tokens for i in span]
56
+ if not indices or not ctx_tokens or not flat or min(flat) < 1 or len(flat) != len(set(flat)):
57
+ raise ValueError("Ambiguous words or missing causal context")
58
+ if len(set(ctx_tokens).intersection(flat)) != 0:
59
+ raise ValueError("Context and target share a token")
60
+ if runtime.candidate != "qwen" or not runtime.encoder.config.tie_word_embeddings:
61
+ raise ValueError("This output projection requires Qwen's verified tied embedding weights")
62
+ vocab = runtime.encoder.embed_tokens.weight
63
+ idx = torch.tensor(flat, device=feats.hidden.device)
64
+ tokens = torch.tensor(feats.token_ids, device=idx.device)
65
+ losses = []
66
+ for chunk in idx.split(16):
67
+ logits = F.linear(feats.hidden[chunk - 1], vocab)
68
+ losses.append(F.cross_entropy(logits, tokens[chunk], reduction="none"))
69
+ surprisal = dict(zip(flat, torch.cat(losses).tolist(), strict=True))
70
+ # Undo the documented encoding of the across-head mean attention.
71
+ rel = feats.relations[..., 0]
72
+ attn = (rel + math.log(2.)).expm1() / torch.arange(1, len(rel) + 1, device=rel.device)[:, None]
73
+ prior_attn = attn[:, ctx_tokens].sum(dim=1).tolist()
74
+ # Pool normalized contextual representations of content-bearing subwords.
75
+ layers = [F.normalize(x.float(), dim=-1) for x in (feats.mid, feats.hidden)]
76
+ ctx_vectors = [x[sorted(indices)].mean(0) for x in layers]
77
+ seen_content = set()
78
+ attended = 0.
79
+ cum_scores = 0.
80
+ trans_sum = 0.
81
+ total_tokens = 0
82
+ seen_indices = []
83
+ features = []
84
+ for k, (word, selected) in enumerate(zip(words, target_tokens, strict=True), start=1):
85
+ if not selected:
86
+ raise ValueError("Target word has no corresponding source tokens")
87
+ cum_scores += sum(surprisal[i] for i in selected)
88
+ attended += sum(prior_attn[i] for i in selected)
89
+ trans_sum += sum(trace[i]["transition"] for i in selected)
90
+ total_tokens += len(selected)
91
+ if word and word not in STOP:
92
+ seen_content.add(word)
93
+ seen_indices.extend(i for i in selected if any(c.isalnum() for c in text[slice(*feats.offsets[i])]))
94
+ cosine = ([float(F.cosine_similarity(p, x[seen_indices].mean(0), dim=0))
95
+ for p, x in zip(ctx_vectors, layers, strict=True)] if seen_indices else [0., 0.])
96
+ features.append([math.log1p(len(context)), math.log1p(k),
97
+ len(ctx_content & seen_content) / max(1, len(seen_content)),
98
+ contiguous_overlap(ctx_words, words[:k]), trans_sum / total_tokens,
99
+ cum_scores / k, attended / total_tokens, *cosine])
100
+ if not all(math.isfinite(v) for word in features for v in word):
101
+ raise ValueError("Nonfinite feature")
102
+ return {"id": row["id"], "words": features}
103
+
104
+
105
+ @torch.inference_mode()
106
+ def run(runtime, reader, checkpoint, input_path, output_dir):
107
+ path = Path(input_path)
108
+ raw = path.read_bytes()
109
+ rows = [json.loads(line) for line in raw.splitlines()]
110
+ output = Path(output_dir)
111
+ output.mkdir(parents=True, exist_ok=True)
112
+ count = [0]
113
+ def count_call(_module, _inputs):
114
+ count[0] += 1
115
+ with runtime.encoder.register_forward_pre_hook(count_call):
116
+ with (output / "features.jsonl").open("w") as out:
117
+ for n, row in enumerate(rows, 1):
118
+ values = features_for_text(runtime, reader, checkpoint, row)
119
+ if count[0] != n:
120
+ raise RuntimeError("Each text requires exactly one encoder pass")
121
+ out.write(json.dumps(values, allow_nan=False) + "\n")
122
+ if n % 32 == 0:
123
+ out.flush()
124
+ print(f"Carter–Hoffman forecasts {n}/{len(rows)}", flush=True)
125
+ (output / "receipt.json").write_text(json.dumps({"backbone": runtime.candidate,
126
+ "revision": runtime.revision, "input_sha256": hashlib.sha256(raw).hexdigest(),
127
+ "features": FEATURES, "forward_calls": count[0], "input_rows": len(rows),
128
+ "output_sha256": hashlib.sha256((output / "features.jsonl").read_bytes()).hexdigest()
129
+ }, indent=2))
research/reading_validation/local_features.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grade-free span features shared by the difficulty and comprehension assays."""
2
+
3
+ from collections import Counter, defaultdict
4
+ from dataclasses import dataclass
5
+ import csv
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+ from research.reading_validation.local_forecast import (
12
+ CACHE,
13
+ CHANNELS,
14
+ CHECKPOINT,
15
+ RESULTS,
16
+ WORD,
17
+ digest,
18
+ rows,
19
+ )
20
+
21
+
22
+ PACKET = CACHE / "expository-lora/prepared"
23
+ DATA = CACHE / "reading-validation"
24
+ OUT = RESULTS / "reading-validation-local"
25
+ SPAN_WIDTH = 8
26
+ BLOCKS = ("surface", "medical", "lexical", "representation", "shared", "persistent")
27
+
28
+
29
+ def verified_rows(dataset, name):
30
+ path = PACKET / dataset / name
31
+ audit = json.loads((PACKET / "source-audit.json").read_bytes())
32
+ if digest(path) != audit["files_sha256"][f"{dataset}/{name}"]:
33
+ raise ValueError(f"Observation geometry changed: {path}")
34
+ return rows(path)
35
+
36
+
37
+ def row_grams(words):
38
+ return set(zip(*(words[k:] for k in range(5))))
39
+
40
+
41
+ def medical_counts(raw, exclude):
42
+ """Count training words and term spans at their original source coordinates."""
43
+ from research.stage6.medreadme_span_audit import FILES, compact, source_spans
44
+
45
+ for name, expected in FILES.items():
46
+ if digest(raw / name) != expected:
47
+ raise ValueError(f"MedReadMe source checksum mismatch for {name}")
48
+ fit_texts = defaultdict(list)
49
+ with (raw / "readability.csv").open(newline="") as stream:
50
+ for item in csv.DictReader(stream):
51
+ if item["split"] == "train":
52
+ fit_texts[item["Source"], item["Side"], compact(item["Sentence"])].append(item["Sentence"])
53
+ document_counts, terms, starts, ends, mentions, term_counts = [Counter() for _ in range(6)]
54
+ labels = [r for r in json.loads((raw / "jargon.json").read_bytes()) if r["split"] == "train"]
55
+ keys = [(*r["belongings"], compact("".join(r["tokens"]))) for r in labels]
56
+ counts = Counter(keys)
57
+ coverage = Counter()
58
+ for key, r in zip(keys, labels, strict=True):
59
+ if len(fit_texts[key]) != 1 or counts[key] != 1:
60
+ coverage["ambiguous_or_unaligned"] += 1
61
+ continue
62
+ (text,) = fit_texts[key]
63
+ matches = list(WORD.finditer(text))
64
+ words = tuple(m.group().casefold() for m in matches)
65
+ if exclude(words):
66
+ coverage["overlap_with_target_material"] += 1
67
+ continue
68
+ coverage["used_sentences"] += 1
69
+ document_counts.update(words)
70
+ for j in range(len(words)):
71
+ term_counts.update(tuple(words[j:e]) for e in range(j + 1, min(j + SPAN_WIDTH, len(words)) + 1))
72
+ selected = set()
73
+ for lo, hi, _ in source_spans(text, r["tokens"], r["entities"]):
74
+ span = [i for i, m in enumerate(matches) if lo <= m.start() and m.end() <= hi]
75
+ if not span or (matches[span[0]].start(), matches[span[-1]].end()) != (lo, hi):
76
+ continue
77
+ selected.update(span)
78
+ phrase = tuple(words[span[0] : span[-1] + 1])
79
+ if len(phrase) <= SPAN_WIDTH:
80
+ terms[phrase] += 1
81
+ starts[words[span[0]]] += 1
82
+ ends[words[span[-1]]] += 1
83
+ mentions.update(words[j] for j in selected)
84
+ return (document_counts, terms, starts, ends, mentions, term_counts), coverage
85
+
86
+
87
+ def source_lexicon():
88
+ target_grams = defaultdict(set)
89
+ target_forms = set()
90
+ for item in rows(DATA / "local-stimuli.jsonl"):
91
+ words = tuple(match.group().casefold() for match in WORD.finditer(item["text"]))
92
+ for gram in row_grams(words):
93
+ target_grams[gram].add(item["id"])
94
+ target_forms.add(words)
95
+
96
+ def overlaps(words):
97
+ grams = row_grams(words)
98
+ matches = Counter(key for gram in grams for key in target_grams.get(gram, ()))
99
+ return words in target_forms or (bool(matches) and max(matches.values()) * 4 >= len(grams))
100
+
101
+ medical, coverage = medical_counts(CACHE / "medreadme-audit/raw", overlaps)
102
+ complex_path = CACHE / "stage5/complex-l4-input/stimuli.jsonl"
103
+ fit_sentences = {
104
+ tuple(m.group().casefold() for m in WORD.finditer(r["text"]))
105
+ for r in rows(complex_path)
106
+ if r["split"] in ("train", "trial")
107
+ }
108
+ overlap_count = sum(overlaps(words) for words in fit_sentences)
109
+ frequencies = Counter(w for words in fit_sentences if not overlaps(words) for w in words)
110
+ receipt = dict(
111
+ medreadme_training=dict(coverage),
112
+ complex_unique_sentences=len(fit_sentences),
113
+ overlapping_complex_sentences=overlap_count,
114
+ lexical_checkpoint_overlap_qualification="The immutable CompLex head used its published original fit.",
115
+ )
116
+ return Lexicon(frequencies, *medical), receipt
117
+
118
+
119
+ @dataclass
120
+ class Lexicon:
121
+ frequencies: Counter
122
+ counts: Counter
123
+ terms: Counter
124
+ begins: Counter
125
+ finishes: Counter
126
+ mentions: Counter
127
+ term_counts: Counter
128
+
129
+ def records(self):
130
+ return dict(
131
+ frequencies=self.frequencies,
132
+ counts=self.counts,
133
+ begins=self.begins,
134
+ finishes=self.finishes,
135
+ mentions=self.mentions,
136
+ phrases=[(k, self.terms[k], self.term_counts[k]) for k in sorted(self.terms)],
137
+ )
138
+
139
+ def word_scores(self, words):
140
+ columns = []
141
+ for count in (self.mentions, self.begins, self.finishes):
142
+ prior = count.total() / self.counts.total()
143
+ columns.append([(count[w] + 5 * prior) / (self.counts[w] + 5) for w in words])
144
+ return np.column_stack(columns)
145
+
146
+
147
+ def read_gpu(directory, inputs=None, source_seal=None):
148
+ if directory is None:
149
+ return {}
150
+ seal = json.loads((directory / "seal.json").read_bytes())
151
+ expected = json.loads((source_seal or (OUT / "input-seal.json")).read_bytes())
152
+ docs = rows(inputs or (DATA / "local-stimuli.jsonl"))
153
+ runtime = json.loads((directory.parent / "causality.json").read_bytes())
154
+ if runtime.get("checkpoint", runtime.get("checkpoint_sha256")) != CHECKPOINT:
155
+ raise ValueError("GPU extraction used another selected checkpoint")
156
+ if (
157
+ seal["passes"] != len(docs)
158
+ or seal["channels"] != list(CHANNELS)
159
+ or seal["stimuli_sha256"] != expected["stimuli_sha256"]
160
+ or seal["lexical_sha256"] != expected["lexical_sha256"]
161
+ or seal["code_sha256"] != digest(Path(__file__).with_name("local_forecast.py"))
162
+ ):
163
+ raise ValueError("GPU extract disagrees with the sealed inputs")
164
+ out = {}
165
+ for row, info in zip(docs, seal["documents"], strict=True):
166
+ file = directory / info["file"]
167
+ if row["id"] != info["id"] or info["sha256"] != digest(file) or info["id"] in out:
168
+ raise ValueError("GPU extract content mismatch")
169
+ with np.load(file, allow_pickle=False) as arrays:
170
+ item = {name: arrays[name] for name in arrays.files}
171
+ words = np.array([m.span() for m in WORD.finditer(row["text"])], dtype=int)
172
+ if (
173
+ not np.array_equal(item["words"][:, :2], words)
174
+ or len(item["offsets"]) != info["tokens"]
175
+ or any(not np.isfinite(a).all() for a in item.values())
176
+ ):
177
+ raise ValueError("Invalid word alignment or feature")
178
+ out[info["id"]] = item
179
+ return out
180
+
181
+
182
+ def normalize_means(x, lo, hi):
183
+ accum = np.concatenate((np.zeros_like(x[:1]), x.cumsum(axis=0)))
184
+ return (accum[hi + 1] - accum[lo]) / (hi - lo + 1)[:, None]
185
+
186
+
187
+ def disjoint_ranking(coords, scores, limit=None):
188
+ selected = []
189
+ for index in np.argsort(-scores, kind="stable"):
190
+ a, b = coords[index]
191
+ if any(a < coords[j, 1] and coords[j, 0] < b for j in selected):
192
+ continue
193
+ selected.append(int(index))
194
+ if limit is not None and len(selected) >= limit:
195
+ break
196
+ return np.asarray(selected, dtype=int)
197
+
198
+
199
+ @dataclass
200
+ class Sentence:
201
+ key: str
202
+ document: str
203
+ coords: np.ndarray
204
+ features: dict
205
+ raw: dict
206
+ sentence: dict
207
+
208
+
209
+ def sentence_features(
210
+ key, document, text, start, end, lex, gpu, sentence_index, version, *, sentence_endpoint=True
211
+ ):
212
+ all_words = list(WORD.finditer(text))
213
+ indices = np.array(
214
+ [i for i, w in enumerate(all_words) if w.start() >= start and w.end() <= end], dtype=int
215
+ )
216
+ if not len(indices):
217
+ raise ValueError(f"No complete words at {key}")
218
+ tokens = [all_words[i] for i in indices]
219
+ words = [w.group().casefold() for w in tokens]
220
+ spans = np.array([w.span() for w in tokens])
221
+ sizes = spans[:, 1] - spans[:, 0]
222
+ frequency = np.array([np.log1p(lex.frequencies[word]) for word in words])
223
+ medical = lex.word_scores(words)
224
+ pos = np.arange(len(tokens))
225
+ lo = np.repeat(pos, np.minimum(len(pos) - pos, SPAN_WIDTH))
226
+ hi = np.concatenate([np.arange(j, min(j + SPAN_WIDTH, len(pos))) for j in pos])
227
+ widths = hi - lo + 1
228
+ coords = np.column_stack((spans[lo, 0], spans[hi, 1]))
229
+ avg = lambda x: normalize_means(np.atleast_2d(x).T, lo, hi).ravel()
230
+ form = np.column_stack(
231
+ (
232
+ np.log1p(widths),
233
+ np.log1p(coords[:, 1] - coords[:, 0]),
234
+ np.log1p(lo),
235
+ np.log1p(indices[lo]),
236
+ avg(sizes),
237
+ avg(frequency),
238
+ sizes[lo],
239
+ sizes[hi],
240
+ frequency[lo],
241
+ frequency[hi],
242
+ avg([w.group()[0].isupper() for w in tokens]),
243
+ avg([w.group().isupper() for w in tokens]),
244
+ avg([any(c.isdigit() for c in w.group()) for w in tokens]),
245
+ )
246
+ )
247
+ phrases = [tuple(words[a : b + 1]) for a, b in zip(lo, hi, strict=True)]
248
+ external = np.column_stack(
249
+ (
250
+ normalize_means(medical, lo, hi),
251
+ medical[lo, 1],
252
+ medical[hi, 2],
253
+ [np.log1p(lex.terms[p]) for p in phrases],
254
+ [lex.terms[p] / (lex.term_counts[p] + 4) for p in phrases],
255
+ )
256
+ )
257
+ sf = {
258
+ "surface": np.array(
259
+ [
260
+ np.log1p(len(text[start:end])),
261
+ np.log1p(len(words)),
262
+ np.log1p(sentence_index),
263
+ version,
264
+ sizes.mean(),
265
+ frequency.mean(),
266
+ np.quantile(frequency, 0.10),
267
+ ]
268
+ ),
269
+ "medical": np.r_[medical.mean(axis=0), np.quantile(medical[:, 0], 0.90)],
270
+ }
271
+ blocks, raw = dict(surface=form, medical=external), {}
272
+ if gpu is not None:
273
+ native = gpu["words"][indices, 2]
274
+ # Only explicitly certified tokens contribute to a readout. Include coverage as a feature.
275
+ valid = native >= 0
276
+ score = np.zeros(len(words))
277
+ score[valid] = gpu["lexical"][native[valid]]
278
+ blocks["lexical"] = np.column_stack((avg(score), score[lo], score[hi], avg(valid)))
279
+ if sentence_endpoint:
280
+ if not valid.any():
281
+ raise ValueError(f"No certified word for the sentence rating in {key}")
282
+ sf["lexical"] = np.array((score[valid].mean(), np.quantile(score[valid], 0.90), valid.mean()))
283
+ raw["external_lexical"] = avg(score)
284
+ for label, array in [("representation", "projection"), ("shared", "shared")]:
285
+ if array not in gpu:
286
+ continue
287
+ present = np.zeros((len(words), gpu[array].shape[1]))
288
+ present[valid] = gpu[array][native[valid]]
289
+ blocks[label] = normalize_means(present, lo, hi)
290
+ if sentence_endpoint:
291
+ last = np.flatnonzero(gpu["offsets"][:, 1] == end)
292
+ if not len(last):
293
+ raise ValueError(f"Sentence endpoint lacks a certified token in {key}")
294
+ sf[label] = gpu[array][last[-1]].astype(float)
295
+ if "trace" in gpu:
296
+ native_lo = np.searchsorted(gpu["offsets"][:, 1], spans[:, 0], side="right")
297
+ native_hi = np.searchsorted(gpu["offsets"][:, 0], spans[:, 1], side="left")
298
+ if (native_lo >= native_hi).any():
299
+ raise ValueError("Word has no overlapping original token")
300
+ trace = gpu["trace"]
301
+ change = np.diff(trace[:, 0], prepend=0)
302
+ word_trace = np.array(
303
+ [np.r_[trace[b - 1], change[a:b].max()] for a, b in zip(native_lo, native_hi, strict=True)]
304
+ )
305
+ blocks["persistent"] = np.column_stack((normalize_means(word_trace, lo, hi), word_trace[hi]))
306
+ raw.update(displayed_mass=avg(word_trace[:, 0]), displayed_increase=avg(word_trace[:, -1]))
307
+ sf["persistent"] = np.r_[word_trace.mean(axis=0), word_trace[-1], word_trace.max(axis=0)]
308
+ if any(not np.isfinite(x).all() for x in (*blocks.values(), *sf.values())):
309
+ raise ValueError(f"Nonfinite features for {key}")
310
+ return Sentence(key, document, coords, blocks, raw, sf)
311
+
312
+
313
+ def build(gpu_path=None):
314
+ lex, receipt = source_lexicon()
315
+ gpu = read_gpu(gpu_path)
316
+ if gpu:
317
+ receipt["word_end_coverage"] = {
318
+ study: dict(
319
+ total=sum(len(r["words"]) for k, r in gpu.items() if k.startswith(study + "/")),
320
+ certified=sum(
321
+ int((r["words"][:, 2] >= 0).sum()) for k, r in gpu.items() if k.startswith(study + "/")
322
+ ),
323
+ )
324
+ for study in ("plaba", "kerwer")
325
+ }
326
+ text = {r["id"]: r["text"] for r in rows(DATA / "local-stimuli.jsonl")}
327
+ out = {}
328
+ for row in verified_rows("plaba", "ratings.jsonl"):
329
+ case = "plaba/" + row["id"]
330
+ mat = text[case]
331
+ for i, node in enumerate(row["ratings"]):
332
+ key = node["anchor_id"]
333
+ out[key] = sentence_features(
334
+ key,
335
+ case,
336
+ mat,
337
+ node["start"],
338
+ node["stop"],
339
+ lex,
340
+ gpu.get(case),
341
+ i,
342
+ float(row["id"].endswith("_simp")),
343
+ )
344
+ # Kerwer matching uses body-text sentences with verbatim counterparts, preserving intervening headings.
345
+ layouts = verified_rows("kerwer", "layout.jsonl")
346
+ source_design = json.loads((RESULTS / "kerwer-transfer-protocol.json").read_bytes())["alignment"][
347
+ "eligible"
348
+ ]["headings"]
349
+ for row in layouts:
350
+ case = "kerwer/" + row["id"]
351
+ mat = text[case]
352
+ source = source_design[row["id"]]
353
+ if [b for a, b in source] != row["matched_stops"]:
354
+ raise ValueError("Kerwer matched sentence coordinates changed")
355
+ for i, (start, stop) in enumerate(source):
356
+ key = case + "@" + str(stop)
357
+ out[key] = sentence_features(key, case, mat, start, stop, lex, gpu.get(case), i, 1.0)
358
+ return out, receipt
research/reading_validation/local_forecast.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prepare outcome-free abstracts and extract local and persistent scores in one pass."""
2
+
3
+ from dataclasses import replace
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+ import re
8
+
9
+ import numpy as np
10
+
11
+
12
+ ROOT = Path(__file__).resolve().parents[2]
13
+ CACHE = ROOT / '.cache/cogllm'
14
+ RESULTS = ROOT / 'research/results'
15
+ CHECKPOINT = 'c1704d4436d767fa43bdb59e9216698514e1f6bd1d45cad4b60d0f018d84abb5'
16
+ WORD = re.compile(r"[^\W_]+(?:[’'\-][^\W_]+)*")
17
+ CHANNELS = ('unresolved', 'opened', 'resolved', 'transition')
18
+
19
+
20
+ def digest(path):
21
+ with path.open('rb') as stream:
22
+ return hashlib.file_digest(stream, 'sha256').hexdigest()
23
+
24
+
25
+ def rows(path):
26
+ with path.open() as stream:
27
+ return [json.loads(line) for line in stream if line.strip()]
28
+
29
+
30
+ def prepare():
31
+ output = CACHE / 'reading-validation'
32
+ output.mkdir(exist_ok=True)
33
+ packet = CACHE / 'expository-lora/prepared'
34
+ sources = {}
35
+ assays = json.loads((packet / 'source-audit.json').read_text())
36
+ with (output / 'local-stimuli.jsonl').open('w') as stream:
37
+ for study in ('plaba', 'kerwer'):
38
+ relative = f'{study}/stimuli.jsonl'
39
+ sources[relative] = digest(packet / relative)
40
+ if sources[relative] != assays['files_sha256'][relative]:
41
+ raise ValueError('Stimulus content differs from the sealed source')
42
+ for row in rows(packet / relative):
43
+ stimulus = {'id': f"{study}/{row['id']}", 'text': row['text']}
44
+ stream.write(json.dumps(stimulus, ensure_ascii=False) + '\n')
45
+ head = RESULTS / 'gradio-candidate-checkpoint/lexical/heads.npz'
46
+ manifest = json.loads((head.parent / 'fitting.json').read_text())
47
+ if digest(head) != manifest['artifacts']['heads.npz']['sha256']:
48
+ raise ValueError('CompLex lexical-head checksum mismatch')
49
+ with np.load(head, allow_pickle=False) as fits:
50
+ method = fits['methods'].tolist().index('target_end')
51
+ fraction = fits['fractions'].tolist().index(100)
52
+ weight, bias = fits['weights_target_end'][fraction], fits['intercepts'][method, fraction]
53
+ if not (np.all(weight == weight[0]) and np.all(bias == bias[0])):
54
+ raise ValueError('Full-training lexical heads disagree')
55
+ np.savez(output / 'local-lexical.npz', w=weight[0].astype('float64'), b=bias[0])
56
+ seal = dict(stimuli_sha256=digest(output / 'local-stimuli.jsonl'),
57
+ lexical_sha256=digest(output / 'local-lexical.npz'),
58
+ original_lexical_sha256=digest(head), checkpoint_sha256=CHECKPOINT,
59
+ protocol_sha256=digest(Path(__file__).with_name('local-protocol.md')), sources=sources)
60
+ print(json.dumps(seal, indent=2))
61
+ return seal
62
+
63
+
64
+ def run(runtime, reader, checkpoint, input_path, output_dir):
65
+ import torch
66
+ from research.stage5.complex_tokenization import token_span
67
+ from research.token_readout.runner import trace_rows
68
+
69
+ inputs, destination = Path(input_path), Path(output_dir)
70
+ destination.mkdir(exist_ok=True, parents=True)
71
+ if checkpoint['candidate'] != 'qwen' or runtime.revision != checkpoint['revision']:
72
+ raise ValueError('Expected the pinned Qwen text backbone')
73
+ native = reader.state_dict()
74
+ if set(checkpoint['reader']) != set(native) or any(
75
+ not torch.equal(native[k].cpu(), v.cpu()) for k, v in checkpoint['reader'].items()
76
+ ):
77
+ raise ValueError('Reader differs from its loaded checkpoint')
78
+ lexical_file = inputs.with_name('local-lexical.npz')
79
+ with np.load(lexical_file, allow_pickle=False) as lexical:
80
+ w = torch.as_tensor(lexical['w'], device=runtime.device, dtype=torch.float64)
81
+ b = float(lexical['b'])
82
+ if w.shape != (2048,) or not torch.isfinite(w).all():
83
+ raise ValueError('Malformed lexical readout')
84
+ # A data-independent projection supplies a clean comparison to the trained readout projection.
85
+ generator = np.random.default_rng(78491)
86
+ reduced, _ = np.linalg.qr(generator.standard_normal((2048, 32)))
87
+ projection = torch.from_numpy(reduced.astype(np.float32)).to(runtime.device)
88
+ scale = checkpoint['scale']
89
+ summary, files, seen = [], [], set()
90
+ def count_call(_module, _args):
91
+ files.append(1)
92
+ with runtime.encoder.register_forward_pre_hook(count_call), torch.no_grad():
93
+ for row in rows(inputs):
94
+ key, text = row['id'], row['text']
95
+ if key in seen or set(row) != {'id', 'text'}:
96
+ raise ValueError('Expected distinct grade-free documents')
97
+ seen.add(key)
98
+ before = len(files)
99
+ ft = runtime.encode(text)
100
+ if len(files) != before + 1:
101
+ raise ValueError('Expected one backbone pass per document')
102
+ final, middle = reader.project(ft)
103
+ scores = reader.score_projected(final, middle, ft.relations)
104
+ scores = replace(scores, opening=scores.opening * scale['opening_gain'],
105
+ resolution=scores.resolution * scale['resolution_gain'] + scale['resolution_bias'])
106
+ trace = trace_rows(text, ft.offsets, scores, checkpoint['priors'], reader.anchor_tokens)
107
+ word_index = []
108
+ for word in WORD.finditer(text):
109
+ _, interval = token_span(text, ft.offsets, *word.span())
110
+ if interval is not None:
111
+ end = interval[1]
112
+ prefix = runtime.tokenizer.encode(text[:word.end()], add_special_tokens=False).ids
113
+ if tuple(prefix) == ft.token_ids[:end + 1]:
114
+ word_index.append((*word.span(), end))
115
+ continue
116
+ word_index.append((*word.span(), -1))
117
+ hidden = torch.nn.functional.normalize(ft.hidden.double(), dim=1)
118
+ with (destination / f'{before:03d}.npz').open('wb') as stream:
119
+ np.savez_compressed(stream,
120
+ offsets=np.asarray(ft.offsets, dtype=np.int32),
121
+ words=np.asarray(word_index, dtype=np.int32),
122
+ trace=np.array([[t[c] for c in CHANNELS] for t in trace], dtype=np.float32),
123
+ lexical=(hidden @ w + b).clamp(0, 1).float().cpu().numpy(),
124
+ projection=(hidden.float() @ projection).cpu().numpy(),
125
+ shared=final.cpu().numpy(),
126
+ )
127
+ file = destination / f'{before:03d}.npz'
128
+ summary.append(dict(id=key, file=file.name, sha256=digest(file),
129
+ text_sha256=hashlib.sha256(text.encode()).hexdigest(), tokens=len(ft.token_ids)))
130
+ seal = dict(revision=runtime.revision, passes=len(files), documents=summary, channels=CHANNELS,
131
+ stimuli_sha256=digest(inputs), lexical_sha256=digest(lexical_file),
132
+ projection_seed=78491, code_sha256=digest(Path(__file__)))
133
+ (destination / 'seal.json').write_text(json.dumps(seal, indent=2) + '\n')
134
+
135
+
136
+ if __name__ == '__main__':
137
+ prepare()
research/reading_validation/local_inference.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local reading difficulty on a single already-computed Qwen feature sequence."""
2
+
3
+ from collections import Counter
4
+ from dataclasses import dataclass
5
+ import gzip
6
+ from hashlib import sha256
7
+ import json
8
+ from pathlib import Path
9
+ import re
10
+
11
+ import numpy as np
12
+
13
+ from research.reading_validation.local_features import Lexicon, disjoint_ranking, sentence_features
14
+ from research.reading_validation.local_forecast import WORD, digest
15
+ from research.stage5.complex_tokenization import token_span
16
+
17
+
18
+ DEFAULT = Path(__file__).resolve().parents[1] / "results/reading-validation-local/serving"
19
+ BOUNDARY = re.compile(r'(?<=[.!?])(?=\s+[A-Z0-9“"(])|(?<=\n)(?=\s*\S)')
20
+ REVISION = "15852e8c16360a2fea060d615a32b45270f8a8fc"
21
+ SCHEMA = "cogllm-local-reading-en-v1"
22
+ LEXICON_DIGEST = "9184bd90fefd7f01b5cc9108019bfe5dae7685575d375c25db444121de0a741c"
23
+
24
+
25
+ def english_sentences(text):
26
+ stops = [0] + [m.start() for m in BOUNDARY.finditer(text)] + [len(text)]
27
+ spans = []
28
+ for a, b in zip(stops, stops[1:]):
29
+ segment = text[a:b]
30
+ left = a + len(segment) - len(segment.lstrip())
31
+ right = a + len(segment.rstrip())
32
+ if left < right and WORD.search(text, left, right):
33
+ spans.append((left, right))
34
+ return spans
35
+
36
+
37
+ def _matrix_blocks(parts, centers, scales, values):
38
+ return np.column_stack([(values[k] - centers[k]) / scales[k] for k in parts])
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class LocalInference:
43
+ lexicon: Lexicon
44
+ rank: dict
45
+ rating: dict
46
+ lexical_weight: np.ndarray
47
+ lexical_bias: float
48
+ projection: np.ndarray
49
+ bundle_sha256: str
50
+
51
+ @classmethod
52
+ def load(cls, directory=DEFAULT):
53
+ directory = Path(directory)
54
+ packed = directory / "lexicon.json.gz"
55
+ supplied = json.loads((directory / "manifest.json").read_bytes())["files_sha256"]["lexicon.json.gz"]
56
+ if digest(packed) != supplied:
57
+ raise ValueError("Local reading lexicon differs from its manifest")
58
+ return cls.from_lexicon(directory, gzip.decompress(packed.read_bytes()))
59
+
60
+ @classmethod
61
+ def from_lexicon(cls, directory, lexical_bytes):
62
+ """Load the same sealed reading model from the uncompressed lexical parameters."""
63
+ directory = Path(directory)
64
+ manifest_path = directory / "manifest.json"
65
+ manifest = json.loads(manifest_path.read_bytes())
66
+ if (
67
+ manifest["schema"] != SCHEMA
68
+ or manifest["revision"] != REVISION
69
+ or set(manifest["files_sha256"]) != {"lexicon.json.gz", "weights.npz"}
70
+ ):
71
+ raise ValueError("Unrecognized English local-reading checkpoint")
72
+ if digest(directory / "weights.npz") != manifest["files_sha256"]["weights.npz"]:
73
+ raise ValueError("Local reading weights differ from their manifest")
74
+ if sha256(lexical_bytes).hexdigest() != LEXICON_DIGEST:
75
+ raise ValueError("Incorrect lexical counts for this reading model")
76
+ lex = json.loads(lexical_bytes)
77
+ dictionaries = {k: Counter(v) for k, v in lex.items() if k != "phrases"}
78
+ dictionaries["terms"] = Counter({tuple(words): n for words, n, count in lex["phrases"]})
79
+ dictionaries["term_counts"] = Counter({tuple(words): count for words, n, count in lex["phrases"]})
80
+ with np.load(directory / "weights.npz", allow_pickle=False) as arrays:
81
+ rank = dict(parts=manifest["rank_features"], coef=arrays["rank_coef"])
82
+ rating = dict(
83
+ parts=manifest["rating_features"],
84
+ coef=arrays["rating_coef"],
85
+ offset=arrays["rating_offset"],
86
+ )
87
+ for model, prefix in ((rank, "rank"), (rating, "rating")):
88
+ model["center"] = {name: arrays[f"{prefix}_mean_{name}"] for name in model["parts"]}
89
+ model["scale"] = {name: arrays[f"{prefix}_scale_{name}"] for name in model["parts"]}
90
+ w, b, proj = arrays["lexical_weight"], float(arrays["lexical_bias"]), arrays["projection"]
91
+ if (
92
+ w.shape != (2048,)
93
+ or proj.shape != (2048, 32)
94
+ or len(rank["coef"]) != 56
95
+ or rating["coef"].shape != (2061, 2)
96
+ or rating["offset"].shape != (2, 5)
97
+ ):
98
+ raise ValueError("Unexpected source projection or local reading head dimension")
99
+ return cls(Lexicon(**dictionaries), rank, rating, w, b, proj, digest(manifest_path))
100
+
101
+ def _infer_arrays(self, text, arrays, normalized_at, spans):
102
+ output = []
103
+ for i, (start, end) in enumerate(spans):
104
+ if not (0 <= start < end <= len(text)) or (i and start < spans[i - 1][1]):
105
+ raise ValueError("Sentence intervals must be ordered spans in the original text")
106
+ if not WORD.search(text, start, end):
107
+ continue
108
+ word_table = arrays["words"]
109
+ words = (word_table[:, 0] >= start) & (word_table[:, 1] <= end)
110
+ valid = int(np.count_nonzero(word_table[words, 2] >= 0))
111
+ can_rate = valid > 0 and end in normalized_at
112
+ node = sentence_features(
113
+ str(end),
114
+ "article",
115
+ text,
116
+ start,
117
+ end,
118
+ self.lexicon,
119
+ arrays,
120
+ i,
121
+ 0.0,
122
+ sentence_endpoint=can_rate,
123
+ )
124
+ rank = (
125
+ _matrix_blocks(self.rank["parts"], self.rank["center"], self.rank["scale"], node.features)
126
+ @ self.rank["coef"]
127
+ )
128
+ proposals = []
129
+ for j in disjoint_ranking(node.coords, rank, 5):
130
+ a, b = node.coords[j]
131
+ proposals.append(
132
+ dict(start=int(a), end=int(b), rank=len(proposals) + 1, score=float(rank[j]))
133
+ )
134
+ rating = None
135
+ if can_rate:
136
+ values = dict(node.sentence)
137
+ values["surface"] = values["surface"][[0, 1, 2, 4, 5, 6]]
138
+ values["sentence_state"] = normalized_at[end]
139
+ x = np.concatenate(
140
+ [
141
+ (values[k] - self.rating["center"][k]) / self.rating["scale"][k]
142
+ for k in self.rating["parts"]
143
+ ]
144
+ )
145
+ z = (x @ self.rating["coef"])[:, None] * (np.arange(1, 6) - 3) + self.rating["offset"]
146
+ p = np.exp(z - z.max(axis=1, keepdims=True))
147
+ p /= p.sum(axis=1, keepdims=True)
148
+ rating = {k: float(p[j] @ np.arange(1, 6)) for j, k in enumerate(("ease", "understanding"))}
149
+ output.append(
150
+ dict(
151
+ start=int(start),
152
+ end=int(end),
153
+ phrases=proposals,
154
+ rating=rating,
155
+ words=int(words.sum()),
156
+ certified_words=valid,
157
+ )
158
+ )
159
+ return dict(schema=SCHEMA, language="en", bundle_sha256=self.bundle_sha256, sentences=output)
160
+
161
+ def score(self, text, features, tokenizer, reader, *, sentence_spans=None):
162
+ """Return source-offset phrases and 1–5 sentence ratings from provided native features.
163
+
164
+ The caller chooses the English endpoint. Custom sentence bounds are Unicode half-open
165
+ intervals. Ranking logits are conditional on the supplied sentence. A missing
166
+ certified sentence stop has a null rating and preserves the available phrase ranks.
167
+ """
168
+ if reader.input_width != 2048 or features.hidden.shape != (len(features.offsets), 2048):
169
+ raise ValueError("Local readout requires one native Qwen3.5-2B feature sequence")
170
+ if not text.strip():
171
+ raise ValueError("Expected the original article text")
172
+ encoded = tokenizer.encode(text, add_special_tokens=False)
173
+ if tuple(encoded.ids) != tuple(features.token_ids) or tuple(map(tuple, encoded.offsets)) != tuple(
174
+ features.offsets
175
+ ):
176
+ raise ValueError("The provided features refer to a different article or tokenizer")
177
+ spans = list(sentence_spans) if sentence_spans is not None else english_sentences(text)
178
+ words = []
179
+ for m in WORD.finditer(text):
180
+ _, hit = token_span(text, features.offsets, *m.span())
181
+ index = -1
182
+ if hit is not None:
183
+ prefix = tokenizer.encode(text[: m.end()], add_special_tokens=False).ids
184
+ if tuple(prefix) == tuple(features.token_ids[: hit[1] + 1]):
185
+ index = hit[1]
186
+ words.append((*m.span(), index))
187
+ offsets = np.asarray(features.offsets, dtype=int)
188
+ # Project token features in blocks to limit temporary memory on the host.
189
+ n = len(offsets)
190
+ lexical = np.empty(n, dtype=np.float32)
191
+ projected = np.empty((n, 32), dtype=np.float32)
192
+ normalized_at = {}
193
+ certified = {}
194
+ for _, end in spans:
195
+ candidates = np.flatnonzero(offsets[:, 1] == end)
196
+ if len(candidates):
197
+ j = int(candidates[-1])
198
+ if tuple(tokenizer.encode(text[:end], add_special_tokens=False).ids) == tuple(
199
+ features.token_ids[: j + 1]
200
+ ):
201
+ certified[j] = end
202
+ for start in range(0, n, 128):
203
+ stop = min(start + 128, n)
204
+ matrix = features.hidden[start:stop].detach().cpu().numpy().astype(np.float64)
205
+ norms = np.linalg.norm(matrix, axis=1, keepdims=True)
206
+ if not np.isfinite(norms).all() or (norms <= 0).any():
207
+ raise ValueError("Invalid native final-layer state")
208
+ matrix /= norms
209
+ lexical[start:stop] = np.clip(matrix @ self.lexical_weight + self.lexical_bias, 0, 1)
210
+ projected[start:stop] = matrix.astype(np.float32) @ self.projection
211
+ for j, end in certified.items():
212
+ if start <= j < stop:
213
+ normalized_at[end] = matrix[j - start].copy()
214
+ arrays = dict(
215
+ words=np.asarray(words, dtype=int).reshape(-1, 3),
216
+ offsets=offsets,
217
+ lexical=lexical,
218
+ projection=projected,
219
+ )
220
+ return self._infer_arrays(text, arrays, normalized_at, spans)
research/reading_validation/transition_external_forecast.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Outcome-blind standard and directed one-pass discourse forecasts on whole articles."""
2
+ from dataclasses import replace
3
+ import hashlib
4
+ import json
5
+ import math
6
+ from pathlib import Path
7
+ import re
8
+
9
+ import numpy as np
10
+ import torch
11
+ from torch.nn import functional as F
12
+
13
+ from research.reading_validation.bridge_forecast import STOP, FEATURES, contiguous_overlap, norm_word
14
+ from research.token_readout.runner import trace_rows
15
+
16
+ PROMPT = ("Assess how each new sentence fits the preceding writing, including the topic or title when present. "
17
+ "Answer Yes if the sentence is understandable and connected, even when it introduces a new idea. "
18
+ "Answer No if the connection is missing, a reference is unclear, or the new claim is inconsistent. "
19
+ "Earlier answers may be blank. Respond with Yes or No only.")
20
+ ASSISTANT = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
21
+
22
+
23
+ def form(row):
24
+ prefix="<|im_start|>system\n"+PROMPT+"<|im_end|>\n"
25
+ pos=0; cuts=[]
26
+ for stop in row["stops"]:
27
+ if not pos <= stop["start"] < stop["end"]:
28
+ raise ValueError("Directed marker order must follow the original text")
29
+ background=row["text"][pos:stop["start"]].strip()
30
+ sentence=row["text"][stop["start"]:stop["end"]].strip()
31
+ msg=(("Previously read:\n"+background+"\n") if background else "")+"New sentence:\n"+sentence
32
+ prefix += "<|im_start|>user\n"+msg+"\nDoes it fit?"+ASSISTANT
33
+ cuts.append((stop["id"],len(prefix)))
34
+ prefix += "<|im_end|>\n"
35
+ pos=stop["end"]
36
+ return prefix,cuts
37
+
38
+
39
+ def directed(runtime,row):
40
+ text,cuts=form(row)
41
+ enc=runtime.tokenizer.encode(text,add_special_tokens=False)
42
+ if len(enc.ids)>2048:
43
+ raise ValueError("Directed document exceeds the verified context limit")
44
+ ends={e:i for i,(_,e) in enumerate(enc.offsets)}
45
+ idx=[ends[c] for _,c in cuts]
46
+ if any(enc.offsets[i][1]!=c or (i+1 < len(enc.ids) and enc.offsets[i+1][0]<c) for i,(_,c) in zip(idx,cuts,strict=True)):
47
+ raise ValueError("Directed word-boundary representation requires an exact completed marker")
48
+ answers=[runtime.tokenizer.encode(a,add_special_tokens=False).ids for a in ("No","Yes")]
49
+ if [len(a) for a in answers]!=[1,1] or answers[0]==answers[1]:
50
+ raise ValueError("Directed forecast requires one distinct token per answer")
51
+ h=runtime.encoder(input_ids=torch.tensor([enc.ids],device=runtime.device),use_cache=False,
52
+ output_attentions=False,output_hidden_states=False).last_hidden_state[0,idx]
53
+ directions=runtime.encoder.embed_tokens.weight[[a[0] for a in answers]]
54
+ logits=F.linear(h,directions)
55
+ return dict(zip((bid for bid,_ in cuts),(logits[:,0]-logits[:,1]).tolist(),strict=True))
56
+
57
+
58
+ def project(runtime,reader,checkpoint,row):
59
+ f=runtime.encode(row["text"])
60
+ final,middle=reader.project(f)
61
+ sc=reader.score_projected(final,middle,f.relations)
62
+ scale=checkpoint["scale"]
63
+ sc=replace(sc,opening=sc.opening*scale["opening_gain"],
64
+ resolution=sc.resolution*scale["resolution_gain"]+scale["resolution_bias"])
65
+ traces=trace_rows(row["text"],f.offsets,sc,checkpoint["priors"],reader.anchor_tokens)
66
+ return pooled_boundary_features(runtime,f,middle,final,traces,row)
67
+
68
+
69
+ def token_surprisals(runtime,features):
70
+ """Apply the tied vocabulary head in bounded blocks to cached causal token states."""
71
+ ids=torch.tensor(features.token_ids[1:],device=runtime.device)
72
+ losses=np.zeros(len(features.token_ids),dtype=np.float64)
73
+ for start in range(0,len(ids),32):
74
+ target=ids[start:start+32]
75
+ logits=F.linear(features.hidden[start:start+len(target)],runtime.encoder.embed_tokens.weight)
76
+ losses[start+1:start+len(target)+1]=F.cross_entropy(logits,target,reduction="none").cpu().numpy()
77
+ return losses
78
+
79
+
80
+ def pooled_boundary_features(runtime,f,middle,final,traces,row,token_surprisal=None):
81
+ """Recover released sentence features from cached encoder output and calibrated token scores."""
82
+ transition=np.asarray([s["transition"] for s in traces])
83
+ offsets=np.asarray(f.offsets)
84
+ real=offsets[:,1]>offsets[:,0]
85
+ tmask=np.array([any(c.isalnum() for c in row["text"][s:e]) for s,e in f.offsets])
86
+ word_ranges=list(re.finditer(r"\S+",row["text"]))
87
+ words=np.array([norm_word(m.group()) for m in word_ranges])
88
+ word_idx=np.full(len(real),-1)
89
+ for i,m in enumerate(word_ranges):
90
+ aligned=(offsets[:,0]<m.end()) & (offsets[:,1]>m.start()) & real
91
+ if np.any(word_idx[aligned]>=0):
92
+ raise ValueError("Token straddles orthographic words")
93
+ word_idx[aligned]=i
94
+ content_words=np.array([w!="" and w not in STOP for w in words])
95
+ content=(word_idx>=0) & content_words[word_idx] & tmask
96
+ wstart=np.array([m.start() for m in word_ranges]); wend=np.array([m.end() for m in word_ranges])
97
+ surprisal=token_surprisals(runtime,f) if token_surprisal is None else token_surprisal
98
+ if np.shape(surprisal)!=(len(f.token_ids),) or not np.isfinite(surprisal).all():
99
+ raise ValueError("Source token surprisal is missing or misaligned")
100
+ n=len(f.offsets); rel=(f.relations[...,0]+math.log(2)).expm1()/torch.arange(1,n+1,device=runtime.device)[:,None]
101
+ rel=rel.cumsum(dim=1).cpu().numpy()
102
+ normalized=[F.normalize(a.float(),dim=-1).cpu().numpy() for a in (f.mid,f.hidden)]
103
+ projected=[x.float().cpu().numpy() for x in (middle,final)]
104
+ def mean(states,mask):
105
+ return states[mask].mean(axis=0) if mask.any() else np.zeros(states.shape[1],dtype=states.dtype)
106
+ rows=[]; raw={}
107
+ for stop in row["stops"]:
108
+ s,e=stop["start"],stop["end"]
109
+ if row["text"][s:e]!=row["text"][s:e].strip():
110
+ raise ValueError("Untrimmed sentence span")
111
+ ctx=(offsets[:,1]<=s) & real
112
+ current=(offsets[:,0]<e)&(offsets[:,1]>s)&real
113
+ if not current.any() or not ctx.any() or (offsets[:,1][current]>e).any() or (ctx&current).any():
114
+ raise ValueError("Unaligned target or preamble")
115
+ lexical=current & (word_idx>=0)
116
+ wc=words[wend<=s].tolist(); wt=words[(wstart<e)&(wend>s)].tolist()
117
+ cs={w for w in wc if w and w not in STOP};ts={w for w in wt if w and w not in STOP}
118
+ cctx=ctx&content; ccur=current&content
119
+ cosine=[]
120
+ for layer in normalized:
121
+ a,b=mean(layer,cctx),mean(layer,ccur)
122
+ denom=np.linalg.norm(a)*np.linalg.norm(b)
123
+ cosine.append(float(np.dot(a,b)/denom) if denom>0 else 0.)
124
+ feats=[math.log1p(len(wc)),math.log1p(len(wt)),len(cs&ts)/max(1,len(ts)),
125
+ contiguous_overlap(wc,wt),float(transition[lexical].mean()),float(surprisal[lexical].sum()/len(wt)),
126
+ float(rel[lexical,np.where(ctx)[0][-1]].mean()),*cosine]
127
+ current_proj=np.concatenate([mean(x,current) for x in projected])
128
+ prev_proj=np.concatenate([mean(x,ctx) for x in projected])
129
+ rep=np.concatenate([current_proj,prev_proj,current_proj*prev_proj])
130
+ rows.append({"id":stop["id"],"features":feats,"representation":rep.tolist(),"position":stop["index"]})
131
+ if stop["archive_final"]:
132
+ raw[stop["id"]]=f.hidden[np.where(current)[0][-1]].cpu().numpy().copy()
133
+ return rows,raw
134
+
135
+
136
+ @torch.inference_mode()
137
+ def run(runtime,reader,checkpoint,input_path,output_dir):
138
+ path=Path(input_path); raw=path.read_bytes()
139
+ data=[json.loads(x) for x in raw.splitlines()]
140
+ out=Path(output_dir);out.mkdir(parents=True,exist_ok=True)
141
+ if runtime.candidate!="qwen" or not runtime.encoder.config.tie_word_embeddings:
142
+ raise ValueError("This study requires the pinned tied Qwen 2B model")
143
+ count=[0]
144
+ def observe(_m,_args):
145
+ count[0]+=1
146
+ raw_vectors={}
147
+ with runtime.encoder.register_forward_pre_hook(observe), (out/"features.jsonl").open("w") as of:
148
+ for i,row in enumerate(data):
149
+ before=count[0]
150
+ rows,raw_row=project(runtime,reader,checkpoint,row)
151
+ if count[0]-before!=1:
152
+ raise RuntimeError("Raw article readout must use one forward")
153
+ dirs=directed(runtime,row)
154
+ if count[0]-before!=2:
155
+ raise RuntimeError("Directed comparator must use one independent forward")
156
+ raw_vectors.update(raw_row)
157
+ for r in rows:
158
+ r["directed"]=dirs[r["id"]]
159
+ of.write(json.dumps(r,allow_nan=False)+"\n")
160
+ if i%32==31:
161
+ of.flush()
162
+ print(f"Coherence articles {i+1}/{len(data)}",flush=True)
163
+ np.savez_compressed(out/"heldout_sentence_states.npz",**raw_vectors)
164
+ files={s.name:hashlib.sha256(s.read_bytes()).hexdigest() for s in out.iterdir() if s.is_file() and s.name!="receipt.json"}
165
+ (out/"receipt.json").write_text(json.dumps({"candidate":runtime.candidate,"revision":runtime.revision,
166
+ "input_sha256":hashlib.sha256(raw).hexdigest(),"documents":len(data),"raw_forward_calls":len(data),
167
+ "directed_forward_calls":len(data),"total_encoder_calls":count[0],"archived_final_states":len(raw_vectors),
168
+ "features":FEATURES,"files":files},indent=2))
research/reading_validation/transition_inference.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """English sentence coherence judgments from an existing, single causal CogLLM pass."""
2
+ from dataclasses import dataclass
3
+ from hashlib import sha256
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+
9
+ CHECKPOINT = 'c1704d4436d767fa43bdb59e9216698514e1f6bd1d45cad4b60d0f018d84abb5'
10
+ REVISION = '15852e8c16360a2fea060d615a32b45270f8a8fc'
11
+ BUNDLE = Path(__file__).resolve().parents[1]/'results/reading-validation-transition-external/readouts.json'
12
+ BUNDLE_SHA = '7cfbc7b6d89e56995e8a909294c91db619eb41aaf30fa8dd3b1a2cac8e7bbf11'
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class LinearProbability:
17
+ columns: np.ndarray
18
+ mean: np.ndarray
19
+ scale: np.ndarray
20
+ weight: np.ndarray
21
+ bias: float
22
+ threshold: float
23
+
24
+ def predict(self, features):
25
+ values = (features[self.columns] - self.mean) / self.scale
26
+ return float(np.exp(-np.logaddexp(0., -(values @ self.weight + self.bias))))
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class TransitionInference:
31
+ primary: LinearProbability
32
+ student: LinearProbability
33
+ surprisal_control: LinearProbability
34
+
35
+ @classmethod
36
+ def load(cls, path=BUNDLE):
37
+ payload=Path(path).read_bytes()
38
+ if sha256(payload).hexdigest()!=BUNDLE_SHA:
39
+ raise ValueError('Unrecognized English coherence readout weights')
40
+ table=json.loads(payload)
41
+ def read(arm):
42
+ fit=table['models'][arm]
43
+ return LinearProbability(np.array(table['columns'][arm],dtype=int),np.array(fit['mean']),
44
+ np.array(fit['std']),np.array(fit['weights']),fit['intercept'],
45
+ table['thresholds'][arm])
46
+ return cls(read('integration'),read('student'),read('lexical_surprisal'))
47
+
48
+ def score_feature(self, feature_row):
49
+ features=np.r_[np.log1p(feature_row['position']),feature_row['features'],feature_row['representation']]
50
+ if features.shape!=(298,) or not np.isfinite(features).all():
51
+ raise ValueError('Coherence input dimensions or finiteness differ from the study')
52
+ risk=self.primary.predict(features)
53
+ return {'risk':risk, 'flagged':risk>self.primary.threshold,'threshold':self.primary.threshold,
54
+ 'surprisal_control_risk':self.surprisal_control.predict(features),
55
+ 'distilled_risk':self.student.predict(features)}
56
+
57
+ def score(self, text, features, tokenizer, reader, runtime, spans, *, token_trace, checkpoint_sha256, token_surprisal=None):
58
+ """Evaluate each original transition at the completed sentence's final visible token.
59
+
60
+ The first span represents the opening sentence. Subsequent positions carry one-based indices.
61
+ A sentence whose tokenization uses later text receives a null score. Risk is calibrated to
62
+ incremental coherence flags on short English stories. It is not a personal load rating.
63
+ """
64
+ if (runtime.candidate!='qwen' or runtime.revision!=REVISION or checkpoint_sha256!=CHECKPOINT
65
+ or features.relations is None or not runtime.encoder.config.tie_word_embeddings):
66
+ raise ValueError('This readout requires the selected native-attention Qwen3.5-2B checkpoint')
67
+ encoding=tokenizer.encode(text,add_special_tokens=False)
68
+ if tuple(encoding.ids)!=tuple(features.token_ids) or tuple(map(tuple,encoding.offsets))!=tuple(features.offsets):
69
+ raise ValueError('Coherence readout received features for another article')
70
+ offsets=tuple(map(tuple,features.offsets))
71
+ if [(r['start'],r['end']) for r in token_trace]!=list(offsets):
72
+ raise ValueError('Coherence token scores differ from the article source offsets')
73
+ output=[]
74
+ certified=[]
75
+ previous_end=0
76
+ for index,(start,end) in enumerate(spans,1):
77
+ if not 0<=previous_end<=start<end<=len(text) or text[start:end]!=text[start:end].strip():
78
+ raise ValueError('Expected ordered, nonoverlapping, trimmed sentence spans in the source article')
79
+ previous_end=end
80
+ if index==1:
81
+ continue
82
+ result={'start':start,'end':end,'sentence_index':index,'risk':None,'flagged':None,
83
+ 'threshold':self.primary.threshold,'surprisal_control_risk':None,'distilled_risk':None}
84
+ output.append(result)
85
+ prefix=tokenizer.encode(text[:end],add_special_tokens=False).ids
86
+ if (not 0<len(prefix)<=len(offsets) or offsets[len(prefix)-1][1]!=end
87
+ or tuple(prefix)!=tuple(features.token_ids[:len(prefix)])):
88
+ continue
89
+ # Sentence splits inside an orthographic word cannot match the study's word pooling.
90
+ if start>0 and not text[start-1].isspace():
91
+ continue
92
+ certified.append({'id':index,'index':index,'start':start,'end':end,'archive_final':False})
93
+ if certified:
94
+ import torch
95
+ from research.reading_validation.transition_external_forecast import pooled_boundary_features
96
+ with torch.inference_mode():
97
+ final,middle=reader.project(features)
98
+ design,_=pooled_boundary_features(runtime,features,middle,final,token_trace,{'text':text,'stops':certified},token_surprisal)
99
+ for row in design:
100
+ output[row['id']-2].update(self.score_feature(row))
101
+ return output
research/stage5/complex_tokenization.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audit native Qwen token boundaries for designated CompLex spans."""
2
+
3
+ import argparse
4
+ from collections import Counter, defaultdict
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+ import unicodedata
9
+
10
+ def token_span(text, offsets, start, end):
11
+ selected = []
12
+ covered = set()
13
+ for i, (left, right) in enumerate(offsets):
14
+ lo, hi = max(start, left), min(end, right)
15
+ inside = [index for index in range(lo, hi) if not text[index].isspace()]
16
+ if not inside:
17
+ continue
18
+ if text[left:start].strip() or text[end:right].strip():
19
+ return "crosses_nonwhite_boundary", None
20
+ selected.append(i)
21
+ covered.update(inside)
22
+ if covered != {index for index in range(start, end) if not text[index].isspace()} or not selected:
23
+ return "incomplete_coverage", None
24
+ return "exact_nonwhite_span", (selected[0], selected[-1])
25
+
26
+
27
+ def audit(data, tokenizer_path, output):
28
+ import tokenizers
29
+ from ..stage3.probe import _jsonl
30
+ from ..stage3.run import MODEL, REVISION
31
+
32
+ if tokenizer_path.parent.name != REVISION or tokenizer_path.name != "tokenizer.json":
33
+ raise ValueError("Expected tokenizer.json from the pinned Qwen3.5-2B revision")
34
+ tokenizer = tokenizers.Tokenizer.from_file(str(tokenizer_path))
35
+ stimuli = {row["id"]: row for row in _jsonl(data / "stimuli.jsonl")}
36
+ encoded = {key: tokenizer.encode(row["text"], add_special_tokens=False) for key, row in stimuli.items()}
37
+ by_split = defaultdict(Counter)
38
+ target_context = defaultdict(lambda: defaultdict(set))
39
+ widths = Counter()
40
+
41
+ for obs in _jsonl(data / "observations.jsonl"):
42
+ row = stimuli[obs["stimulus_id"]]
43
+ text = row["text"]
44
+ span = obs["target_span"]
45
+ left, right = span["start"], span["end"]
46
+ if not (0 <= left < right <= len(text)) or text[left:right] != span["text"] or obs["split"] != row["split"]:
47
+ raise ValueError(f"Invalid prepared CompLex target span for {obs['id']}")
48
+ stats = by_split[row["split"]]
49
+ stats["observations"] += 1
50
+ reading = encoded[row["id"]]
51
+ status, location = token_span(text, reading.offsets, left, right)
52
+ stats[status] += 1
53
+ if location is None:
54
+ continue
55
+ begin, last = location
56
+ widths[last - begin + 1] += 1
57
+ cut = tokenizer.encode(text[:right], add_special_tokens=False)
58
+ if reading.ids[:last + 1] == cut.ids:
59
+ stats["exact_span_and_stable_target_end_prefix"] += 1
60
+ else:
61
+ stats["exact_span_but_changed_token_prefix"] += 1
62
+ key = (obs["kind"], unicodedata.normalize("NFKC", span["text"]).casefold())
63
+ target_context[row["split"]][key].add(row["context_group"])
64
+
65
+ sources = {
66
+ name: hashlib.sha256(path.read_bytes()).hexdigest()
67
+ for name, path in (
68
+ ("tokenizer.json", tokenizer_path), ("stimuli.jsonl", data / "stimuli.jsonl"),
69
+ ("observations.jsonl", data / "observations.jsonl"),
70
+ )
71
+ }
72
+ heldout = target_context["test"]
73
+ eligible_repeat = [contexts for contexts in heldout.values() if len(contexts) > 1]
74
+ counts = [len(item.ids) for item in encoded.values()]
75
+ result = {
76
+ "model": MODEL,
77
+ "revision": REVISION,
78
+ "tokenizers": tokenizers.__version__,
79
+ "input_sha256": sources,
80
+ "span_scope": (
81
+ "Whole-sentence native tokenization; selected overlapping tokens must cover exactly the non-whitespace "
82
+ "characters of the designated span. A stable prefix means equality to tokenizing the original text "
83
+ "truncated immediately after the final target character. This checks token IDs only."
84
+ ),
85
+ "by_split": {name: dict(by_split[name]) for name in ("train", "trial", "test")},
86
+ "exact_target_token_width_counts": dict(sorted(widths.items())),
87
+ "native_sentence_inventory": {
88
+ "unique_sentences": len(encoded), "tokens": sum(counts), "shortest": min(counts), "longest": max(counts),
89
+ },
90
+ "test_exact_span_target_types": {
91
+ "casefold_unique": len(heldout),
92
+ "also_in_train": len(set(heldout) & set(target_context["train"])),
93
+ "with_multiple_distinct_context_groups": len(eligible_repeat),
94
+ "same_type_pairs_across_contexts_before_scoring": sum(len(group) * (len(group) - 1) // 2 for group in eligible_repeat),
95
+ },
96
+ }
97
+ output.parent.mkdir(parents=True, exist_ok=True)
98
+ output.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n", encoding="utf-8")
99
+
100
+
101
+ if __name__ == "__main__":
102
+ parser = argparse.ArgumentParser(description=__doc__)
103
+ for key in ("data", "tokenizer", "output"):
104
+ parser.add_argument(f"--{key}", required=True, type=Path)
105
+ args = parser.parse_args()
106
+ audit(args.data, args.tokenizer, args.output)
research/stage6/medreadme_span_audit.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audit exact alignment of published MedReadMe jargon spans to source text."""
2
+
3
+ import argparse
4
+ from bisect import bisect_left
5
+ from collections import Counter, defaultdict
6
+ import csv
7
+ import hashlib
8
+ from itertools import accumulate
9
+ import json
10
+ from pathlib import Path
11
+
12
+ REVISION = '7c52205d18f16b80e3ffccb4e9da88b1942df310'
13
+ FILES = {
14
+ 'readability.csv': '54082bb202d8916f296b37c9b304fd9f2c102920587ea6c346ea626be3d44ab1',
15
+ 'jargon.json': '426e43f8fa5b9d4fbba2c7b3fabad93f23d0ea7ccd4a45fb906e23f927ed1e1d',
16
+ }
17
+ SPLITS = {'train': 2587, 'dev': 784, 'test': 1140}
18
+ CATEGORIES = frozenset({'general-complex', 'general-medical-multisense', 'medical-jargon-google-easy',
19
+ 'medical-jargon-google-hard', 'medical-name-entity', 'abbr-medical', 'abbr-general'})
20
+
21
+
22
+ def compact(value):
23
+ return ''.join(value.split())
24
+
25
+
26
+ def source_spans(text, tokens, entities):
27
+ positions = [index for index, character in enumerate(text) if not character.isspace()]
28
+ pieces = [compact(token) for token in tokens]
29
+ if ''.join(text[index] for index in positions) != ''.join(pieces):
30
+ raise ValueError('Published tokens disagree with the source even after whitespace removal')
31
+ boundaries = list(accumulate(map(len, pieces), initial=0))
32
+ for start, end, category, terms in entities:
33
+ start = positions[boundaries[start]]
34
+ end = positions[boundaries[end] - 1] + 1
35
+ if compact(text[start:end]) != compact(''.join(terms)):
36
+ raise ValueError('Source character span differs from the annotated token span')
37
+ yield start, end, category
38
+
39
+
40
+ def word_coverage(spans, word_offsets):
41
+ starts = [start for start, _ in word_offsets]
42
+ for start, end, category in spans:
43
+ index = bisect_left(starts, start)
44
+ previous_overlaps = index > 0 and word_offsets[index - 1][1] > start
45
+ stop = bisect_left(starts, end)
46
+ if previous_overlaps or (stop > index and word_offsets[stop - 1][1] > end):
47
+ yield category, 'partial_word_boundary'
48
+ elif index == stop:
49
+ yield category, 'no_app_word'
50
+ else:
51
+ yield category, 'one_full_app_word' if stop - index == 1 else 'multiple_full_app_words'
52
+
53
+
54
+ def run(raw, output):
55
+ from research.semantic_tracking.iirc_anchor_fit import WORD
56
+ from research.stage3.run import save_json
57
+
58
+ for name, expected in FILES.items():
59
+ with (raw / name).open('rb') as stream:
60
+ if hashlib.file_digest(stream, 'sha256').hexdigest() != expected:
61
+ raise ValueError(f'Expected the pinned MedReadMe file: {name}')
62
+ with (raw / 'readability.csv').open(encoding='utf-8', newline='') as stream:
63
+ rows = list(csv.DictReader(stream))
64
+ texts = defaultdict(list)
65
+ for row in rows:
66
+ text = row['Sentence']
67
+ texts[(row['Source'], row['Side'], row['split'], compact(text))].append(text)
68
+ labels = json.loads((raw / 'jargon.json').read_bytes())
69
+ label_splits = Counter(row['split'] for row in labels)
70
+ if label_splits != SPLITS:
71
+ raise ValueError('Label split inventory changed')
72
+ keys = [(*row['belongings'], row['split'], compact(''.join(row['tokens']))) for row in labels]
73
+ key_counts = Counter(keys)
74
+ counts = {split: Counter() for split in SPLITS}
75
+ test_sources = Counter()
76
+ all_categories = Counter()
77
+ test_coverage = defaultdict(Counter)
78
+ for key, row in zip(keys, labels, strict=True):
79
+ source, _, split, _ = key
80
+ tokens, entities = row['tokens'], row['entities']
81
+ if not all(compact(token) for token in tokens):
82
+ raise ValueError('Published tokens must contain at least one visible character')
83
+ for begin, end, category, terms in entities:
84
+ if not (0 <= begin < end <= len(tokens) and tokens[begin:end] == terms and category in CATEGORIES):
85
+ raise ValueError('Invalid published jargon coordinates or categories')
86
+ all_categories[category] += 1
87
+ matches = texts.get(key, ())
88
+ counts[split]['sentences'] += 1
89
+ counts[split]['spans'] += len(entities)
90
+ if len(matches) != 1 or key_counts[key] != 1:
91
+ counts[split]['unmatched' if not matches else 'ambiguous'] += 1
92
+ continue
93
+ text, = matches
94
+ spans = list(source_spans(text, tokens, entities))
95
+ counts[split]['exact_unique_sentences'] += 1
96
+ counts[split]['exact_spans'] += len(spans)
97
+ if split == 'test':
98
+ test_sources[source] += 1
99
+ words = [match.span() for match in WORD.finditer(text)]
100
+ for category, coverage in word_coverage(spans, words):
101
+ test_coverage[category][coverage] += 1
102
+ save_json(output, {
103
+ 'repository_revision': REVISION, 'files_sha256': FILES,
104
+ 'matching': 'unique source, side, split and original text after removing only whitespace',
105
+ 'split_counts': counts, 'all_annotations_by_category': all_categories,
106
+ 'aligned_test_sentences_by_source': test_sources, 'aligned_test_span_coverage_by_app_word_boundaries': test_coverage,
107
+ 'scope': 'Author span annotations, individually published sentences, no reader-by-reader response or article keys.',
108
+ })
109
+
110
+
111
+ if __name__ == '__main__':
112
+ parser = argparse.ArgumentParser(description=__doc__)
113
+ for name in ('raw', 'output'):
114
+ parser.add_argument(f'--{name}', type=Path, required=True)
115
+ run(**vars(parser.parse_args()))
research/token_readout/app.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio surface for an injected, checkpoint-backed token readout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from collections import defaultdict
7
+ from collections.abc import Callable, Mapping, Sequence
8
+ from dataclasses import dataclass
9
+ from html import escape
10
+ from importlib import import_module
11
+ from math import floor, isfinite
12
+ from numbers import Real
13
+ from pathlib import Path
14
+
15
+
16
+ CHANNELS = {
17
+ 'unresolved': ('Still unexplained', '#168577'),
18
+ 'opened': ('Question raised', '#8e63bc'),
19
+ 'resolved': ('Question resolved', '#357fbe'),
20
+ 'transition': ('Transition signal', '#bd622e'),
21
+ }
22
+
23
+ EXAMPLE_TEXT = (
24
+ 'The monitor displayed a warning during the second run. '
25
+ 'The team compared the two readings and checked the calibration record. '
26
+ 'They eventually found that a loose sensor cable had triggered the warning.'
27
+ )
28
+
29
+ CSS = """
30
+ .gradio-container { max-width: 1160px !important; }
31
+ #cogllm-heading { margin-bottom: .5rem; }
32
+ #cogllm-heading h1 { letter-spacing: -.04em; font-weight: 650; }
33
+ #cogllm-reading .trace-panel {
34
+ color: #182b29; background: #fbfcf9; border: 1px solid #dce3da;
35
+ border-radius: .9rem;
36
+ }
37
+ #cogllm-reading .trace-legend {
38
+ padding: .85rem .95rem; border-bottom: 1px solid #e1e8df;
39
+ font-size: .88rem;
40
+ }
41
+ #cogllm-reading .trace-legend p, #cogllm-reading .trace-legend span {
42
+ color: #263b34 !important;
43
+ }
44
+ #cogllm-reading .trace-legend p { margin: 0 0 .55rem; line-height: 1.55; }
45
+ #cogllm-reading .trace-legend .trace-keys {
46
+ display: flex; flex-wrap: wrap; align-items: center; gap: .45rem .8rem;
47
+ }
48
+ #cogllm-reading .trace-legend span { border-radius: .3rem; padding: .13rem .38rem; }
49
+ #cogllm-reading .trace-text {
50
+ white-space: pre-wrap; overflow-wrap: anywhere; line-height: 2.05;
51
+ margin: 0 auto; padding: 1rem .95rem 1.15rem; max-width: 88ch;
52
+ color: #182b29 !important;
53
+ }
54
+ #cogllm-reading .trace-text mark {
55
+ color: #182b29 !important; border-radius: .16em; padding-block: .13em;
56
+ -webkit-box-decoration-break: clone; box-decoration-break: clone;
57
+ }
58
+ #cogllm-reading .tone-0 { background: transparent; }
59
+ #cogllm-reading .tone-1 { background: #f7f1e2; }
60
+ #cogllm-reading .tone-2 { background: #f8e9c8; }
61
+ #cogllm-reading .tone-3 { background: #f8dca5; }
62
+ #cogllm-reading .tone-4 { background: #f7c88c; }
63
+ #cogllm-reading .tone-5 { background: #f5b676; }
64
+ #cogllm-reading .point-mark, #cogllm-reading .point-key {
65
+ border-bottom: 2px solid #124f45;
66
+ }
67
+ #cogllm-reading .context-mark, #cogllm-reading .context-key {
68
+ outline: 1px dashed #31659a; outline-offset: .1em;
69
+ }
70
+ #cogllm-details .trace-detail {
71
+ padding: .1rem 0; display: grid; gap: .28rem; overflow-wrap: anywhere;
72
+ }
73
+ #cogllm-details .trace-detail p { margin: 0; }
74
+ #cogllm-details .trace-context-help { color: var(--body-text-color-subdued); font-size: .86rem; }
75
+ #cogllm-details .trace-diagnostics summary { cursor: pointer; font-size: .86rem; }
76
+ #cogllm-details .trace-diagnostics[open] .trace-values { margin-top: .45rem; }
77
+ #cogllm-details .trace-values {
78
+ display: flex; flex-wrap: wrap; gap: .25rem .72rem;
79
+ color: var(--body-text-color-subdued); font-size: .85rem;
80
+ }
81
+ #cogllm-details .trace-channel { display: inline-flex; gap: .35rem; align-items: center; }
82
+ #cogllm-details .trace-swatch { width: .6em; height: .6em; border-radius: 50%; }
83
+ #cogllm-details .trace-quote { white-space: pre-wrap; }
84
+ @media (max-width: 550px) { #cogllm-reading .trace-text { padding-inline: .68rem; } }
85
+ """
86
+
87
+
88
+ @dataclass(frozen=True, slots=True)
89
+ class Token:
90
+ start: int
91
+ end: int
92
+ unresolved: float
93
+ opened: float
94
+ resolved: float
95
+ transition: float
96
+ pointer_start: int | None
97
+ pointer_end: int | None
98
+
99
+
100
+ @dataclass(frozen=True, slots=True)
101
+ class Analysis:
102
+ text: str
103
+ checkpoint: str
104
+ tokens: tuple[Token, ...]
105
+
106
+
107
+ def _score(value: object) -> float:
108
+ if isinstance(value, bool) or not isinstance(value, Real):
109
+ raise ValueError('Model scores must be numeric.')
110
+ result = float(value)
111
+ if not isfinite(result) or result < 0:
112
+ raise ValueError('Model scores must be finite and nonnegative.')
113
+ return result
114
+
115
+
116
+ def parse_analysis(text: str, payload: Mapping) -> Analysis:
117
+ """Check exact input round-trip, causal pointer spans, and display coordinates."""
118
+ if not isinstance(payload, Mapping) or payload.get('text') != text:
119
+ raise ValueError('The analysis did not preserve the original passage.')
120
+ checkpoint = payload.get('checkpoint')
121
+ if not isinstance(checkpoint, str) or not checkpoint.strip():
122
+ raise ValueError('The analysis did not identify its model checkpoint.')
123
+ rows = payload.get('tokens')
124
+ if not isinstance(rows, Sequence) or isinstance(rows, (str, bytes)) or not rows:
125
+ raise ValueError('The passage contains no text the model can analyze.')
126
+ previous_start = 0
127
+ tokens = []
128
+ for row in rows:
129
+ if not isinstance(row, Mapping):
130
+ raise ValueError('The analysis is missing scores or source positions.')
131
+ start, end = row.get('start'), row.get('end')
132
+ if type(start) is not int or type(end) is not int or not previous_start <= start <= end <= len(text):
133
+ raise ValueError('The analysis returned invalid or out-of-order source positions.')
134
+ pointer_start, pointer_end = row.get('pointer_start'), row.get('pointer_end')
135
+ if (pointer_start is not None or pointer_end is not None) and (
136
+ type(pointer_start) is not int or type(pointer_end) is not int
137
+ or not 0 <= pointer_start < pointer_end <= end
138
+ ):
139
+ raise ValueError('The analysis linked to text outside the current reading position.')
140
+ scores = {key: _score(row.get(key)) for key in CHANNELS}
141
+ tokens.append(Token(start, end, **scores, pointer_start=pointer_start, pointer_end=pointer_end))
142
+ previous_start = start
143
+ return Analysis(text, checkpoint, tuple(tokens))
144
+
145
+
146
+ def source_html(text: str) -> str:
147
+ """Preserve literal carriage returns through HTML's newline normalization."""
148
+ return escape(text, quote=False).replace('\r', '&#13;')
149
+
150
+
151
+ def render_article(analysis: Analysis, selected: int) -> str:
152
+ text, tokens = analysis.text, analysis.tokens
153
+ current = tokens[selected]
154
+ starts, ends = defaultdict(list), defaultdict(list)
155
+ boundaries = {0, len(text), current.start, current.end}
156
+ if current.pointer_start is not None:
157
+ boundaries.update((current.pointer_start, current.pointer_end))
158
+ for index, token in enumerate(tokens):
159
+ if token.start < token.end:
160
+ starts[token.start].append(index)
161
+ ends[token.end].append(index)
162
+ boundaries.update((token.start, token.end))
163
+
164
+ parts = [f'<section class="trace-panel" data-checkpoint="{escape(analysis.checkpoint, quote=True)}">',
165
+ '<div class="trace-legend" role="group" aria-label="Highlighting guide">',
166
+ '<p>Darker shading means the model estimates that more is still unexplained at that point. '
167
+ 'Lighter shading later in the text means the estimate has fallen. Compare colors within this passage.</p>',
168
+ '<div class="trace-keys"><span class="point-key">Underline · Selected text</span>',
169
+ '<span class="context-key">Dashed outline · Related earlier text</span></div></div>',
170
+ '<div class="trace-text" aria-label="Analyzed passage">']
171
+ maximum = max(token.unresolved for token in tokens)
172
+ ordered = sorted(boundaries)
173
+ active = set()
174
+ for start, end in zip(ordered, ordered[1:]):
175
+ active.difference_update(ends[start])
176
+ active.update(starts[start])
177
+ is_current = current.start <= start < end <= current.end
178
+ is_context = current.pointer_start is not None and current.pointer_start <= start < end <= current.pointer_end
179
+ content = source_html(text[start:end])
180
+ if not active and not is_current and not is_context:
181
+ parts.append(content)
182
+ continue
183
+ classes = []
184
+ attributes = [f'data-start="{start}"', f'data-end="{end}"']
185
+ if active:
186
+ index = max(active, key=lambda item: (tokens[item].unresolved, item))
187
+ score = tokens[index].unresolved
188
+ tone = 0 if maximum == 0 else min(5, floor(5 * (score / maximum) + .5))
189
+ classes.append(f'tone-{tone}')
190
+ attributes.extend((f'data-token="{index + 1}"', f'data-unresolved="{score:.9g}"',
191
+ f'title="Still unexplained at this point {score:.3f}"'))
192
+ if is_current:
193
+ classes.append('point-mark')
194
+ attributes.append('aria-current="location"')
195
+ if is_context:
196
+ classes.append('context-mark')
197
+ parts.append(f'<mark class="{" ".join(classes)}" {" ".join(attributes)}>{content}</mark>')
198
+ parts.append('</div></section>')
199
+ return ''.join(parts)
200
+
201
+
202
+ def render_detail(analysis: Analysis, selected: int) -> str:
203
+ token = analysis.tokens[selected]
204
+ text = analysis.text
205
+ context_start, context_end = max(0, token.start - 12), min(len(text), token.end + 12)
206
+ snippet = (('…' if context_start else '') + source_html(text[context_start:token.start])
207
+ + '<strong>' + source_html(text[token.start:token.end]) + '</strong>'
208
+ + source_html(text[token.end:context_end]) + ('…' if context_end < len(text) else ''))
209
+ scores = ''.join(
210
+ f'<span class="trace-channel"><span class="trace-swatch" style="background:{color}" '
211
+ f'aria-hidden="true"></span>{label} {getattr(token, key):.3f}</span>'
212
+ for key, (label, color) in CHANNELS.items()
213
+ )
214
+ detail = [f'<div class="trace-detail" role="status" data-selected="{selected + 1}">',
215
+ f'<p class="trace-quote">Selected text · “{snippet}”</p>']
216
+ if token.pointer_start is not None:
217
+ pointer = source_html(text[token.pointer_start:token.pointer_end])
218
+ detail.append(f'<p class="trace-quote" data-pointer-start="{token.pointer_start}" '
219
+ f'data-pointer-end="{token.pointer_end}"><strong>Related earlier text</strong> · “{pointer}”</p>')
220
+ detail.append('<p class="trace-context-help">The model suggests rereading the two marked parts together.</p>')
221
+ detail.extend(('<details class="trace-diagnostics"><summary>Model scores at this position</summary>',
222
+ f'<p class="trace-values">{scores}</p></details></div>'))
223
+ return ''.join(detail)
224
+
225
+
226
+ def initial_position(analysis: Analysis) -> tuple[int, bool]:
227
+ """Start at a local rise so cumulative color alone does not select the end."""
228
+ tokens = analysis.tokens
229
+ candidates = [i for i, token in enumerate(tokens) if analysis.text[token.start:token.end].strip()]
230
+
231
+ def increase(index):
232
+ return tokens[index].unresolved - tokens[index - 1].unresolved if index else 0.0
233
+
234
+ selected = max(candidates, key=increase, default=0)
235
+ has_rise = bool(candidates and increase(selected) > 0)
236
+ return (selected if has_rise else (candidates or [0])[0]), has_rise
237
+
238
+
239
+ def plot_rows(analysis: Analysis):
240
+ import pandas as pd
241
+
242
+ return pd.DataFrame.from_records(
243
+ ({'token': index, 'score': getattr(token, key), 'signal': label}
244
+ for index, token in enumerate(analysis.tokens, 1) for key, (label, _) in CHANNELS.items()),
245
+ columns=('token', 'score', 'signal'),
246
+ )
247
+
248
+
249
+ def build_app(analyze: Callable[[str], Mapping]):
250
+ import gradio as gr
251
+
252
+ with gr.Blocks(title='CogLLM Reading Review', analytics_enabled=False) as ui:
253
+ gr.Markdown('# CogLLM Reading Review\n'
254
+ 'Analyze a passage to see where the model estimates an explanation is still pending.',
255
+ elem_id='cogllm-heading')
256
+ with gr.Row(equal_height=False):
257
+ with gr.Column(scale=1, min_width=270):
258
+ article = gr.Textbox(label='Your passage', lines=9, max_lines=18,
259
+ placeholder='Paste a passage to review')
260
+ run = gr.Button('Analyze passage', variant='primary')
261
+ example = gr.Button('Load example', variant='secondary', size='sm')
262
+ gr.Markdown('In the example, you might wonder what caused the warning. '
263
+ 'The last sentence explains it. Load the example, then select **Analyze passage**.')
264
+
265
+ with gr.Column(scale=2, min_width=320):
266
+ status = gr.HTML()
267
+ highlighted = gr.HTML(elem_id='cogllm-reading')
268
+ cursor = gr.Slider(1, 2, value=1, step=1, precision=0, label='Explore a position in the passage',
269
+ visible=False)
270
+ detail = gr.HTML(elem_id='cogllm-details')
271
+ with gr.Accordion('View the model curves', open=False):
272
+ gr.Markdown('Green tracks what the model estimates is still unexplained as you read. '
273
+ 'Purple and blue estimate questions raised or resolved at each position. '
274
+ 'Orange flags possible breaks in continuity.')
275
+ plot = gr.LinePlot(x='token', y='score', color='signal', label='Model signals by position',
276
+ x_title='Position in the passage', y_title='Model score', color_title='Signal',
277
+ show_label=True, height=330, visible=False,
278
+ color_map={label: color for label, color in CHANNELS.values()})
279
+ analysis_state = gr.State()
280
+
281
+ def submit(text):
282
+ if not isinstance(text, str) or not text.strip():
283
+ raise gr.Error('Paste a passage or load the example.')
284
+ try:
285
+ analysis = parse_analysis(text, analyze(text))
286
+ except ValueError as error:
287
+ raise gr.Error(escape(str(error))) from error
288
+ selected, has_rise = initial_position(analysis)
289
+ count = len(analysis.tokens)
290
+ note = ('<p role="status"><strong>Start at the underline.</strong> '
291
+ 'The model’s estimate of what remains unexplained rises most here.</p>'
292
+ if has_rise else '<p role="status">Move the slider to explore the passage.</p>')
293
+ return (
294
+ analysis, render_article(analysis, selected), gr.update(value=plot_rows(analysis), visible=True),
295
+ gr.update(maximum=max(count, 2), value=selected + 1, visible=True, interactive=count > 1),
296
+ render_detail(analysis, selected), note,
297
+ )
298
+
299
+ def load_example():
300
+ return (EXAMPLE_TEXT, None, '', gr.update(value=None, visible=False),
301
+ gr.update(maximum=2, value=1, visible=False), '', '')
302
+
303
+ def inspect(analysis, index):
304
+ if analysis is None or index is None or not 1 <= index <= len(analysis.tokens):
305
+ return gr.skip(), gr.skip()
306
+ selected = int(index) - 1
307
+ return render_article(analysis, selected), render_detail(analysis, selected)
308
+
309
+ run.click(submit, article, [analysis_state, highlighted, plot, cursor, detail, status],
310
+ api_name='analyze', concurrency_id='passage', concurrency_limit=1)
311
+ example.click(load_example, outputs=[article, analysis_state, highlighted, plot, cursor, detail, status],
312
+ api_name='load_example', api_visibility='undocumented', show_progress='hidden',
313
+ concurrency_id='passage', concurrency_limit=1)
314
+ cursor.input(inspect, [analysis_state, cursor], [highlighted, detail], api_name='select_token',
315
+ api_visibility='undocumented', show_progress='hidden', trigger_mode='always_last')
316
+ return ui
317
+
318
+
319
+ def load_runner(spec: str, model: Path, checkpoint: Path, **options):
320
+ """Resolve an explicitly selected runner factory for a real checkpoint."""
321
+ module, separator, name = spec.partition(':')
322
+ if not separator or not module or not name.isidentifier():
323
+ raise ValueError('Runner must use module:factory syntax')
324
+ factory = getattr(import_module(module), name)
325
+ analyze = factory(model=model, checkpoint=checkpoint, **options)
326
+ if not callable(analyze):
327
+ raise TypeError('Runner factory must return a callable analysis function')
328
+ return analyze
329
+
330
+
331
+ def main():
332
+ import gradio as gr
333
+
334
+ parser = argparse.ArgumentParser(description=__doc__)
335
+ parser.add_argument('--runner', default='research.token_readout.portable_runner:load',
336
+ help='Real candidate factory, module:factory')
337
+ parser.add_argument('--view', choices=('writing', 'signals'), default='writing',
338
+ help='English reader-rated wording or the multilingual research curve')
339
+ parser.add_argument('--model', type=Path, required=True, help='Local Qwen snapshot')
340
+ parser.add_argument('--checkpoint', type=Path, required=True, help='Sealed token readout checkpoint')
341
+ parser.add_argument('--narrative-operating-point', choices=('balanced','high_recall'), default='balanced',
342
+ help='Source-calibrated screening rule for character introductions')
343
+ parser.add_argument('--port', type=int, default=7860)
344
+ args = parser.parse_args()
345
+ css = CSS
346
+ if args.view == 'writing':
347
+ from research.reading_validation.local_inference import LocalInference
348
+ from research.reading_validation.transition_inference import TransitionInference
349
+ from research.reading_validation.narrative_inference import MarginalNarrativeInference
350
+ from research.reading_validation.terminology_inference import TerminologyInference
351
+ from research.token_readout import writing_review
352
+ runner = load_runner(args.runner, args.model, args.checkpoint, english_head=LocalInference.load(),
353
+ transition_head=TransitionInference.load(), narrative_head=MarginalNarrativeInference.for_writers(args.narrative_operating_point),
354
+ terminology_head=TerminologyInference.load())
355
+ ui = writing_review.build_app(runner)
356
+ css += writing_review.STYLE
357
+ else:
358
+ ui = build_app(load_runner(args.runner, args.model, args.checkpoint))
359
+ ui.launch(
360
+ server_name='127.0.0.1', server_port=args.port, share=False, css=css,
361
+ theme=gr.themes.Soft(primary_hue='teal', neutral_hue='slate'),
362
+ )
363
+
364
+
365
+ if __name__ == '__main__':
366
+ main()
research/token_readout/backbone.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen causal token features with native full-attention relationships."""
2
+
3
+ from contextlib import contextmanager, nullcontext
4
+ from dataclasses import dataclass
5
+ import inspect
6
+ from math import isfinite, log
7
+ from pathlib import Path
8
+ from threading import RLock
9
+
10
+ import torch
11
+
12
+ from research.backbone_transfer.extract import RELATIVE_RMS_LIMIT, load_language_model
13
+
14
+
15
+ MAX_TOKENS = 2048
16
+ RELATION_ABSOLUTE_LIMIT = 1e-3
17
+ _ATTENTION_LOCK = RLock()
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Features:
22
+ token_ids: tuple[int, ...]
23
+ offsets: tuple[tuple[int, int], ...]
24
+ hidden: torch.Tensor
25
+ mid: torch.Tensor
26
+ relations: torch.Tensor | None
27
+
28
+
29
+ class _GlobalRelationships:
30
+ """Aggregate the SDPA weights from its actual Q, K, mask, and scale."""
31
+
32
+ def __init__(self, original, layers, size, device):
33
+ self.original = original
34
+ self.layers = frozenset(layers)
35
+ self.seen = set()
36
+ self.checked_masks = []
37
+ self.positions = torch.arange(size, device=device)
38
+ self.total = torch.zeros((size, size), device=device, dtype=torch.float32)
39
+ self.peak = torch.zeros_like(self.total)
40
+ self.head_count = 0
41
+
42
+ def __call__(self, module, query, key, value, attention_mask, **kwargs):
43
+ if module in self.layers:
44
+ if module in self.seen:
45
+ raise RuntimeError(f'Duplicate global attention capture at layer {module.layer_idx}')
46
+ self.capture(module, query, key, value, attention_mask, kwargs)
47
+ self.seen.add(module)
48
+ return self.original(module, query, key, value, attention_mask, **kwargs)
49
+
50
+ def capture(self, module, query, key, value, attention_mask, kwargs):
51
+ size = len(self.positions)
52
+ scale = kwargs.get('scaling')
53
+ is_causal = kwargs.get('is_causal')
54
+ if is_causal is None:
55
+ is_causal = module.is_causal
56
+ if (query.ndim != 4 or key.ndim != 4 or query.shape[0] != 1 or key.shape[0] != 1
57
+ or query.shape[-2:] != key.shape[-2:] or query.shape[-2] != size
58
+ or not query.shape[1] or not key.shape[1] or query.shape[1] % key.shape[1]
59
+ or getattr(module, 'num_key_value_groups', 1) != query.shape[1] // key.shape[1]
60
+ or query.dtype != torch.float32 or key.dtype != torch.float32 or value.dtype != torch.float32
61
+ or type(scale) not in (int, float) or not isfinite(scale) or scale <= 0
62
+ or kwargs.get('dropout', 0) != 0 or not is_causal
63
+ or kwargs.get('position_bias') is not None or kwargs.get('sliding_window') is not None):
64
+ raise RuntimeError('Global relation capture requires unpadded causal FP32 native attention')
65
+ self.check_mask(attention_mask)
66
+
67
+ heads = query.shape[1]
68
+ key_heads = key.shape[1]
69
+ grouped_queries = query[0].unflatten(0, (key_heads, heads // key_heads))
70
+ transposed_keys = key[0].transpose(-2, -1).unsqueeze(1)
71
+ for start in range(0, size, 32):
72
+ stop = min(start + 32, size)
73
+ positions = self.positions[start:stop, None]
74
+ scores = (grouped_queries[:, :, start:stop] @ transposed_keys[:, :, :, :stop]) * scale
75
+ visible = self.positions[None, :stop] <= positions
76
+ weights = scores.masked_fill(~visible, -torch.inf).softmax(dim=-1).flatten(0, 1)
77
+ self.total[start:stop, :stop].add_(weights.sum(dim=0))
78
+ current_peak = self.peak[start:stop, :stop]
79
+ torch.maximum(current_peak, weights.amax(dim=0), out=current_peak)
80
+ self.head_count += heads
81
+
82
+ def check_mask(self, mask):
83
+ if mask is None or any(mask is checked for checked in self.checked_masks):
84
+ return
85
+ size = len(self.positions)
86
+ if mask.shape != (1, 1, size, size):
87
+ raise RuntimeError('Expected a single square mask for global attention')
88
+ visible = self.positions[:, None] >= self.positions[None, :]
89
+ values = mask[0, 0]
90
+ if values.dtype == torch.bool:
91
+ correct = torch.equal(values, visible)
92
+ elif values.is_floating_point():
93
+ correct = bool(torch.where(visible, values == 0, values <= -1e8).all())
94
+ else:
95
+ correct = False
96
+ if not correct:
97
+ raise RuntimeError('Native global attention does not match causal prefix visibility')
98
+ self.checked_masks.append(mask)
99
+
100
+ def result(self):
101
+ if self.seen != self.layers or not self.head_count:
102
+ raise RuntimeError(f'Captured {len(self.seen)} of {len(self.layers)} native global attention layers')
103
+ uniform_reference = self.positions[:, None] + 1
104
+ mean = self.total / self.head_count
105
+ relations = (torch.stack((mean, self.peak), dim=-1) * uniform_reference.unsqueeze(-1)).log1p() - log(2)
106
+ return relations.masked_fill((self.positions[:, None] < self.positions[None, :]).unsqueeze(-1), 0)
107
+
108
+
109
+ @contextmanager
110
+ def _capture_global(module, layers, size, device):
111
+ # Override the owning model module, leaving Transformers' global SDPA registry untouched.
112
+ with _ATTENTION_LOCK:
113
+ original = module.ALL_ATTENTION_FUNCTIONS
114
+ registry = type(original)()
115
+ capture = _GlobalRelationships(original['sdpa'], layers, size, device)
116
+ registry['sdpa'] = capture
117
+ module.ALL_ATTENTION_FUNCTIONS = registry
118
+ try:
119
+ yield capture
120
+ finally:
121
+ module.ALL_ATTENTION_FUNCTIONS = original
122
+
123
+
124
+ class Backbone:
125
+ """Single-document causal forward for the pinned text backbones."""
126
+
127
+ def __init__(self, candidate, encoder, tokenizer, spec, *, native_attention=True):
128
+ self.candidate = candidate
129
+ self.revision = spec['revision']
130
+ self.width = spec['hidden_width']
131
+ self.encoder = encoder
132
+ self.tokenizer = tokenizer
133
+ self.device = next(encoder.parameters()).device
134
+ if encoder.training or not len(encoder.layers):
135
+ raise ValueError('Expected a frozen backbone in evaluation mode with identifiable layers')
136
+ self.mid_index = (len(encoder.layers) - 1) // 2
137
+ self.global_layers = ()
138
+ self.attention_module = None
139
+ if not native_attention:
140
+ return
141
+ if encoder.config._attn_implementation != 'sdpa':
142
+ raise ValueError('Native relations require the validated SDPA attention backend')
143
+ self.global_layers = tuple(
144
+ layer.self_attn for layer, layer_type in zip(encoder.layers, encoder.config.layer_types, strict=True)
145
+ if layer_type == 'full_attention'
146
+ )
147
+ modules = {inspect.getmodule(type(layer)) for layer in self.global_layers}
148
+ if len(modules) != 1:
149
+ raise ValueError('Expected a single owning attention module and visible native global attention layers')
150
+ self.attention_module = modules.pop()
151
+ if not hasattr(self.attention_module, 'ALL_ATTENTION_FUNCTIONS'):
152
+ raise ValueError('The pinned architecture does not expose its native attention interface')
153
+
154
+ @classmethod
155
+ def load(cls, candidate, model, *, native_attention=True, serving_device=None):
156
+ from tokenizers import Tokenizer
157
+ import transformers
158
+
159
+ model = Path(model)
160
+ encoder, spec = load_language_model(model, candidate, torch, transformers, serving_device=serving_device)
161
+ tokenizer = Tokenizer.from_file(str(model / 'tokenizer.json'))
162
+ return cls(candidate, encoder, tokenizer, spec, native_attention=native_attention)
163
+
164
+ def encode(self, text):
165
+ if type(text) is not str or not text.strip():
166
+ raise ValueError('Provide nonempty original text')
167
+ encoded = self.tokenizer.encode(text, add_special_tokens=False)
168
+ if any(not 0 <= left <= right <= len(text) for left, right in encoded.offsets):
169
+ raise ValueError('Tokenizer offsets fall outside the original Unicode text')
170
+ return self.encode_tokens(tuple(encoded.ids), tuple(encoded.offsets))
171
+
172
+ def encode_tokens(self, token_ids, offsets):
173
+ size = len(token_ids)
174
+ if not 1 <= size <= MAX_TOKENS or len(offsets) != size:
175
+ raise ValueError(f'Expected one unpadded document with 1–{MAX_TOKENS} tokens and exact offsets')
176
+ inputs = torch.tensor([token_ids], device=self.device, dtype=torch.long)
177
+ middle = []
178
+
179
+ def collect(_module, _inputs, output):
180
+ if not isinstance(output, torch.Tensor) or middle:
181
+ raise RuntimeError('Expected exactly one intermediate token tensor')
182
+ middle.append(output[0])
183
+
184
+ capture = (_capture_global(self.attention_module, self.global_layers, size, self.device)
185
+ if self.attention_module is not None else nullcontext())
186
+ with capture as native, self.encoder.layers[self.mid_index].register_forward_hook(collect):
187
+ with torch.inference_mode():
188
+ hidden = self.encoder(input_ids=inputs, use_cache=False, output_attentions=False,
189
+ output_hidden_states=False).last_hidden_state[0]
190
+ relations = native.result() if native is not None else None
191
+ if len(middle) != 1:
192
+ raise RuntimeError('Missing intermediate token tensor')
193
+ hidden, mid = hidden.detach().clone(), middle[0].detach().clone()
194
+ if relations is not None:
195
+ relations = relations.detach().clone()
196
+ if (hidden.shape != (size, self.width) or mid.shape != hidden.shape
197
+ or (relations is not None and relations.shape != (size, size, 2))
198
+ or any(value.dtype != torch.float32 or not bool(value.isfinite().all())
199
+ for value in (hidden, mid, relations) if value is not None)):
200
+ raise RuntimeError('Malformed or nonfinite frozen backbone features')
201
+ return Features(token_ids, offsets, hidden, mid, relations)
202
+
203
+ def validate(self, text):
204
+ """Verify suffix invariance at every frozen feature including native relationships."""
205
+ original = self.encode(text)
206
+ size = len(original.token_ids)
207
+ if size < 4:
208
+ raise ValueError('Validation requires at least four tokens')
209
+ cut = size // 2
210
+ short = self.encode_tokens(original.token_ids[:cut], original.offsets[:cut])
211
+ # Swap in a distinct, verified tokenizer ID while holding indices fixed.
212
+ alternatives = set(original.token_ids)
213
+ if len(alternatives) < 2:
214
+ raise ValueError('Validation requires distinct token IDs')
215
+ first, second = sorted(alternatives)[:2]
216
+ changed_ids = tuple(second if token == first else first for token in original.token_ids[cut:])
217
+ changed = self.encode_tokens(original.token_ids[:cut] + changed_ids, original.offsets)
218
+
219
+ def prefix(value):
220
+ features = {'hidden': value.hidden[:cut], 'mid': value.mid[:cut]}
221
+ if value.relations is not None:
222
+ features['relations'] = value.relations[:cut, :cut]
223
+ return features
224
+
225
+ expected = prefix(original)
226
+ variants = {'truncation': prefix(short), 'suffix_replacement': prefix(changed)}
227
+ absolute = {
228
+ label: {name: float((tensor - expected[name]).abs().max()) for name, tensor in actual.items()}
229
+ for label, actual in variants.items()
230
+ }
231
+ relative = {}
232
+ for label, actual in variants.items():
233
+ relative[label] = {}
234
+ for name in ('hidden', 'mid'):
235
+ difference = (actual[name] - expected[name]).square().mean(dim=-1).sqrt()
236
+ scale = expected[name].square().mean(dim=-1).sqrt().clamp_min(1e-8)
237
+ relative[label][name] = float((difference / scale).max())
238
+ if (any(error > RELATIVE_RMS_LIMIT for check in relative.values() for error in check.values())
239
+ or any(check.get('relations', 0.0) > RELATION_ABSOLUTE_LIMIT for check in absolute.values())):
240
+ raise RuntimeError(f'{self.candidate} causal-prefix feature check failed: {relative}, {absolute}')
241
+ return {'tokens': size, 'common_prefix': cut, 'global_layers': len(self.global_layers),
242
+ 'mid_layer': self.mid_index, 'max_absolute_difference': absolute, 'max_relative_rms': relative,
243
+ 'hidden_relative_tolerance': RELATIVE_RMS_LIMIT, 'relation_absolute_tolerance': RELATION_ABSOLUTE_LIMIT}
research/token_readout/expectation_view.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Display changes in population word expectations at their printed positions."""
2
+
3
+ from html import escape
4
+ from math import isclose, isfinite
5
+
6
+ SCOPE = "population_next_word_disagreement"
7
+ EXAMPLE = (
8
+ "The lights went out in the middle of dinner. "
9
+ "Maya opened a drawer and felt around until she found a match. "
10
+ "A moment later the candle on the table was burning."
11
+ )
12
+
13
+ STYLE = """
14
+ .writing-review .expectation-panel {border-top:1px solid #c4d1cc;padding-top:.75rem;color:#23352f;}
15
+ .writing-review .expectation-panel h3,.writing-review .expectation-panel p,
16
+ .writing-review .expectation-panel summary {color:#23352f!important;}
17
+ .writing-review .expectation-increase {border-bottom:3px solid #974814;}
18
+ .writing-review .expectation-decrease {border-bottom:3px dotted #14596a;}
19
+ .writing-review .expectation-chart {display:block;width:100%;height:8.5rem;}
20
+ .writing-review .expectation-axis {display:flex;justify-content:space-between;font-size:.85rem;}
21
+ .writing-review .expectation-table {max-height:18rem;overflow:auto;}
22
+ .writing-review .expectation-table table {width:100%;border-collapse:collapse;color:#23352f;}
23
+ .writing-review .expectation-table th,.writing-review .expectation-table td {padding:.2rem .35rem;text-align:left;background:#fcfcf8;}
24
+ """
25
+
26
+
27
+ def probability(value):
28
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or not 0 <= value <= 1:
29
+ raise ValueError("A word expectation falls outside the measured probability scale.")
30
+ return value
31
+
32
+
33
+ def bounds(grouped, other):
34
+ low = probability(grouped)
35
+ high = low + probability(other) ** 2
36
+ if high > 1 + 1e-6:
37
+ raise ValueError("The residual vocabulary mass disagrees with the word probabilities.")
38
+ return low, min(high, 1.)
39
+
40
+
41
+ def label_range(low, high, *, signed=False):
42
+ fmt = "+.1f" if signed else ".0f"
43
+ ends = [format(100*x, fmt) for x in (low, high)]
44
+ value = ends[0] if ends[0] == ends[1] else " to ".join(ends)
45
+ return value if signed else value+"%"
46
+
47
+
48
+ def plot(runs):
49
+ lower, upper, bands = [], [], []
50
+ for run in runs:
51
+ bottom = [f"{x:.2f} {99-98*lo:.2f}" for x,lo,hi in run]
52
+ top = [f"{x:.2f} {99-98*hi:.2f}" for x,lo,hi in run]
53
+ lower.append("M"+" L".join(bottom))
54
+ upper.append("M"+" L".join(top))
55
+ bands.append("M"+" L".join(bottom+top[::-1])+" Z")
56
+ return (
57
+ '<svg class="expectation-chart" viewBox="0 0 400 100" preserveAspectRatio="none" '
58
+ 'role="img" aria-label="Estimated range for the chance that two readers give different next-word answers">'
59
+ '<path d="M0 1H400 M0 50H400 M0 99H400" stroke="#c6d1ce" fill="none" vector-effect="non-scaling-stroke"/>'
60
+ f'<path class="expectation-band" d="{" ".join(bands)}" fill="#b8d5cf"/>'
61
+ f'<path class="expectation-upper" d="{" ".join(upper)}" stroke="#47847e" stroke-width="1" fill="none" vector-effect="non-scaling-stroke"/>'
62
+ f'<path class="expectation-lower" d="{" ".join(lower)}" stroke="#175c59" stroke-width="2" fill="none" vector-effect="non-scaling-stroke"/></svg>'
63
+ )
64
+
65
+
66
+ def present(text, reading):
67
+ if reading["scope"] != SCOPE:
68
+ raise ValueError("Unknown population or word expectation measure.")
69
+ words = reading["words"]
70
+ if not words:
71
+ raise ValueError("The passage contains no scorable English word boundary.")
72
+ prev_end = 0
73
+ spans, shifts, cells, runs = [], [], [], []
74
+ for i, word in enumerate(words):
75
+ a, b = word["start"], word["end"]
76
+ if not (isinstance(a, int) and isinstance(b, int) and prev_end <= a < b <= len(text)
77
+ and text[a:b] == word["text"]):
78
+ raise ValueError("A word expectation refers to a different passage.")
79
+ prev_end = b
80
+ lo, hi = bounds(word["after"], word["other_after"])
81
+ before, delta = word["before"], word["change"]
82
+ if before is None:
83
+ if delta is not None:
84
+ raise ValueError("The first word of a measured run cannot have a change without an earlier estimate.")
85
+ before_label, change_label = "—", "—"
86
+ runs.append([])
87
+ else:
88
+ old_lo, old_hi = bounds(before, word["other_before"])
89
+ if delta is None or not isclose(lo - old_lo, delta, abs_tol=1e-6) or not runs:
90
+ raise ValueError("The displayed word change disagrees with its two probabilities.")
91
+ low_change, high_change = lo - old_hi, hi - old_lo
92
+ before_label = label_range(old_lo, old_hi)
93
+ change_label = label_range(low_change, high_change, signed=True)
94
+ if low_change >= .20 or high_change <= -.20:
95
+ guaranteed = low_change if low_change >= .20 else high_change
96
+ spans.append((a, b, "expectation-increase" if guaranteed > 0 else "expectation-decrease"))
97
+ shifts.append((guaranteed, before_label, label_range(lo,hi), word))
98
+ label = escape(word["text"])
99
+ cells.append(f"<tr><td>{i+1}</td><td>{label}</td><td>{before_label}</td><td>{label_range(lo,hi)}</td><td>{change_label}</td></tr>")
100
+ runs[-1].append((2 + 396*i/max(len(words)-1,1), lo, hi))
101
+ examples = []
102
+ for increasing in (False, True):
103
+ selected = [v for v in shifts if (v[0] > 0 if increasing else v[0] < 0)]
104
+ if selected:
105
+ _, before, after, word = max(selected, key=lambda v: abs(v[0]))
106
+ verb = "spread out" if increasing else "narrow"
107
+ top = word["top_next"][0]["word"]
108
+ clue = (f' The leading next word is <strong>“{escape(top)}”</strong>.' if top and not increasing else "")
109
+ examples.append(f'After <strong>“{escape(word["text"])}”</strong> the guesses {verb} ({before} → {after}).'+clue)
110
+ return spans, (
111
+ '<section class="expectation-panel"><h3>Where do readers’ next guesses change?</h3>'
112
+ '<p>After each word, how often would two readers guess different next words? '
113
+ 'A narrow band gives a more precise estimate. A wide band means many possible answers '
114
+ 'fall outside the model’s 8,192 named words. The underlines show only changes of at least '
115
+ '20 percentage points in the same direction across the whole range.</p>'
116
+ '<div class="expectation-axis"><span>100% disagree</span></div>' + plot(runs) +
117
+ f'<div class="expectation-axis"><span>0% · First measured word</span><span>Last measured word</span></div>'
118
+ '<p>' + " ".join(examples) + '</p><details><summary>Values at each word</summary>'
119
+ '<div class="expectation-table"><table><thead><tr><th>Position</th><th>Word</th>'
120
+ '<th>Before</th><th>After</th><th>Change (points)</th></tr></thead><tbody>' +
121
+ "".join(cells) + '</tbody></table></div></details>'
122
+ f'<p class="reading-caption">{len(words)} of {reading["coverage"]["surface_words"]} word endings received an estimate. '
123
+ 'An estimate at the very end assumes the text continues.</p></section>'
124
+ )
research/token_readout/experimental_view.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render the already-computed prefix signal beside the reviewed draft."""
2
+
3
+ from research.token_readout.app import Analysis, source_html
4
+
5
+
6
+ STYLE = """
7
+ .token-experiment { margin-top: .8rem; }
8
+ .token-experiment > summary, .token-experiment details > summary { cursor: pointer; }
9
+ .token-experiment .signal-caption { font-size: .9rem; }
10
+ .token-experiment figure { margin: .8rem 0; }
11
+ .token-experiment .signal-plot { display: block; width: 100%; height: 8rem; }
12
+ .token-experiment .signal-axis { display: flex; justify-content: space-between; font-size: .82rem; }
13
+ .token-experiment .signal-table { max-height: 17rem; overflow: auto; }
14
+ .token-experiment table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
15
+ .token-experiment :is(th, td) { text-align: left; padding: .25rem .5rem; }
16
+ .token-experiment th { position: sticky; top: 0; background: #fcfcf8; }
17
+ .token-experiment .signal-text { white-space: pre-wrap; overflow-wrap: anywhere; }
18
+ """
19
+
20
+
21
+ def token_text(text, token):
22
+ value = text[token.start:token.end]
23
+ if not value:
24
+ return "No printed characters"
25
+ if value.isspace():
26
+ return "Whitespace"
27
+ return source_html(value)
28
+
29
+
30
+ def panel(analysis: Analysis):
31
+ tokens = analysis.tokens
32
+ peak = max(token.unresolved for token in tokens)
33
+ points = []
34
+ rows = []
35
+ for index, token in enumerate(tokens):
36
+ x = 2 + 596 * index / max(1, len(tokens) - 1)
37
+ y = 126 - 124 * token.unresolved / peak if peak else 126
38
+ points.append(f"{x:.2f},{y:.2f}")
39
+ difference = token.unresolved - tokens[index - 1].unresolved if index else None
40
+ change = f"{difference:+.4g}" if difference is not None else "—"
41
+ rows.append(
42
+ f'<tr><td>{index + 1}</td><td class="signal-text">{token_text(analysis.text, token)}</td>'
43
+ f'<td>{token.unresolved:.4g}</td><td>{change}</td></tr>'
44
+ )
45
+
46
+ if len(points) == 1:
47
+ x, y = points[0].split(",")
48
+ curve = f'<circle cx="{x}" cy="{y}" r="2" fill="#166257"/>'
49
+ else:
50
+ curve = (
51
+ f'<polyline points="{" ".join(points)}" fill="none" stroke="#166257" '
52
+ 'stroke-width="2.5" vector-effect="non-scaling-stroke"/>'
53
+ )
54
+ return (
55
+ '<details class="writing-review token-experiment"><summary>Experimental token curve</summary>'
56
+ '<p>The line shows the model’s estimate of how much remains unexplained after each token. '
57
+ 'Its height is in model units. The scale adjusts to this draft.</p>'
58
+ '<figure><svg class="signal-plot" viewBox="0 0 600 128" preserveAspectRatio="none" role="img" '
59
+ 'aria-label="Experimental unresolved signal by model token">'
60
+ '<path d="M2 2H598 M2 126H598" fill="none" stroke="#c5d0c9" vector-effect="non-scaling-stroke"/>'
61
+ f'{curve}</svg><div class="signal-axis"><span>Token 1</span><span>Token {len(tokens)}</span></div>'
62
+ f'<figcaption class="signal-caption">Vertical range: 0 to {peak:.4g} model units.</figcaption></figure>'
63
+ '<details><summary>Values at each token</summary><div class="signal-table" tabindex="0">'
64
+ '<table><thead><tr><th>Token</th><th>Text</th><th>Signal</th><th>Change</th></tr></thead>'
65
+ f'<tbody>{"".join(rows)}</tbody></table></div></details>'
66
+ '<p class="signal-caption">A peak has no established interpretation for an individual reader. '
67
+ 'In eight constructed tests with two open questions, the original curve correctly linked both '
68
+ 'questions to their answers in zero cases.</p></details>'
69
+ )
research/token_readout/extraction.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture exact causal Qwen token states and replay its final attention block."""
2
+
3
+ from contextlib import ExitStack, contextmanager
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from threading import RLock
7
+
8
+ import torch
9
+ from torch import nn
10
+
11
+ from research.backbone_transfer.extract import load_language_model
12
+
13
+
14
+ ATTENTION_LAYERS = (3, 7, 11, 15, 19, 23)
15
+ MID_LAYER = 11
16
+ QUERY_HEADS = 8
17
+ KEY_HEADS = 2
18
+ HEAD_WIDTH = 256
19
+ HIDDEN_WIDTH = 2048
20
+ VOCAB_SIZE = 248_320
21
+ MAX_TOKENS = 2048
22
+ _REGISTRY_LOCK = RLock()
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class TokenFeatures:
27
+ token_ids: tuple[int, ...]
28
+ offsets: tuple[tuple[int, int], ...]
29
+ hidden: torch.Tensor
30
+ mid: torch.Tensor
31
+ queries: torch.Tensor
32
+ keys: torch.Tensor
33
+ layer_input: torch.Tensor
34
+
35
+
36
+ def causal_attention_blocks(queries, keys, block_rows=32):
37
+ """Yield (first query index, weights[layer, head, row, key]).
38
+
39
+ Grouped query heads share their matching K head. The softmax includes the
40
+ complete visible prefix for each row, with future positions exactly zero.
41
+ Only a block of query rows is materialized at a time.
42
+ """
43
+ layers, heads, length, width = queries.shape
44
+ key_layers, key_heads, key_length, key_width = keys.shape
45
+ if (min(layers, heads, length, width, key_heads, block_rows) < 1 or heads % key_heads
46
+ or (key_layers, key_length, key_width) != (layers, length, width)
47
+ or queries.device != keys.device or queries.dtype != keys.dtype
48
+ or not queries.is_floating_point()):
49
+ raise ValueError("Invalid grouped causal Q/K geometry")
50
+ group_size = heads // key_heads
51
+ positions = torch.arange(length, device=queries.device)
52
+ grouped_keys = keys.float().transpose(-2, -1).unsqueeze(2)
53
+ for start in range(0, length, block_rows):
54
+ stop = min(length, start + block_rows)
55
+ query = queries[:, :, start:stop].float().reshape(layers, key_heads, group_size, stop - start, width)
56
+ scores = (query @ grouped_keys).reshape(layers, heads, stop - start, length) * width**-0.5
57
+ future = positions[None, :] > positions[start:stop, None]
58
+ yield start, scores.masked_fill(future, -torch.inf).softmax(dim=-1)
59
+
60
+
61
+ class LowRankUpdate(nn.Module):
62
+ def __init__(self, inputs, outputs, rank):
63
+ super().__init__()
64
+ self.down = nn.Linear(inputs, rank, bias=False)
65
+ self.up = nn.Linear(rank, outputs, bias=False)
66
+ nn.init.zeros_(self.up.weight)
67
+
68
+ def forward(self, value):
69
+ # LoRA alpha equals rank so the branch scale is one.
70
+ return self.up(self.down(value))
71
+
72
+
73
+ class AttentionAdapter(nn.Module):
74
+ def __init__(self, rank=4):
75
+ super().__init__()
76
+ if type(rank) is not int or not 0 < rank <= KEY_HEADS * HEAD_WIDTH:
77
+ raise ValueError("Adapter rank must be a positive integer within the K projection width")
78
+ self.query = LowRankUpdate(HIDDEN_WIDTH, QUERY_HEADS * HEAD_WIDTH, rank)
79
+ self.key = LowRankUpdate(HIDDEN_WIDTH, KEY_HEADS * HEAD_WIDTH, rank)
80
+
81
+ def query_hook(self, _module, inputs, output):
82
+ # Qwen interleaves Q and gate within each head, not across two global halves.
83
+ per_head = output.unflatten(-1, (QUERY_HEADS, HEAD_WIDTH * 2))
84
+ query, gate = per_head.chunk(2, dim=-1)
85
+ update = self.query(inputs[0]).unflatten(-1, (QUERY_HEADS, HEAD_WIDTH))
86
+ return torch.cat((query + update, gate), dim=-1).flatten(-2)
87
+
88
+ def key_hook(self, _module, inputs, output):
89
+ return output + self.key(inputs[0])
90
+
91
+
92
+ class _AttentionCapture:
93
+ def __init__(self, original, expected, length):
94
+ self.original = original
95
+ self.expected = expected
96
+ self.length = length
97
+ self.entries = {}
98
+ self.checked_mask = None
99
+
100
+ def __call__(self, module, query, key, value, attention_mask, **kwargs):
101
+ index = module.layer_idx
102
+ if index not in self.expected or index in self.entries:
103
+ raise RuntimeError(f"Unexpected Qwen attention capture at layer {index}")
104
+ if (query.shape != (1, QUERY_HEADS, self.length, HEAD_WIDTH)
105
+ or key.shape != (1, KEY_HEADS, self.length, HEAD_WIDTH)
106
+ or value.shape != key.shape or not module.is_causal or query.dtype != torch.float32
107
+ or key.dtype != torch.float32 or value.dtype != torch.float32
108
+ or kwargs.get("dropout", 0) != 0 or kwargs.get("is_causal") is False
109
+ or kwargs.get("position_bias") is not None or kwargs.get("scaling") != HEAD_WIDTH**-0.5):
110
+ raise ValueError("Capture requires the pinned unpadded FP32 causal Qwen attention path")
111
+ if attention_mask is not None and attention_mask is not self.checked_mask:
112
+ indices = torch.arange(self.length, device=query.device)
113
+ causal = indices[:, None] >= indices[None, :]
114
+ if attention_mask.shape != (1, 1, self.length, self.length):
115
+ raise ValueError("Unexpected full-attention mask shape for a single unpadded input")
116
+ mask = attention_mask[0, 0]
117
+ if mask.dtype == torch.bool:
118
+ valid = torch.equal(mask, causal)
119
+ elif mask.is_floating_point():
120
+ valid = bool((mask[causal] == 0).all() and (mask[~causal] <= -1e8).all())
121
+ else:
122
+ valid = False
123
+ if not valid:
124
+ raise ValueError("The original attention mask differs from the complete causal prefix")
125
+ self.checked_mask = attention_mask
126
+ result = self.original(module, query, key, value, attention_mask, **kwargs)
127
+ self.entries[index] = (query[0], key[0])
128
+ return result
129
+
130
+
131
+ @contextmanager
132
+ def _capture(expected, length):
133
+ from transformers.models.qwen3_5 import modeling_qwen3_5
134
+
135
+ # Transformers resolves the SDPA interface in this module. Serialize only
136
+ # its scoped substitution and restore it even when the model raises.
137
+ with _REGISTRY_LOCK:
138
+ original = modeling_qwen3_5.ALL_ATTENTION_FUNCTIONS
139
+ capture = _AttentionCapture(original["sdpa"], expected, length)
140
+ registry = type(original)()
141
+ registry["sdpa"] = capture
142
+ modeling_qwen3_5.ALL_ATTENTION_FUNCTIONS = registry
143
+ try:
144
+ yield capture.entries
145
+ if tuple(capture.entries) != expected:
146
+ raise RuntimeError(f"Incomplete Qwen attention capture: {tuple(capture.entries)}")
147
+ finally:
148
+ modeling_qwen3_5.ALL_ATTENTION_FUNCTIONS = original
149
+
150
+
151
+ def _return_tokens(tensors):
152
+ return tuple(tensor.detach().clone() for tensor in tensors)
153
+
154
+
155
+ class QwenRuntime:
156
+ def __init__(self, encoder, tokenizer, revision):
157
+ layers = encoder.layers
158
+ attention = tuple(i for i, layer in enumerate(layers) if layer.block_type == "full_attention")
159
+ if (len(layers) != 24 or attention != ATTENTION_LAYERS
160
+ or encoder.config._attn_implementation != "sdpa" or encoder.training):
161
+ raise ValueError("Unexpected Qwen3.5-2B decoder architecture or attention backend")
162
+ self.encoder = encoder
163
+ self.tokenizer = tokenizer
164
+ self.revision = revision
165
+ self.last = layers[-1]
166
+ self.device = next(encoder.parameters()).device
167
+
168
+ @classmethod
169
+ def load(cls, snapshot):
170
+ import transformers
171
+ from tokenizers import Tokenizer
172
+
173
+ snapshot = Path(snapshot)
174
+ encoder, spec = load_language_model(snapshot, "qwen", torch, transformers)
175
+ tokenizer = Tokenizer.from_file(str(snapshot / "tokenizer.json"))
176
+ return cls(encoder, tokenizer, spec["revision"])
177
+
178
+ def new_adapter(self, rank=4):
179
+ return AttentionAdapter(rank).to(device=self.device, dtype=torch.float32)
180
+
181
+ def _install_adapter(self, stack, adapter):
182
+ if adapter is not None:
183
+ attention = self.last.self_attn
184
+ stack.enter_context(attention.q_proj.register_forward_hook(adapter.query_hook))
185
+ stack.enter_context(attention.k_proj.register_forward_hook(adapter.key_hook))
186
+
187
+ def encode(self, text, adapter=None):
188
+ if type(text) is not str or not text.strip():
189
+ raise ValueError("Provide nonempty original text")
190
+ tokens = self.tokenizer.encode(text, add_special_tokens=False)
191
+ if any(not 0 <= begin <= end <= len(text) for begin, end in tokens.offsets):
192
+ raise ValueError("Tokenizer offsets fall outside the original Unicode text")
193
+ return self.encode_tokens(tokens.ids, tokens.offsets, adapter)
194
+
195
+ def encode_tokens(self, token_ids, offsets, adapter=None):
196
+ token_ids = tuple(token_ids)
197
+ offsets = tuple(tuple(span) for span in offsets)
198
+ length = len(token_ids)
199
+ if (not 1 <= length <= MAX_TOKENS or len(offsets) != length
200
+ or any(type(token) is not int or not 0 <= token < VOCAB_SIZE for token in token_ids)
201
+ or any(len(span) != 2 or not 0 <= span[0] <= span[1] for span in offsets)):
202
+ raise ValueError(f"Expected one unpadded 1–{MAX_TOKENS} token input with exact offsets")
203
+ input_ids = torch.tensor([token_ids], device=self.device, dtype=torch.long)
204
+ stages = {}
205
+
206
+ def save_mid(_module, _inputs, output):
207
+ stages["mid"] = output[0]
208
+
209
+ def save_last_input(_module, inputs):
210
+ stages["last_input"] = inputs[0][0]
211
+
212
+ with _capture(ATTENTION_LAYERS, length) as recorded, ExitStack() as handles:
213
+ handles.enter_context(self.encoder.layers[MID_LAYER].register_forward_hook(save_mid))
214
+ handles.enter_context(self.last.register_forward_pre_hook(save_last_input))
215
+ self._install_adapter(handles, adapter)
216
+ with torch.inference_mode():
217
+ final = self.encoder(input_ids=input_ids, use_cache=False, output_attentions=False,
218
+ output_hidden_states=False).last_hidden_state[0]
219
+ # Materialize ordinary tensors outside inference_mode so the cached
220
+ # block input and frozen features can be used in later autograd.
221
+ hidden, mid, layer_input = _return_tokens((final, stages["mid"], stages["last_input"]))
222
+ queries = torch.stack([recorded[index][0] for index in ATTENTION_LAYERS])
223
+ keys = torch.stack([recorded[index][1] for index in ATTENTION_LAYERS])
224
+ if (any(tensor.shape != (length, HIDDEN_WIDTH) or tensor.dtype != torch.float32
225
+ for tensor in (hidden, mid, layer_input))
226
+ or not all(bool(torch.isfinite(tensor).all()) for tensor in (hidden, mid, layer_input, queries, keys))):
227
+ raise RuntimeError("Nonfinite or malformed all-position Qwen features")
228
+ return TokenFeatures(token_ids, offsets, hidden, mid, queries, keys, layer_input)
229
+
230
+ def replay_last(self, layer_input, adapter):
231
+ """Run the original last block and norm with differentiable Q/K updates."""
232
+ if (layer_input.ndim != 2 or layer_input.shape[1] != HIDDEN_WIDTH
233
+ or not 1 <= layer_input.shape[0] <= MAX_TOKENS or layer_input.device != self.device
234
+ or layer_input.dtype != torch.float32 or layer_input.is_inference()):
235
+ raise ValueError("Expected ordinary FP32 cached Qwen layer-24 inputs on the runtime device")
236
+ length = layer_input.shape[0]
237
+ text_positions = torch.arange(length, device=self.device).unsqueeze(0)
238
+ rotary_positions = text_positions.unsqueeze(0).expand(3, -1, -1)
239
+ layer_input = layer_input.unsqueeze(0)
240
+ rotary = self.encoder.rotary_emb(layer_input, rotary_positions)
241
+ with _capture((ATTENTION_LAYERS[-1],), length) as recorded, ExitStack() as handles:
242
+ self._install_adapter(handles, adapter)
243
+ result = self.last(layer_input, position_embeddings=rotary, position_ids=text_positions,
244
+ attention_mask=None, past_key_values=None, use_cache=False)
245
+ hidden = self.encoder.norm(result)[0]
246
+ query, key = recorded[ATTENTION_LAYERS[-1]]
247
+ return hidden, query, key
248
+
249
+ def validate(self, text):
250
+ """Probe no-op replay, exact token coverage and suffix-causal features."""
251
+ original = self.encode(text)
252
+ if len(original.token_ids) < 4:
253
+ raise ValueError("Validation requires at least four input tokens")
254
+ with torch.no_grad():
255
+ replay = self.replay_last(original.layer_input, self.new_adapter())
256
+ prefix = len(original.token_ids) // 2
257
+ shortened = self.encode_tokens(original.token_ids[:prefix], original.offsets[:prefix])
258
+ changed_tokens = original.token_ids[:prefix] + tuple(
259
+ (token + 1) % VOCAB_SIZE for token in original.token_ids[prefix:]
260
+ )
261
+ changed = self.encode_tokens(changed_tokens, original.offsets)
262
+
263
+ def relative_rms(left, right):
264
+ difference = (left - right).square().mean().sqrt()
265
+ return float(difference / left.square().mean().sqrt().clamp_min(1e-8))
266
+
267
+ def compare(expected, actual):
268
+ return dict(zip(("hidden", "mid", "q", "k", "layer_input"),
269
+ (relative_rms(left, right) for left, right in zip(expected, actual, strict=True)),
270
+ strict=True))
271
+
272
+ def prefix_features(value):
273
+ return (value.hidden[:prefix], value.mid[:prefix], value.queries[:, :, :prefix],
274
+ value.keys[:, :, :prefix], value.layer_input[:prefix])
275
+
276
+ replay_errors = {
277
+ name: relative_rms(left, right)
278
+ for name, left, right in zip(("hidden", "q", "k"),
279
+ (original.hidden, original.queries[-1], original.keys[-1]), replay,
280
+ strict=True)
281
+ }
282
+ comparisons = {"no_op_replay": replay_errors,
283
+ "truncation": compare(prefix_features(original), prefix_features(shortened)),
284
+ "suffix_replacement": compare(prefix_features(original), prefix_features(changed))}
285
+ if any(not 0 <= value <= 1e-3 for data in comparisons.values() for value in data.values()):
286
+ raise RuntimeError(f"Qwen replay or causal-prefix control failed: {comparisons}")
287
+ return {"tokens": len(original.token_ids), "common_prefix": prefix, "relative_rms": comparisons}
research/token_readout/learner_view.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Display learner word reports for the single sentence used by the observation model."""
2
+
3
+ import re
4
+ from html import escape
5
+ from math import isfinite
6
+ from unicodedata import name
7
+
8
+ from research.reading_validation.local_forecast import WORD
9
+ from research.token_readout.app import source_html
10
+
11
+ LEVELS = ("A1", "A2", "B1", "B2", "C1", "C2")
12
+ POOLED = "unspecified"
13
+ EXAMPLE = "The translucent membrane allows light to pass through."
14
+ TITLE = "Which words might an English learner need help with?"
15
+ STOP = re.compile(r"""[.!?]+['"’”)]*(?=\s+\S)""")
16
+ ABBR = re.compile(
17
+ r"(?:\b(?:mr|mrs|ms|dr|prof|jr|sr|vs|e\.g|i\.e)|(?:\b[A-Za-z]\.)+[A-Za-z]|\b[A-Z])\.$",
18
+ re.I,
19
+ )
20
+ STYLE = """
21
+ .learner-result {background:#f8faf7;border:1px solid #cbd7cf;border-radius:.65rem;padding:1rem 1.2rem;}
22
+ .learner-result p,.learner-result .learner-draft {color:#24372e!important;}
23
+ .learner-result p {margin:0 0 .45rem;font-size:.9rem;}
24
+ .learner-result .learner-draft {white-space:pre-wrap;overflow-wrap:anywhere;line-height:3.1;font-size:1.13rem;margin-top:.8rem}
25
+ .learner-result .learner-word {display:inline-block;position:relative;line-height:1.45;min-width:1.35em;
26
+ background:var(--learner-word-color);border-bottom:2px solid #889c8a;border-radius:.16rem;color:#20352a!important;}
27
+ .learner-result .learner-word::before {content:attr(data-rate);position:absolute;left:0;bottom:100%;white-space:nowrap;
28
+ color:#3c5749;font-size:.62em;line-height:1.2;font-weight:650;font-variant-numeric:tabular-nums;}
29
+ .learner-result .high-word {border-bottom:3px solid #ac5f28;}
30
+ """
31
+
32
+
33
+ def validate_sentence(text):
34
+ if not isinstance(text, str) or not text.strip():
35
+ raise ValueError("Enter one English sentence to check its words.")
36
+ letters = [c for c in text if c.isalpha()]
37
+ if not letters or sum("LATIN" in name(c, "") for c in letters) / len(letters) < 0.8:
38
+ raise ValueError(
39
+ "This learner check was trained on English. Enter one English sentence."
40
+ )
41
+ if any(not ABBR.search(text[: m.end()]) for m in STOP.finditer(text)) or re.search(
42
+ r"\n[ \t]*\n\s*\S", text.strip()
43
+ ):
44
+ raise ValueError("Enter one sentence. Use Review draft above for a passage.")
45
+
46
+
47
+ def display(record, level=POOLED):
48
+ if level not in (POOLED, *LEVELS):
49
+ raise ValueError("Choose a listed CEFR level or use the full learner group.")
50
+ if record["schema"] != "nns-self-report-en-v1":
51
+ raise ValueError("The learner result has an unexpected model identity.")
52
+ text = record["text"]
53
+ scores = record["probabilities"][level]
54
+ spans = record["positions"]
55
+ if not spans or len(spans) != len(scores) or record["word_count"] < len(spans):
56
+ raise ValueError(
57
+ "There are no scorable learner word results for this sentence."
58
+ )
59
+ pieces = []
60
+ left = 0
61
+ for (a, b), p in zip(spans, scores, strict=True):
62
+ if (
63
+ type(a) is not int
64
+ or type(b) is not int
65
+ or not left <= a < b <= len(text)
66
+ or not WORD.fullmatch(text[a:b])
67
+ or not isfinite(p)
68
+ or not 0 <= p <= 1
69
+ ):
70
+ raise ValueError("A learner score differs from its printed word.")
71
+ prob = "<1%" if 0 < p < 0.005 else f"{p:.0%}"
72
+ label = escape(
73
+ f"{text[a:b]} · estimated fraction who would mark this word as unknown: {prob}",
74
+ quote=True,
75
+ )
76
+ shade = tuple(
77
+ round(x + (y - x) * (p**0.5))
78
+ for x, y in zip((240, 245, 236), (225, 140, 69), strict=True)
79
+ )
80
+ color = "#" + "".join(f"{x:02x}" for x in shade)
81
+ pieces.extend(
82
+ [
83
+ source_html(text[left:a]),
84
+ f'<span class="learner-word{" high-word" if p >= 0.25 else ""}" style="--learner-word-color:{color}" '
85
+ f'data-start="{a}" data-end="{b}" data-rate="{escape(prob, quote=True)}" '
86
+ f'title="{label}" aria-label="{label}">{source_html(text[a:b])}</span>',
87
+ ]
88
+ )
89
+ left = b
90
+ pieces.append(source_html(text[left:]))
91
+ group = (
92
+ "all English learners in the study"
93
+ if level == POOLED
94
+ else f"English learners at {level}"
95
+ )
96
+ missing = record["word_count"] - len(spans)
97
+ coverage = (
98
+ f" {missing} {'word has' if missing == 1 else 'words have'} no score."
99
+ if missing
100
+ else ""
101
+ )
102
+ return (
103
+ f'<section class="learner-result" data-model="{escape(record["checkpoint_sha256"], quote=True)}">'
104
+ f"<p><strong>Estimated share who would mark each word as unknown</strong> · {group}.</p>"
105
+ f"<p>Warmer colors indicate a higher chance. For example, 20% means about one in five learners.{coverage}</p>"
106
+ f'<div class="learner-draft" aria-label="Original learner sentence">{"".join(pieces)}</div></section>'
107
+ )
108
+
109
+
110
+ def add_learner_check(runner):
111
+ import gradio as gr
112
+
113
+ with gr.Accordion(TITLE, open=False):
114
+ gr.Markdown(
115
+ "Check one English sentence against learners’ own reports of words they did not understand."
116
+ )
117
+ text = gr.Textbox(label="English sentence", placeholder=EXAMPLE, lines=2)
118
+ level = gr.Dropdown(
119
+ label="Learner’s measured English level (CEFR)",
120
+ choices=[("No level supplied", POOLED), *[(k, k) for k in LEVELS]],
121
+ value=POOLED,
122
+ )
123
+ button = gr.Button("Check learner vocabulary", variant="secondary")
124
+ result = gr.HTML()
125
+ state = gr.State()
126
+
127
+ def submit(sentence, measured):
128
+ try:
129
+ if measured not in (POOLED, *LEVELS):
130
+ raise ValueError(
131
+ "Choose a listed CEFR level or use the full learner group."
132
+ )
133
+ packet = runner.learner_sentence(sentence)
134
+ return packet, display(packet, measured)
135
+ except ValueError as error:
136
+ raise gr.Error(escape(str(error))) from error
137
+
138
+ def change(measured, sentence, record):
139
+ return (
140
+ display(record, measured) if record and record["text"] == sentence else ""
141
+ )
142
+
143
+ button.click(
144
+ submit,
145
+ [text, level],
146
+ [state, result],
147
+ api_name="learner_vocabulary",
148
+ concurrency_limit=1,
149
+ )
150
+ level.input(
151
+ change, [level, text, state], result, api_name=False, show_progress="hidden"
152
+ )
153
+ text.input(
154
+ lambda: (None, ""),
155
+ outputs=[state, result],
156
+ api_name=False,
157
+ show_progress="hidden",
158
+ )
research/token_readout/model.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Causal token readout and observation likelihoods for one Qwen pass."""
2
+
3
+ from dataclasses import dataclass
4
+ from math import log, sqrt
5
+
6
+ import torch
7
+ from torch import Tensor, nn
8
+ from torch.nn import functional as F
9
+
10
+ from research.token_readout.extraction import causal_attention_blocks
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Scores:
15
+ opening: Tensor
16
+ resolution: Tensor
17
+ continuity: Tensor
18
+
19
+
20
+ class TokenReadout(nn.Module):
21
+ def __init__(self, input_width=2048, readout_width=48, attention_heads=48):
22
+ super().__init__()
23
+ self.final = nn.Linear(input_width, readout_width, bias=False)
24
+ self.middle = nn.Linear(input_width, readout_width, bias=False)
25
+ self.attention_mix = nn.Linear(readout_width, attention_heads)
26
+ self.observation = nn.Linear(readout_width * 3, 1)
27
+ self.query = nn.Linear(readout_width * 3, readout_width, bias=False)
28
+ self.key = nn.Linear(readout_width, readout_width, bias=False)
29
+ self.resolve_bias = nn.Parameter(torch.zeros(()))
30
+ self.attention_weight = nn.Parameter(torch.zeros(()))
31
+ nn.init.zeros_(self.observation.weight)
32
+ nn.init.zeros_(self.observation.bias)
33
+ nn.init.zeros_(self.attention_mix.weight)
34
+ nn.init.zeros_(self.attention_mix.bias)
35
+ nn.init.normal_(self.query.weight, std=0.015)
36
+
37
+ def forward(self, features) -> Scores:
38
+ hidden = features.hidden.float()
39
+ middle = features.mid.float()
40
+ state = self.final(F.layer_norm(hidden, hidden.shape[-1:]))
41
+ state = state + self.middle(F.layer_norm(middle, middle.shape[-1:]))
42
+ state = F.layer_norm(state, state.shape[-1:])
43
+ previous = torch.cat((state[:1], state[:-1]))
44
+ change = state - previous
45
+ mix = self.attention_mix(state).softmax(-1)
46
+ source = self.key(state)
47
+ event, resolution, continuity = [], [], []
48
+ positions = torch.arange(len(state), device=state.device)
49
+ for start, block in causal_attention_blocks(features.queries, features.keys):
50
+ evidence = block.flatten(0, 1).transpose(0, 1).float()
51
+ length = len(evidence)
52
+ end = start + length
53
+ native = torch.einsum('rh,rht->rt', mix[start:end], evidence)
54
+ earlier = positions[None, :] < positions[start:end, None]
55
+ # Only strictly earlier positions contribute to the context summary.
56
+ previous_mass = native * earlier
57
+ previous_context = (previous_mass @ state) / previous_mass.sum(dim=-1, keepdim=True).clamp_min(1e-6)
58
+ representation = torch.cat((state[start:end], change[start:end], previous_context), dim=-1)
59
+ event.append(self.observation(representation).squeeze(-1))
60
+ semantic = self.query(representation) @ source.T / sqrt(source.shape[-1])
61
+ # Attend over cues at any prior distance. The uniform reference removes the basic prefix-length scale.
62
+ relative_mass = (native * (positions[start:end, None] + 1)).clamp_min(1e-8).log()
63
+ resolution.append(semantic + self.attention_weight * relative_mass + self.resolve_bias)
64
+ continuity.append(F.cosine_similarity(state[start:end], previous_context, dim=-1))
65
+ return Scores(torch.cat(event), torch.cat(resolution), torch.cat(continuity))
66
+
67
+
68
+ def intervals(offsets, start, end) -> tuple[int, int]:
69
+ matching = [index for index, (left, right) in enumerate(offsets)
70
+ if right > left and left < end and right > start]
71
+ if (not matching or offsets[matching[-1]][1] != end
72
+ or matching != list(range(matching[0], matching[-1] + 1))
73
+ or offsets[matching[0]][0] > start):
74
+ raise ValueError(f'Observation [{start}, {end}) does not end on a certified token boundary')
75
+ return matching[0], matching[-1] + 1
76
+
77
+
78
+ def phase_first_event(sentence_logits: Tensor) -> Tensor:
79
+ no_report = F.logsigmoid(-sentence_logits).cumsum(0)
80
+ survival = torch.cat((no_report.new_zeros(1), no_report))
81
+ return torch.cat((survival[:-1] + F.logsigmoid(sentence_logits), survival[-1:]))
82
+
83
+
84
+ def first_report_logits(scores, spans, prior) -> Tensor:
85
+ residual = torch.stack([torch.logsumexp(scores[start:end], dim=0) - log(end - start) for start, end in spans])
86
+ return residual + prior
87
+
88
+
89
+ def first_report_nll(logits, counts) -> Tensor:
90
+ mass = phase_first_event(logits)
91
+ return -(counts * mass).sum() / counts.sum()
92
+
93
+
94
+ def interval_nll(logits: Tensor, risk_start: int, start: int, end: int) -> Tensor:
95
+ """Negative log mass of first activation in [start, end), conditional on risk start."""
96
+ if not 0 <= risk_start <= start < end <= len(logits):
97
+ raise ValueError('Invalid first-hit time window')
98
+ before = F.softplus(logits[risk_start:start]).sum()
99
+ inside = F.softplus(logits[start:end]).sum().clamp_min(torch.finfo(logits.dtype).tiny)
100
+ return before - torch.log(-torch.expm1(-inside))
101
+
102
+
103
+ def censored_nll(logits: Tensor, risk_start: int, end: int) -> Tensor:
104
+ if not 0 <= risk_start < end <= len(logits):
105
+ raise ValueError('Invalid right-censoring time window')
106
+ return F.softplus(logits[risk_start:end]).sum()
107
+
108
+
109
+ def matched_effect(logits, chances) -> Tensor:
110
+ """Calibrate the contrast of observed reports at the identical target sentence."""
111
+ return F.smooth_l1_loss(logits[1].sigmoid() - logits[0].sigmoid(), chances[1] - chances[0], beta=0.1)
112
+
113
+
114
+ def question_mass(opening_logits, resolution_logits, candidates=None):
115
+ """Expected unresolved candidates and causal resolution mass by token and anchor."""
116
+ n = len(opening_logits)
117
+ positions = torch.arange(n, device=opening_logits.device)
118
+ visible = positions[:, None] >= positions
119
+ earlier = positions[:, None] > positions
120
+ opening = opening_logits.sigmoid()
121
+ if candidates is not None:
122
+ opening = opening * candidates
123
+ keep = F.logsigmoid(-resolution_logits).masked_fill(~earlier, 0.0)
124
+ survival = keep.cumsum(0)
125
+ unresolved = survival.exp() * opening[None, :] * visible
126
+ resolved = (survival - keep).exp() * opening[None, :] * resolution_logits.sigmoid() * earlier
127
+ return opening, unresolved, resolved
research/token_readout/physical_view.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Show the two original sentences implicated by a short physical story."""
2
+
3
+ from html import escape
4
+ from math import isfinite
5
+
6
+ EXAMPLE = ("Mina filled a glass bottle with water. She sealed the bottle and placed it in the freezer. "
7
+ "The water inside froze overnight. Mina took the bottle out and set it on the counter. "
8
+ "Without warming it, she immediately poured the water into a cup.")
9
+
10
+
11
+ def render(text, reading):
12
+ if reading["scope"] != "authored_physical_conflict":
13
+ raise ValueError("The physical-story display needs the fitted consistency observer.")
14
+ spans = [tuple(v) for v in reading["sentences"]]
15
+ events = reading["observations"]
16
+ if len(events)!=len(spans)-1 or len(spans)<2:
17
+ raise ValueError("The reading does not cover every sentence transition.")
18
+ choices=[];total=0.
19
+ for j,r in enumerate(events,1):
20
+ p=r["source_probabilities"]
21
+ if (r["sentence"]!=j or (r["start"],r["end"])!=spans[j] or len(p)!=j or
22
+ any(not isfinite(v) or not 0<=v<=1. for v in p) or
23
+ abs(sum(p)-r["first_conflict_probability"])>1e-5):
24
+ raise ValueError("A physical transition lost its earlier source or normalized probability.")
25
+ total+=sum(p)
26
+ choices.extend((v,i,j) for i,v in enumerate(p))
27
+ if abs(total-reading["probability_any"])>1e-5:
28
+ raise ValueError("Candidate pairs disagree with the whole-story probability.")
29
+ _,i,j=max(choices,key=lambda row:row[0])
30
+ if reading["review"]:
31
+ intro=(f'<p>Compare <strong>sentence {i+1}</strong> (earlier action) with '
32
+ f'<strong>sentence {j+1}</strong> (possible conflict). This pair ranked highest in the story.</p>')
33
+ else:
34
+ intro='<p>The model did not flag a pair in this story at its development threshold.</p>'
35
+ chunks=[];last=0
36
+ for k,(a,b) in enumerate(spans):
37
+ if not last<=a<b<=len(text):
38
+ raise ValueError("Sentence boundaries differ from the original story.")
39
+ chunks.append(escape(text[last:a]))
40
+ original=escape(text[a:b])
41
+ if reading["review"] and k in (i,j):
42
+ role="earlier" if k==i else "conflict"
43
+ title="Earlier action" if k==i else "Possible conflict"
44
+ original=f'<mark class="physical-{role}" title="{title}" data-start="{a}" data-end="{b}">{original}</mark>'
45
+ chunks.append(original);last=b
46
+ chunks.append(escape(text[last:]))
47
+ return ('<section class="physical-review" aria-label="Physical continuity">'+intro+
48
+ '<div class="physical-draft" aria-label="Original story">'+''.join(chunks)+'</div></section>')
49
+
50
+
51
+ STYLE="""
52
+ .physical-review {background:#f8faf7; border:1px solid #b4c4bb; border-radius:.6rem; padding:1rem; color:#23352f!important;}
53
+ .physical-review p,.physical-review strong,.physical-review .physical-draft {color:#23352f!important;}
54
+ .physical-draft {white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.8;}
55
+ .physical-draft mark {color:#1d302a!important;padding:.08em 0;box-decoration-break:clone;}
56
+ .physical-earlier {background:#c7e3df!important;box-shadow:inset 0 -.12em #347065;}
57
+ .physical-conflict {background:#f7d9b9!important;outline:1px dashed #8a4726;}
58
+ """
59
+
60
+
61
+ def add_physical_check(runner):
62
+ import gradio as gr
63
+ with gr.Accordion("Do two events in a short story conflict?",open=False):
64
+ gr.Markdown("Paste five to seven sentences about everyday physical actions. "
65
+ "The model looks for a later action that conflicts with an earlier one.")
66
+ story=gr.Textbox(label="Short physical story",lines=5)
67
+ with gr.Row():
68
+ submit=gr.Button("Compare events",variant="primary")
69
+ example=gr.Button("Load a physical story")
70
+ result=gr.HTML()
71
+ def review(text):
72
+ if not isinstance(text,str) or not text.strip():
73
+ raise gr.Error("Enter a short physical story.")
74
+ try:
75
+ return render(text,runner.physical_story(text))
76
+ except ValueError as error:
77
+ raise gr.Error(escape(str(error))) from error
78
+ submit.click(review,inputs=story,outputs=result,api_name="physical_story",concurrency_limit=1)
79
+ example.click(lambda:(EXAMPLE,""),outputs=[story,result],api_name=False,show_progress="hidden")
research/token_readout/portable_runner.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio factory for fitted portable CogLLM checkpoints."""
2
+
3
+ from math import isfinite
4
+ from pathlib import Path
5
+
6
+ import torch
7
+
8
+ from research.backbone_transfer.extract import digest
9
+ from research.token_readout.backbone import Backbone
10
+ from research.token_readout.readout import PortableReadout
11
+ from research.token_readout.runner import TokenRunner
12
+ from research.token_readout.transfer_fit import CHECKPOINT_SCHEMA, DEFAULT_SCALE
13
+
14
+
15
+ def load(*, model: Path, checkpoint: Path, english_head=None, transition_head=None, narrative_head=None,
16
+ terminology_head=None, serving_device=None):
17
+ identity = digest(checkpoint)
18
+ packet = torch.load(checkpoint, map_location='cpu', weights_only=True)
19
+ fields = {'schema', 'candidate', 'revision', 'variant', 'relations', 'reader', 'priors', 'scale'}
20
+ if not isinstance(packet, dict) or packet.keys() != fields or packet['schema'] != CHECKPOINT_SCHEMA:
21
+ raise ValueError('Expected a portable readout checkpoint with an identified backbone and variant')
22
+ if (packet['candidate'] not in ('qwen', 'lfm3', 'gemma4') or packet['variant'] not in ('point', 'span')
23
+ or type(packet['relations']) is not bool):
24
+ raise ValueError('Checkpoint identifies an unsupported text backbone or readout')
25
+ scale = packet['scale']
26
+ priors = packet['priors']
27
+ if (not isinstance(scale, dict) or scale.keys() != DEFAULT_SCALE.keys()
28
+ or any(type(value) not in (int, float) or not isfinite(value) for value in scale.values())
29
+ or min(scale['opening_gain'], scale['resolution_gain']) <= 0
30
+ or not isinstance(priors, dict) or any(type(priors.get(key)) not in (int, float) or not isfinite(priors[key])
31
+ for key in ('opening', 'resolution'))):
32
+ raise ValueError('Checkpoint calibration must provide finite priors and positive gains')
33
+ if (english_head is None) != (transition_head is None):
34
+ raise ValueError('Writing review requires both the wording and coherence readouts.')
35
+ if english_head is not None:
36
+ from research.reading_validation.transition_inference import CHECKPOINT
37
+ if identity != CHECKPOINT:
38
+ raise ValueError('The writing readouts require the validated Qwen token checkpoint.')
39
+ runtime = Backbone.load(packet['candidate'], model, native_attention=packet['relations'], serving_device=serving_device)
40
+ if runtime.revision != packet['revision']:
41
+ raise ValueError('Readout weights belong to another model revision')
42
+ if english_head is not None:
43
+ from research.reading_validation.local_inference import REVISION
44
+ if packet['candidate'] != 'qwen' or runtime.revision != REVISION:
45
+ raise ValueError('English writing review requires the Qwen revision used to train the head.')
46
+ reader = PortableReadout(runtime.width, packet['variant'], packet['relations']).to(runtime.device)
47
+ reader.load_state_dict(packet['reader'], strict=True)
48
+ reader.eval().requires_grad_(False)
49
+ return TokenRunner(runtime, reader, None, priors, identity, scale=scale, anchor_width=reader.anchor_tokens,
50
+ english_head=english_head, transition_head=transition_head, narrative_head=narrative_head,
51
+ terminology_head=terminology_head)
research/token_readout/readout.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Causal point and span readouts over frozen token features."""
2
+
3
+ from math import log, sqrt
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ from research.token_readout.model import Scores
10
+
11
+
12
+ PROJECTION_BUDGET = 196_608
13
+ MATCH_WIDTH = 32
14
+ SPAN_TOKENS = 4
15
+
16
+
17
+ class PortableReadout(nn.Module):
18
+ """Score opening and link resolution for all token positions at once.
19
+
20
+ Each column corresponds to an anchor ending at that token. The span
21
+ variant reads the preceding tokens as part of the anchor and can match it
22
+ to a cue anywhere later in the document. Native relation inputs contain
23
+ mean and maximum global attention as log1p(relative to uniform) - log(2).
24
+ """
25
+
26
+ def __init__(self, input_width, variant='point', relations=True):
27
+ super().__init__()
28
+ if type(input_width) is not int or input_width <= 0:
29
+ raise ValueError('The backbone must provide a positive integer hidden width')
30
+ if variant not in ('point', 'span') or type(relations) is not bool:
31
+ raise ValueError('Specify a point or span readout and whether to use native relations')
32
+ self.input_width = input_width
33
+ self.variant = variant
34
+ self.use_relations = relations
35
+ self.anchor_tokens = SPAN_TOKENS if variant == 'span' else 1
36
+
37
+ # Keep the input projection budget approximately constant across the
38
+ # tested hidden widths. The pairwise match width is identical.
39
+ width = max(8, min(64, PROJECTION_BUDGET // (2 * input_width)))
40
+ self.final = nn.Linear(input_width, width, bias=False)
41
+ self.middle = nn.Linear(input_width, width, bias=False)
42
+ self.opening = nn.Linear(3 * width, 1)
43
+ self.query = nn.Linear(3 * width, MATCH_WIDTH, bias=False)
44
+ self.key = nn.Linear(width, MATCH_WIDTH, bias=False)
45
+ self.resolve_bias = nn.Parameter(torch.zeros(()))
46
+ if relations:
47
+ self.relation_weight = nn.Parameter(torch.zeros(2))
48
+ nn.init.zeros_(self.opening.weight)
49
+ nn.init.zeros_(self.opening.bias)
50
+
51
+ if variant == 'span':
52
+ self.span_weight = nn.Linear(width, 1, bias=False)
53
+ self.span_position_bias = nn.Parameter(torch.zeros(SPAN_TOKENS))
54
+ self.interaction_query = nn.Linear(3 * width, MATCH_WIDTH, bias=False)
55
+ self.interaction_key = nn.Linear(width, MATCH_WIDTH, bias=False)
56
+ self.interaction_gain = nn.Parameter(torch.zeros(()))
57
+
58
+ def _anchor_spans(self, state, positions):
59
+ """Represent a short preceding window at each anchor endpoint."""
60
+ if self.variant == 'point':
61
+ return state
62
+ span_states = F.pad(state, (0, 0, SPAN_TOKENS - 1, 0)).unfold(0, SPAN_TOKENS, 1).transpose(1, 2)
63
+ span_indices = positions[:, None] + positions.new_tensor(range(1 - SPAN_TOKENS, 1))
64
+ logits = self.span_weight(span_states).squeeze(-1) + self.span_position_bias
65
+ weights = logits.masked_fill(span_indices < 0, -torch.inf).softmax(-1)
66
+ pooled = (span_states * weights.unsqueeze(-1)).sum(1)
67
+ return F.layer_norm(state + pooled, state.shape[-1:])
68
+
69
+ def _history(self, state, relations, earlier, positions):
70
+ if self.use_relations:
71
+ weights = (relations[..., 0] + log(2)).expm1().clamp_min(0).masked_fill(~earlier, 0)
72
+ return (weights @ state) / weights.sum(dim=-1, keepdim=True).clamp_min(1e-6)
73
+ before = torch.cat((torch.zeros_like(state[:1]), state[:-1]), dim=0).cumsum(dim=0)
74
+ return before / positions[:, None].clamp_min(1)
75
+
76
+ def project(self, features):
77
+ hidden, middle = features.hidden, features.mid
78
+ if (hidden.ndim != 2 or len(hidden) == 0 or hidden.shape[1] != self.input_width
79
+ or middle.shape != hidden.shape or middle.device != hidden.device
80
+ or len(features.offsets) != len(hidden)):
81
+ raise ValueError('The token-aligned backbone features do not match the readout width')
82
+
83
+ return (self.final(F.layer_norm(hidden.float(), hidden.shape[-1:])),
84
+ self.middle(F.layer_norm(middle.float(), middle.shape[-1:])))
85
+
86
+ def score_projected(self, final, middle, native) -> Scores:
87
+ if (final.ndim != 2 or len(final) == 0 or final.shape[1] != self.final.out_features
88
+ or middle.shape != final.shape or middle.device != final.device):
89
+ raise ValueError('Projected final and middle states must follow the same token axis')
90
+ if self.use_relations and (native is None or native.shape != (len(final), len(final), 2)
91
+ or native.device != final.device or not native.is_floating_point()):
92
+ raise ValueError('Native relations must have two channels on the aligned token axes')
93
+ state = F.layer_norm(final + middle, final.shape[-1:])
94
+ previous = torch.cat((state[:1], state[:-1]), dim=0)
95
+ positions = torch.arange(len(state), device=state.device)
96
+ earlier = positions[:, None] > positions[None, :]
97
+ relations = native.float() if self.use_relations else None
98
+ history = self._history(state, relations, earlier, positions)
99
+ cue = torch.cat((state, state - previous, history), dim=-1)
100
+ anchors = self._anchor_spans(state, positions)
101
+
102
+ # Two matrix products avoid an all-pairs tensor with a hidden axis.
103
+ scale = 1 / sqrt(MATCH_WIDTH)
104
+ resolution = (self.query(cue) @ self.key(anchors).T) * scale
105
+ relation_shift = relations @ self.relation_weight if self.use_relations else 0.0
106
+ resolution = resolution + relation_shift + self.resolve_bias
107
+ if self.variant == 'span':
108
+ interaction = (self.interaction_query(cue) @ self.interaction_key(anchors).T) * scale
109
+ resolution = resolution + self.interaction_gain * F.silu(interaction + relation_shift)
110
+ resolution = resolution.masked_fill(~earlier, torch.finfo(resolution.dtype).min)
111
+
112
+ return Scores(self.opening(cue).squeeze(-1), resolution, F.cosine_similarity(state, history, dim=-1))
113
+
114
+ def forward(self, features) -> Scores:
115
+ return self.score_projected(*self.project(features), features.relations)
research/token_readout/reference_view.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offer an earlier phrase only after the writer selects a pronoun that refers back."""
2
+ from research.token_readout.app import source_html
3
+
4
+ STYLE = """
5
+ .writing-review .ref-review { color:#23352f!important; border-top:1px solid #cbd7cf; padding-top:.8rem; }
6
+ .writing-review .ref-review h3 { font-size:1.08rem; color:#23352f!important; }
7
+ .writing-review .ref-review details { margin:.35rem 0; }
8
+ .writing-review .ref-review summary { cursor:pointer; padding:.25rem 0; color:#273d36!important; }
9
+ .writing-review .ref-review p { color:#273d36!important; }
10
+ .writing-review .ref-answer { border-left:3px solid #356591; padding-left:.65rem; }
11
+ """
12
+
13
+ def result(text, record):
14
+ if record.get('scope')!='given_prior_reference':
15
+ raise ValueError('This reference tool requires a writer-selected backward reference.')
16
+ candidates=list(map(tuple,record['pronouns']))
17
+ if candidates!=sorted(set(candidates)):
18
+ raise ValueError('Reference choices must follow their original positions.')
19
+ by_pronoun={}
20
+ for link in record['links']:
21
+ q=link['pronoun_start'],link['pronoun_end'];a,b=link['phrase_start'],link['phrase_end']
22
+ if (link['scope']!='given_prior_reference' or q not in candidates or q in by_pronoun
23
+ or not 0<=a<=link['antecedent_start']<link['antecedent_end']<=b<=q[0]):
24
+ raise ValueError('Reference and earlier phrase must belong to the same article prefix.')
25
+ by_pronoun[q]=(a,b)
26
+ chunks=[];spans=[];rules=[]
27
+ for i,(a,b) in enumerate(candidates):
28
+ if type(a) is not int or type(b) is not int or not 0<=a<b<=len(text):
29
+ raise ValueError('Invalid pronoun in the original draft.')
30
+ start=max(0,a-32);end=min(len(text),b+23)
31
+ display=('…' if start else '')+source_html(text[start:a])+'<strong>'+source_html(text[a:b])+'</strong>'+source_html(text[b:end])+('…' if end<len(text) else '')
32
+ spans.append((a,b,'ref-pronoun-'+str(i)))
33
+ rules.append(f'.writing-review:has(details.ref-{i}[open]) .ref-pronoun-{i} {{outline:2px solid #5c3d8b; outline-offset:.06em;}}')
34
+ if (a,b) in by_pronoun:
35
+ x,y=by_pronoun[a,b];spans.append((x,y,'ref-earlier-'+str(i)))
36
+ rules.append(f'.writing-review:has(details.ref-{i}[open]) .ref-earlier-{i} {{box-shadow:inset 0 -.22em #94bddf;}}')
37
+ answer=f'Likely earlier phrase · <strong>“{source_html(text[x:y])}”</strong>'
38
+ else:answer='The model has too little evidence to choose one earlier phrase.'
39
+ chunks.append(f'<details class="ref-{i}" name="cogllm-selected-reference"><summary>{display}</summary><p class="ref-answer">{answer}</p></details>')
40
+ explain=('Choose a pronoun you intend to point back. Opening it marks that pronoun and the suggested earlier phrase in your draft.'
41
+ if chunks else 'This draft has no supported English pronoun with earlier text to inspect.')
42
+ return spans,('<style>'+''.join(rules)+'</style>' if rules else '')+('<section class="ref-review" aria-label="Inspect a reference"><h3>Which earlier phrase does this pronoun refer to?</h3>'
43
+ f'<p>{explain}</p>'+''.join(chunks)+'</section>')
research/token_readout/runner.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load a sealed token readout and produce its whole-document app trace."""
2
+
3
+ from contextlib import nullcontext
4
+ from dataclasses import replace
5
+ from math import isclose, isfinite, log
6
+ from pathlib import Path
7
+ from threading import Lock
8
+ from types import SimpleNamespace
9
+
10
+ import torch
11
+
12
+ from research.backbone_transfer.extract import digest
13
+ from research.token_readout.extraction import QwenRuntime
14
+ from research.token_readout.model import Scores, TokenReadout, question_mass
15
+
16
+
17
+ def trace_rows(text, offsets, scores, priors, anchor_width=1):
18
+ """Map the causal mass distribution to exact Unicode spans for display."""
19
+ n = len(offsets)
20
+ if (not n or scores.opening.shape != (n,) or scores.resolution.shape != (n, n)
21
+ or scores.continuity.shape != (n,)):
22
+ raise ValueError('Token offsets and model score dimensions disagree')
23
+
24
+ device = scores.opening.device
25
+ candidate = torch.tensor([any(ch.isalnum() for ch in text[start:end]) for start, end in offsets],
26
+ dtype=torch.bool, device=device)
27
+ opened, unresolved, resolved = question_mass(scores.opening + priors['opening'],
28
+ scores.resolution + priors['resolution'], candidate)
29
+ previous = torch.cat((torch.zeros_like(unresolved[:1]), unresolved[:-1]), dim=0)
30
+ discontinuity = (0.5 * (1 - scores.continuity)).clamp(0.0, 1.0)
31
+
32
+ # Repeated Unicode offsets can represent several pieces of one character.
33
+ # A displayed pointer always refers to a completed earlier source span.
34
+ bounds = torch.tensor(offsets, device=device)
35
+ positions = torch.arange(n, device=device)
36
+ eligible = ((positions[:, None] > positions[None, :])
37
+ & (bounds[:, :1] >= bounds[None, :, 1])
38
+ & candidate[None, :])
39
+ associated = resolved + discontinuity[:, None] * previous
40
+ strength, pointer = associated.masked_fill(~eligible, -1).max(dim=1)
41
+
42
+ values = torch.stack((unresolved.sum(dim=1), opened, resolved.sum(dim=1),
43
+ previous.sum(dim=1) * discontinuity), dim=1)
44
+ if not torch.isfinite(values).all() or not torch.isfinite(strength).all():
45
+ raise ArithmeticError('Nonfinite token trace')
46
+ values = values.tolist()
47
+ references = zip(pointer.tolist(), strength.tolist(), strict=True)
48
+ rows = []
49
+ for (start, end), (mass, onset, closure, transition), (anchor, association) in zip(offsets, values, references, strict=True):
50
+ if association > 0:
51
+ pointer_start = offsets[max(0, anchor + 1 - anchor_width)][0]
52
+ pointer_end = offsets[anchor][1]
53
+ else:
54
+ pointer_start, pointer_end = None, None
55
+ rows.append({'start': start, 'end': end, 'unresolved': mass, 'opened': onset,
56
+ 'resolved': closure, 'transition': transition,
57
+ 'pointer_start': pointer_start, 'pointer_end': pointer_end})
58
+ return rows
59
+
60
+
61
+ class TokenRunner:
62
+ def __init__(self, runtime, reader, adapter, priors, checkpoint, *, scale=None, anchor_width=1,
63
+ english_head=None, transition_head=None, narrative_head=None, terminology_head=None):
64
+ self.runtime = runtime
65
+ self.reader = reader
66
+ self.adapter = adapter
67
+ self.priors = priors
68
+ self.checkpoint = checkpoint
69
+ self.scale = scale
70
+ self.anchor_width = anchor_width
71
+ self.english_head = english_head
72
+ self.transition_head = transition_head
73
+ self.narrative_head = narrative_head
74
+ self.terminology_head = terminology_head
75
+ self._word_report = None
76
+ self._reference_head = None
77
+ self._physical_head = None
78
+ self._population_head = None
79
+ self._summary_head = None
80
+ self._forwards = 0
81
+ self._lock = Lock()
82
+
83
+ def _observe_forward(self, _encoder, _inputs):
84
+ self._forwards += 1
85
+
86
+ def forward_count(self):
87
+ return self._forwards
88
+
89
+ @torch.no_grad()
90
+ def __call__(self, text):
91
+ return self._analyze(text, english=False)
92
+
93
+ @torch.no_grad()
94
+ def review_english(self, text, *, narrative=False, terminology=False, references=False, expectations=False, summary=False):
95
+ if self.english_head is None or self.transition_head is None:
96
+ raise ValueError('English writing review requires the validated wording and coherence heads.')
97
+ if terminology and self.terminology_head is None:
98
+ raise ValueError("The scientific terminology readout has not been loaded.")
99
+ if expectations and not 2 <= len(text.split()) <= 64:
100
+ raise ValueError("The next-word view accepts short English passages of 2 to 64 words.")
101
+ return self._analyze(text, english=True, narrative=narrative, terminology=terminology,
102
+ references=references, expectations=expectations, summary=summary)
103
+
104
+ @torch.inference_mode()
105
+ def physical_story(self, text):
106
+ """Read a whole short physical narrative once and locate a possible conflicting pair."""
107
+ from research.reading_validation.argument_data import sentences
108
+ from research.reading_validation.state_inference import PhysicalContinuity
109
+
110
+ if not 5 <= len(sentences(text)) <= 7:
111
+ raise ValueError('Enter a short narrative of five to seven sentences.')
112
+ if len(self.runtime.tokenizer.encode(text, add_special_tokens=False).ids) > 1024:
113
+ raise ValueError('Physical continuity accepts up to 1,024 model tokens.')
114
+ with self._lock, self.runtime.encoder.register_forward_pre_hook(self._observe_forward):
115
+ if self._physical_head is None:
116
+ self._physical_head = PhysicalContinuity.load()
117
+ before = self._forwards
118
+ result = self._physical_head.from_features(text, self.runtime, self.runtime.encode(text))
119
+ if self._forwards - before != 1:
120
+ raise RuntimeError('Physical continuity requires one full-article forward.')
121
+ return result
122
+
123
+ @torch.inference_mode()
124
+ def learner_sentence(self, text):
125
+ """Compute calibrated probabilities for one sentence on the writer's existing backbone."""
126
+ from research.reading_validation.local_inference import REVISION
127
+ from research.token_readout.learner_view import validate_sentence
128
+
129
+ validate_sentence(text)
130
+ if self.english_head is None or self.runtime.revision != REVISION:
131
+ raise ValueError('The English learner check requires the verified writing model.')
132
+ if len(self.runtime.tokenizer.encode(text, add_special_tokens=False).ids) > 1024:
133
+ raise ValueError('The learner check accepts sentences up to 1,024 model tokens.')
134
+ with self._lock, self.runtime.encoder.register_forward_pre_hook(self._observe_forward):
135
+ if self._word_report is None:
136
+ from research.reading_validation.nns_inference import WordReport
137
+ self._word_report = WordReport.load(native=self.english_head)
138
+ before = self._forwards
139
+ features = self.runtime.encode(text)
140
+ result = self._word_report.score_levels(text, features, self.runtime.tokenizer, self.reader)
141
+ if self._forwards - before != 1:
142
+ raise RuntimeError('Each learner vocabulary check requires one encoder forward.')
143
+ return result
144
+
145
+ def _analyze(self, text, *, english, narrative=False, terminology=False, references=False, expectations=False, summary=False):
146
+ with self._lock, self.runtime.encoder.register_forward_pre_hook(self._observe_forward):
147
+ before = self._forwards
148
+ if references and self._reference_head is None:
149
+ from research.reading_validation.reference_inference import ReferenceInference
150
+ self._reference_head = ReferenceInference.conditional()
151
+ capture = self._reference_head.capture(text, self.runtime) if references else nullcontext()
152
+ with capture as observed:
153
+ features = self.runtime.encode(text) if self.adapter is None else self.runtime.encode(text, self.adapter)
154
+ if references:
155
+ ref = dict(scope=observed.scope, pronouns=[list(observed.pointer.words[i][:2]) for i in observed.pointer.queries],
156
+ links=observed.links(features))
157
+ if self._forwards - before != 1:
158
+ raise RuntimeError('Each document trace requires exactly one encoder forward')
159
+ scores = self.reader(features)
160
+ if self.scale is not None:
161
+ scores = replace(scores, opening=scores.opening * self.scale['opening_gain'],
162
+ resolution=scores.resolution * self.scale['resolution_gain']
163
+ + self.scale['resolution_bias'])
164
+ rows = trace_rows(text, features.offsets, scores, self.priors, self.anchor_width)
165
+ result = {'text': text, 'checkpoint': self.checkpoint, 'tokens': rows}
166
+ if english:
167
+ result['english'] = self.english_head.score(text, features, self.runtime.tokenizer, self.reader)
168
+ spans = [(s['start'], s['end']) for s in result['english']['sentences']]
169
+ from research.reading_validation.transition_external_forecast import token_surprisals
170
+
171
+ surprisal = token_surprisals(self.runtime, features)
172
+ common = dict(checkpoint_sha256=self.checkpoint, token_surprisal=surprisal)
173
+ inputs = (text, features, self.runtime.tokenizer, self.reader, self.runtime, spans)
174
+ result['english']['transitions'] = self.transition_head.score(*inputs, token_trace=rows, **common)
175
+ if summary:
176
+ from research.reading_validation.summary_understanding import SummaryUnderstanding
177
+ if self._summary_head is None:
178
+ self._summary_head = SummaryUnderstanding.load()
179
+ result['english']['summary'] = self._summary_head.score(text, features, self.runtime, token_surprisal=surprisal)
180
+ if references:
181
+ result['english']['references'] = ref
182
+ if expectations:
183
+ from research.reading_validation.population_inference import PopulationWordInference
184
+ if self._population_head is None:
185
+ self._population_head = PopulationWordInference.load()
186
+ result['english']['expectations'] = self._population_head.analyze(text, features, self.runtime)
187
+ if terminology:
188
+ result['english']['terminology'] = self.terminology_head.score(text,features,self.runtime)
189
+ if narrative:
190
+ if self.narrative_head is None:
191
+ raise ValueError("The English narrative word model has not been loaded.")
192
+ result['english']['narrative_words'] = self.narrative_head.score(*inputs, **common)
193
+ if self._forwards - before != 1:
194
+ raise RuntimeError('English writing review requires one encoder forward for the whole passage')
195
+ return result
196
+
197
+
198
+ def load(*, model: Path, checkpoint: Path):
199
+ """Gradio factory for a candidate emitted by token_readout.fit."""
200
+ identity = digest(checkpoint)
201
+ packet = torch.load(checkpoint, map_location='cpu', weights_only=True)
202
+ if (not isinstance(packet, dict) or set(packet) != {'reader', 'adapter', 'priors', 'mode'}
203
+ or packet['mode'] not in ('frozen', 'lora')
204
+ or (packet['adapter'] is not None) != (packet['mode'] == 'lora')):
205
+ raise ValueError('Expected a frozen or LoRA token readout checkpoint from fit.py')
206
+ prior = packet['priors']
207
+ if not isinstance(prior, dict) or any(
208
+ type(prior.get(name)) not in (float, int) or not isfinite(prior[name])
209
+ for name in ('opening', 'resolution')
210
+ ):
211
+ raise ValueError('Checkpoint lacks finite opening and resolution priors')
212
+
213
+ runtime = QwenRuntime.load(model)
214
+ reader = TokenReadout().to(runtime.device)
215
+ reader.load_state_dict(packet['reader'], strict=True)
216
+ reader.eval().requires_grad_(False)
217
+ adapter = None
218
+ if packet['adapter'] is not None:
219
+ adapter = runtime.new_adapter(rank=4)
220
+ adapter.load_state_dict(packet['adapter'], strict=True)
221
+ adapter.eval().requires_grad_(False)
222
+ return TokenRunner(runtime, reader, adapter, prior, identity)
223
+
224
+
225
+ def verify_mock_runtime():
226
+ """Check known opening/closure arithmetic and exact app dispatch on CPU."""
227
+ text = '甲 ? e\u0301'
228
+ offsets = ((0, 1), (2, 3), (4, 6))
229
+ runtime = SimpleNamespace(encoder=torch.nn.Identity())
230
+ adapter = object()
231
+
232
+ def encode(source, active_adapter):
233
+ if source != text or active_adapter is not adapter:
234
+ raise AssertionError('The runner changed the source or selected adapter')
235
+ runtime.encoder(torch.zeros(1))
236
+ return SimpleNamespace(offsets=offsets)
237
+
238
+ def reader(features):
239
+ if features.offsets != offsets:
240
+ raise AssertionError('Encoded offsets changed before inference')
241
+ return Scores(torch.zeros(3), torch.full((3, 3), -log(3.0)), torch.tensor([1.0, 0.0, -1.0]))
242
+
243
+ runtime.encode = encode
244
+ run = TokenRunner(runtime, reader, adapter, {'opening': 0.0, 'resolution': 0.0}, 'cpu-mock')
245
+ rows = run(text)['tokens']
246
+ expected = ((0.5, 0.5, 0.0, 0.0), (0.375, 0.0, 0.125, 0.25), (0.78125, 0.5, 0.09375, 0.375))
247
+ for row, coordinates, values in zip(rows, offsets, expected, strict=True):
248
+ if (row['start'], row['end']) != coordinates or any(
249
+ not isclose(row[field], value, abs_tol=1e-6)
250
+ for field, value in zip(('unresolved', 'opened', 'resolved', 'transition'), values, strict=True)
251
+ ):
252
+ raise AssertionError('Token trace disagrees with the independent event arithmetic')
253
+ if [(row['pointer_start'], row['pointer_end']) for row in rows] != [(None, None), (0, 1), (0, 1)]:
254
+ raise AssertionError('Pointer must refer to the earlier eligible span')
255
+ if run.forward_count() != 1:
256
+ raise AssertionError('Mock encoder was not counted exactly once')
257
+ return {'mock_encoder_forwards': 1, 'tokens': 3, 'event_arithmetic_verified': True,
258
+ 'punctuation_candidate_mask_verified': True, 'pointers_verified': True}
research/token_readout/summary_view.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Present the whole-summary human judgment in the units used by its annotators."""
2
+ from html import escape
3
+ from math import isfinite
4
+
5
+ SCOPE = "english_generated_summary_comprehensibility"
6
+ EXAMPLE = ("The city will replace the footbridge after inspectors found cracks in its supports. "
7
+ "A shuttle will carry pedestrians across the river during the repairs.")
8
+
9
+
10
+ def panel(record):
11
+ if record["scope"]!=SCOPE or not isinstance(record["available"],bool):
12
+ raise ValueError("Unknown summary assessment.")
13
+ threshold=record["threshold"]
14
+ if not isinstance(threshold,(int,float)) or not isfinite(threshold) or not 0<threshold<1:
15
+ raise ValueError("Invalid review threshold.")
16
+ heading='<h3>Can a reader understand this summary?</h3>'
17
+ if not record["available"]:
18
+ if record["probability_difficult"] is not None or record["review"] is not None or not record["reason"]:
19
+ raise ValueError("An unavailable reading must have an explanation.")
20
+ body='<p>'+escape(record["reason"])+'</p>'
21
+ else:
22
+ p=record["probability_difficult"]
23
+ if (not isinstance(p,(int,float)) or not isfinite(p) or not 0<=p<=1 or
24
+ not isinstance(record["review"],bool) or record["review"]!=(p>=threshold)):
25
+ raise ValueError("Inconsistent summary probability and review decision.")
26
+ call="Worth a second read." if record["review"] else "Below the study’s review threshold."
27
+ body=(f'<p><strong>{p:.0%}</strong> estimated chance that a study rater would say '
28
+ f'they could not read and understand the whole summary. {call}</p>'
29
+ '<p class="reading-caption">The study used short English summaries of news and how-to articles. '
30
+ 'The percentage concerns the whole draft. Sentence colors above use separate reader ratings. '
31
+ '<a href="https://aclanthology.org/2023.emnlp-main.584/" target="_blank" '
32
+ 'rel="noopener noreferrer">Original reading study</a>.</p>')
33
+ return '<section class="summary-understanding">'+heading+body+'</section>'
research/token_readout/terminology_view.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render a calibrated count over the whole draft and named source-to-cue connections."""
2
+
3
+ from html import escape
4
+ from math import ceil,isfinite
5
+
6
+
7
+ def check(text,record):
8
+ level=record["expected"]
9
+ end=record["ends"]
10
+ start=record["starts"]
11
+ if not 0<len(end)==len(start)==len(level)==record["tokens"]<=1024:
12
+ raise ValueError("Terminology counts do not cover the original token sequence.")
13
+ if (any(not isfinite(x) or x<0 for x in level) or sorted(end)!=end or
14
+ any(not 0<=a<=b<=len(text) for a,b in zip(start,end,strict=True))):
15
+ raise ValueError("Terminology count or location is invalid.")
16
+ for link in record["links"]:
17
+ a,b=link["source"];c,d=link["cue"]
18
+ if not 0<=a<b<=c<d<=len(text) or not isfinite(link["score"]) or link["score"]<record["threshold"]:
19
+ raise ValueError("One terminology link failed its fitted source and location criteria.")
20
+
21
+
22
+ def markup(text,record):
23
+ check(text,record)
24
+ y=record["expected"]
25
+ y_max=max(1,ceil(max(y)))
26
+ paths=" ".join(f"{1000*i/max(1,len(y)-1):.2f},{100-96*v/y_max:.2f}" for i,v in enumerate(y))
27
+ chart=(f'<div class="term-chart" role="img" aria-label="Estimated mentions awaiting a definition, '
28
+ f'from {y[0]:.2f} to {y[-1]:.2f}, maximum {max(y):.2f}"><span><small>{y_max}</small><small>0</small></span>'
29
+ '<svg aria-hidden="true" viewBox="0 0 1000 104" preserveAspectRatio="none">'
30
+ '<path d="M0 4H1000 M0 100H1000" fill="none" stroke="#83978d" stroke-width="1"/>'
31
+ f'<polyline fill="none" stroke="#176956" stroke-width="2.5" vector-effect="non-scaling-stroke" '
32
+ f'points="{paths}"/></svg></div>')
33
+ items=[]
34
+ for link in record["links"]:
35
+ a,b=link["source"];c,d=link["cue"]
36
+ items.append(f'<li><span class="term-source">{escape(text[a:b])}</span> '
37
+ f'<span aria-label="may be explained at">→</span> <span class="term-cue">{escape(text[c:d])}</span></li>')
38
+ if items:
39
+ extra=(f'<details><summary>Show {len(items)-4} more links</summary><ul>{"".join(items[4:])}</ul></details>'
40
+ if len(items)>4 else "")
41
+ findings='<p>Possible term → later wording</p><ul>'+"".join(items[:4])+'</ul>'+extra
42
+ else:
43
+ findings="<p>No term and later wording crossed the trained link threshold in this draft.</p>"
44
+ return ('<section class="term-review" aria-label="Technical terms"><h3>Terms awaiting an explanation</h3>'
45
+ '<p>The line estimates how many earlier terminology mentions are still waiting for a definition.</p>'
46
+ +chart+f'<div class="term-x"><span>Start of draft</span><span>End · {y[-1]:.2f} expected mentions</span></div>'
47
+ +findings+'<p class="term-scope">Trained on textbook definitions. In held biology and physics passages, '
48
+ '30% of proposed links matched both the annotated term and its later definition interval.</p></section>')
49
+
50
+
51
+ def marked_spans(record):
52
+ marks=[]
53
+ for link in record["links"]:
54
+ for kind in ("source","cue"):
55
+ a,b=link[kind]
56
+ marks.append((a,b,kind))
57
+ return marks
research/token_readout/transfer_fit.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fit matched portable readouts on one frozen Colab backbone."""
2
+
3
+ import argparse
4
+ from collections import defaultdict
5
+ from dataclasses import replace
6
+ import gc
7
+ from math import ceil, log
8
+ from pathlib import Path
9
+ import random
10
+ from time import monotonic
11
+
12
+ import torch
13
+ from torch.nn import functional as F
14
+
15
+ from research.backbone_transfer.extract import digest, read_json, stream_rows, write_json
16
+ from research.token_readout.backbone import Backbone
17
+ from research.token_readout.model import (
18
+ Scores, censored_nll, first_report_logits, first_report_nll, interval_nll, matched_effect, phase_first_event,
19
+ )
20
+ from research.token_readout.readout import PortableReadout
21
+
22
+
23
+ ENDPOINTS = ('frick', 'evidence')
24
+ VARIANTS = ('point', 'span')
25
+ DEFAULT_SCALE = {'opening_gain': 1.0, 'resolution_gain': 1.0, 'resolution_bias': 0.0}
26
+ CHECKPOINT_SCHEMA = 2
27
+
28
+
29
+ def smoothed_log_odds(events, exposure):
30
+ if not 0 <= events <= exposure:
31
+ raise ValueError('Observed events must be inside the risk set')
32
+ return log((events + 0.5) / (exposure - events + 0.5))
33
+
34
+
35
+ def observations(packet):
36
+ stories = defaultdict(list)
37
+ for row in packet['frick']:
38
+ stories[row['group_id']].append(row)
39
+ frick = [sorted(group, key=lambda row: row['condition']) for group in stories.values()]
40
+ if any(len(group) != 2 for group in frick) or not all((frick, packet['evidence'])):
41
+ raise ValueError('Both observation endpoints require data and complete story pairs')
42
+ return {'frick': frick, 'evidence': packet['evidence']}
43
+
44
+
45
+ def priors_for(training, cache):
46
+ by_sentence = defaultdict(lambda: [0, 0])
47
+ openings, opening_exposure, supports, support_exposure = 0, 0, 0, 0
48
+ for pair in training['frick']:
49
+ for row in pair:
50
+ events = row['event_counts']
51
+ risk = sum(events) + row['censor_count']
52
+ for i, (count, (begin, end)) in enumerate(zip(events, row['sentence_tokens'], strict=True)):
53
+ by_sentence[i][0] += count
54
+ by_sentence[i][1] += risk
55
+ openings += count
56
+ opening_exposure += risk * (end - begin)
57
+ risk -= count
58
+ if risk != row['censor_count']:
59
+ raise ValueError('Frick exposure differs from the observed censor count')
60
+ for row in training['evidence']:
61
+ for window in row['window_tokens'].values():
62
+ stop = len(cache[row['id']].offsets) if window is None else window[1]
63
+ supports += window is not None
64
+ support_exposure += stop - row['risk_start']
65
+ if not openings or not supports:
66
+ raise ValueError('Training requires observed events on both endpoints')
67
+ return {
68
+ 'sentence': [smoothed_log_odds(*by_sentence[index]) for index in range(len(by_sentence))],
69
+ 'sentence_default': smoothed_log_odds(sum(value[0] for value in by_sentence.values()),
70
+ sum(value[1] for value in by_sentence.values())),
71
+ 'opening': smoothed_log_odds(openings, opening_exposure),
72
+ 'resolution': smoothed_log_odds(supports, support_exposure),
73
+ }
74
+
75
+
76
+ def sentence_logits(residuals, spans, priors, gain=1.0):
77
+ values = priors['sentence'][:len(spans)]
78
+ values = values + [priors['sentence_default']] * (len(spans) - len(values))
79
+ return first_report_logits(residuals * gain, spans, residuals.new_tensor(values))
80
+
81
+
82
+ def report_values(rows, predict):
83
+ return [(row, predict(row['id']).opening) for row in rows]
84
+
85
+
86
+ def report_loss(values, priors, gain=1.0, paired=False):
87
+ logits, targets, losses = [], [], []
88
+ for row, residue in values:
89
+ hazard = sentence_logits(residue, row['sentence_tokens'], priors, gain)
90
+ counts = residue.new_tensor([*row['event_counts'], row['censor_count']])
91
+ losses.append(first_report_nll(hazard, counts))
92
+ index = row['target_sentence_index'] - 1
93
+ if not 0 <= index < len(hazard):
94
+ raise ValueError('Frick target is outside its risk sequence')
95
+ logits.append(hazard[index])
96
+ targets.append(counts[index] / counts[index:].sum().clamp_min(1))
97
+ base = torch.stack(losses).mean()
98
+ return base + 0.25 * matched_effect(logits, targets) if paired else base
99
+
100
+
101
+ def support_values(row, predict):
102
+ pair_logits = predict(row['id']).resolution
103
+ return row, {name: pair_logits[:, span[1] - 1] for name, span in row['anchor_tokens'].items()}
104
+
105
+
106
+ def support_loss(item, priors, gain=1.0, bias=0.0, paired=False):
107
+ row, residue = item
108
+ begin = row['risk_start']
109
+ logits = {name: values * gain + priors['resolution'] + bias for name, values in residue.items()}
110
+ losses = []
111
+ for name, window in row['window_tokens'].items():
112
+ scores = logits[name]
113
+ loss = censored_nll(scores, begin, len(scores)) if window is None else interval_nll(scores, begin, *window)
114
+ losses.append(loss)
115
+ if not paired:
116
+ return torch.stack(losses).mean()
117
+ early, late = row['earlier_query'], row['later_query']
118
+ if early in logits and late in logits and row['window_tokens'][early] is not None:
119
+ start, end = row['window_tokens'][early]
120
+ positive = torch.logsumexp(logits[early][start:end], dim=0)
121
+ competing = torch.logsumexp(logits[late][start:end], dim=0)
122
+ losses.append(0.5 * F.softplus(competing - positive))
123
+ if row['sham_tokens'] is not None:
124
+ sham_start, sham_end = row['sham_tokens']
125
+ negative = torch.logsumexp(logits[early][sham_start:sham_end], dim=0)
126
+ negative = negative + log((end - start) / (sham_end - sham_start))
127
+ losses.append(0.5 * F.softplus(negative - positive))
128
+ return torch.stack(losses).mean()
129
+
130
+
131
+ def validation_values(groups, predict):
132
+ with torch.no_grad():
133
+ return {
134
+ 'frick': [report_values(rows, predict) for rows in groups['frick']],
135
+ 'evidence': [support_values(row, predict) for row in groups['evidence']],
136
+ }
137
+
138
+
139
+ def validated_losses(data, priors, scale):
140
+ report = [report_loss(group, priors, scale['opening_gain']) for group in data['frick']]
141
+ support = [support_loss(pair, priors, scale['resolution_gain'], scale['resolution_bias'])
142
+ for pair in data['evidence']]
143
+ return {'frick': float(torch.stack(report).mean()), 'evidence': float(torch.stack(support).mean())}
144
+
145
+
146
+ def balanced_updates(groups, order):
147
+ packets = {key: list(groups[key]) for key in ENDPOINTS}
148
+ for step in range(max(map(len, packets.values()))):
149
+ for source, rows in packets.items():
150
+ if step % len(rows) == 0:
151
+ order.shuffle(rows)
152
+ yield source, rows[step % len(rows)]
153
+
154
+
155
+ def linked_stream(rows, seed):
156
+ order = random.Random(seed)
157
+ remaining = list(rows)
158
+ while remaining:
159
+ order.shuffle(remaining)
160
+ yield from remaining
161
+
162
+
163
+ def checkpoint(reader, candidate, revision, variant, priors, scale, path):
164
+ payload = {'schema': CHECKPOINT_SCHEMA, 'candidate': candidate, 'revision': revision, 'variant': variant,
165
+ 'relations': True, 'reader': reader.state_dict(), 'priors': priors, 'scale': scale}
166
+ pending = path.with_suffix('.pending')
167
+ torch.save(payload, pending)
168
+ pending.replace(path)
169
+
170
+
171
+ def train_variant(candidate, revision, variant, cache, width, training, dev, linked, priors, settings, output):
172
+ torch.manual_seed(settings['seed'])
173
+ order = random.Random(settings['seed'])
174
+ reader = PortableReadout(width, variant=variant, relations=True).cuda()
175
+ optimizer = torch.optim.AdamW(reader.parameters(), lr=settings['lr'], weight_decay=settings['weight_decay'])
176
+ additional = linked_stream(linked, settings['seed'])
177
+ linked_batch = ceil(len(linked) / max(map(len, training.values())))
178
+ history = []
179
+ started = monotonic()
180
+ best_score, best_epoch, stop = float('inf'), 0, 'epoch_limit'
181
+ path = output / f'{variant}.pt'
182
+
183
+ def predict(identity):
184
+ return reader(cache[identity])
185
+
186
+ for epoch in range(1, settings['epochs'] + 1):
187
+ reader.train()
188
+ losses = {source: [] for source in ENDPOINTS}
189
+ auxiliary = []
190
+ for source, row in balanced_updates(training, order):
191
+ optimizer.zero_grad(set_to_none=True)
192
+ if source == 'frick':
193
+ loss = report_loss(report_values(row, predict), priors, paired=True)
194
+ else:
195
+ loss = support_loss(support_values(row, predict), priors, paired=True)
196
+ if linked_batch:
197
+ interval_losses = [support_loss(support_values(next(additional), predict), priors, paired=True)
198
+ for _ in range(linked_batch)]
199
+ auxiliary_loss = torch.stack(interval_losses).mean()
200
+ auxiliary.append(auxiliary_loss.detach())
201
+ loss = loss + 0.5 * auxiliary_loss
202
+ if not torch.isfinite(loss):
203
+ raise ArithmeticError(f'{candidate} {variant} {source} loss is nonfinite')
204
+ loss.backward()
205
+ torch.nn.utils.clip_grad_norm_(reader.parameters(), 5.0, error_if_nonfinite=True)
206
+ optimizer.step()
207
+ losses[source].append(loss.detach())
208
+ reader.eval()
209
+ study = validated_losses(validation_values(dev, predict), priors, DEFAULT_SCALE)
210
+ row = {'epoch': epoch, 'training_composite': {key: float(torch.stack(value).mean()) for key, value in losses.items()},
211
+ 'dev_nll': study, 'updates': {key: len(value) for key, value in losses.items()},
212
+ 'elapsed_seconds': monotonic() - started}
213
+ if auxiliary:
214
+ row['linked_auxiliary_nll'] = float(torch.stack(auxiliary).mean())
215
+ row['linked_examples_used'] = len(auxiliary) * linked_batch
216
+ score = sum(study.values()) / len(study)
217
+ if not all(logit < float('inf') for logit in study.values()):
218
+ raise ArithmeticError('Development objective is nonfinite')
219
+ if score < best_score - settings['min_dev_gain']:
220
+ best_score, best_epoch = score, epoch
221
+ checkpoint(reader, candidate, revision, variant, priors, DEFAULT_SCALE, path)
222
+ history.append(row)
223
+ print(candidate, variant, row, flush=True)
224
+ if epoch >= settings['minimum_epochs'] and epoch - best_epoch >= settings['patience']:
225
+ stop = 'development_plateau'
226
+ break
227
+ if row['elapsed_seconds'] >= settings['arm_seconds']:
228
+ stop = 'arm_time_limit'
229
+ break
230
+ write_json(output / f'{variant}-history.json', history)
231
+ if best_epoch == 0:
232
+ raise RuntimeError('No valid dev checkpoint was saved')
233
+ packet = torch.load(path, map_location='cuda', weights_only=True)
234
+ reader.load_state_dict(packet['reader'], strict=True)
235
+ return reader.eval(), {'selected_epoch': best_epoch, 'epochs': len(history), 'stop': stop,
236
+ 'dev_nll': history[best_epoch - 1]['dev_nll'],
237
+ 'parameters': sum(value.numel() for value in reader.parameters()),
238
+ 'seconds': monotonic() - started}
239
+
240
+
241
+ def choose_calibration(reader, cache, dev, priors):
242
+ """Shrink extreme residuals and fit a support intercept using only development observations."""
243
+ values = validation_values(dev, lambda identity: reader(cache[identity]))
244
+ gains = (1.0, 0.75, 0.5, 0.3, 0.2, 0.12, 0.06)
245
+ biases = (0.0, -0.75, 0.75, -1.5, 1.5, -2.25, 2.25, -3.0, 3.0)
246
+
247
+ def frick(gain):
248
+ losses = [report_loss(group, priors, gain) for group in values['frick']]
249
+ return float(torch.stack(losses).mean())
250
+
251
+ def evidence(gain, bias):
252
+ losses = [support_loss(item, priors, gain, bias) for item in values['evidence']]
253
+ return float(torch.stack(losses).mean())
254
+
255
+ first = min(gains, key=frick)
256
+ gain, bias = min(((gain, bias) for gain in gains for bias in biases),
257
+ key=lambda pair: evidence(*pair))
258
+ scale = {'opening_gain': first, 'resolution_gain': gain, 'resolution_bias': bias}
259
+ return scale, validated_losses(values, priors, scale)
260
+
261
+
262
+ def probabilities(logits):
263
+ return logits.sigmoid().clamp(1e-8, 1 - 1e-7).tolist()
264
+
265
+
266
+ def forecasts(geometry, cache, priors, reader=None, scale=DEFAULT_SCALE):
267
+ result = {kind: {} for kind in ('frick', 'evidence', 'controls', 'ab')}
268
+ with torch.no_grad():
269
+ for identity, row in geometry.items():
270
+ if row['split'] != 'test':
271
+ continue
272
+ features = cache[identity]
273
+ length = len(features.offsets)
274
+ scores = reader(features) if reader is not None else None
275
+ if row['kind'] == 'frick':
276
+ residuals = features.hidden.new_zeros(length) if scores is None else scores.opening
277
+ logits = sentence_logits(residuals, row['sentence_tokens'], priors, scale['opening_gain'])
278
+ prediction = {'hazard': probabilities(logits), 'first_report': phase_first_event(logits).exp().tolist()}
279
+ else:
280
+ prediction = {'hazard': {}}
281
+ for name, span in row['anchor_tokens'].items():
282
+ residuals = features.hidden.new_zeros(length) if scores is None else scores.resolution[:, span[1] - 1]
283
+ prediction['hazard'][name] = probabilities(residuals * scale['resolution_gain']
284
+ + priors['resolution'] + scale['resolution_bias'])
285
+ result[row['kind']][identity] = prediction
286
+ return result
287
+
288
+
289
+ def run(candidate, model, stimuli, output, protocol_sha256, learning, layout, settings):
290
+ runtime = Backbone.load(candidate, model)
291
+ revision, width = runtime.revision, runtime.width
292
+ device = next(runtime.encoder.parameters()).device
293
+ if device.type != 'cuda' or torch.cuda.get_device_name(device) != 'NVIDIA L4':
294
+ raise RuntimeError('The portable experiment requires a verified Colab L4')
295
+ settings, learning, layout = read_json(settings), read_json(learning), read_json(layout)
296
+ output.mkdir(parents=True, exist_ok=False)
297
+ geometry = layout['rows']
298
+ texts = {row['id']: row['text'] for row in stream_rows(stimuli)}
299
+ if layout['model'] != candidate or set(texts) != geometry.keys():
300
+ raise ValueError('Stimuli and tokenizer geometry differ')
301
+ controls = [runtime.validate(text) for text in settings['technical_controls']]
302
+ cache, counted = {}, 0
303
+ start = monotonic()
304
+
305
+ def count(_module, _inputs):
306
+ nonlocal counted
307
+ counted += 1
308
+
309
+ with runtime.encoder.register_forward_pre_hook(count):
310
+ for identity, text in texts.items():
311
+ prior_count = counted
312
+ features = runtime.encode(text)
313
+ if counted != prior_count + 1 or features.offsets != tuple(map(tuple, geometry[identity]['offsets'])):
314
+ raise ValueError(f'Token coordinates or forward count changed for {identity}')
315
+ if features.relations is None:
316
+ raise ValueError('Comparative arms require observed native attention relations')
317
+ cache[identity] = replace(features, hidden=features.hidden.clone(), mid=features.mid.clone(),
318
+ relations=features.relations.clone())
319
+ extraction_seconds = monotonic() - start
320
+ tokens = sum(len(features.offsets) for features in cache.values())
321
+ extraction_peaks = torch.cuda.max_memory_reserved()
322
+ del runtime
323
+ gc.collect()
324
+ torch.cuda.empty_cache()
325
+ torch.cuda.reset_peak_memory_stats()
326
+ print(candidate, 'extracted', counted, 'documents and', tokens, 'native tokens', flush=True)
327
+ write_json(output / 'causality.json', {'checks': controls, 'model': candidate, 'revision': revision,
328
+ 'document_forwards': counted, 'every_document_single_forward': True})
329
+ training, dev = (observations(learning[split]) for split in ('train', 'dev'))
330
+ linked = learning['train'].get('linked', [])
331
+ for split, rows in (('train', learning['train']), ('dev', learning['dev'])):
332
+ if any(geometry[row['id']]['split'] != split or geometry[row['id']]['kind'] != source
333
+ for source, observations_for_source in rows.items() for row in observations_for_source):
334
+ raise ValueError('Training or development payload contains a row from another split')
335
+ if learning['dev'].get('linked') or len(linked) != sum(row['kind'] == 'linked' for row in geometry.values()):
336
+ raise ValueError('IIRC supervision is restricted to the supplemental train split')
337
+ priors = priors_for(training, cache)
338
+ write_json(output / 'forecast-position.json', forecasts(geometry, cache, priors))
339
+ fits = {}
340
+ for variant in VARIANTS:
341
+ reader, fits[variant] = train_variant(candidate, revision, variant, cache, width,
342
+ training, dev, linked, priors, settings, output)
343
+ write_json(output / f'forecast-{variant}.json', forecasts(geometry, cache, priors, reader))
344
+ scale, dev_nll = choose_calibration(reader, cache, dev, priors)
345
+ fits['span-calibrated'] = {'dev_nll': dev_nll, 'scale': scale, 'parameters': fits['span']['parameters'],
346
+ 'selected_epoch': fits['span']['selected_epoch']}
347
+ checkpoint(reader, candidate, revision, 'span', priors, scale, output / 'span-calibrated.pt')
348
+ write_json(output / 'forecast-span-calibrated.json', forecasts(geometry, cache, priors, reader, scale))
349
+ write_json(output / 'fitting.json', {
350
+ 'candidate': candidate, 'revision': revision, 'documents': counted, 'tokens': tokens, 'fits': fits,
351
+ 'linked_training_examples': len(linked),
352
+ 'selection_score': 'equal mean Frick and ExpMRC development negative log likelihood',
353
+ 'dev_position_nll': validated_losses(validation_values(dev, lambda identity: zero_scores(cache[identity])),
354
+ priors, DEFAULT_SCALE),
355
+ 'peak_extraction_reserved_bytes': extraction_peaks, 'peak_fitting_reserved_bytes': torch.cuda.max_memory_reserved(),
356
+ 'extraction_seconds': extraction_seconds, 'device': torch.cuda.get_device_name(device),
357
+ })
358
+ write_json(output / 'seal.json', {'protocol_sha256': protocol_sha256, 'candidate': candidate, 'revision': revision,
359
+ 'files_sha256': {path.name: digest(path) for path in sorted(output.iterdir())}})
360
+
361
+
362
+ def zero_scores(features):
363
+ length = len(features.offsets)
364
+ opening = features.hidden.new_zeros(length)
365
+ return Scores(opening, features.hidden.new_zeros(length, length), opening)
366
+
367
+
368
+ if __name__ == '__main__':
369
+ parser = argparse.ArgumentParser(description=__doc__)
370
+ parser.add_argument('--candidate', required=True, choices=('qwen', 'lfm3', 'gemma4'))
371
+ for name in ('model', 'stimuli', 'output', 'learning', 'layout', 'settings'):
372
+ parser.add_argument('--' + name, type=Path, required=True)
373
+ parser.add_argument('--protocol-sha256', required=True)
374
+ run(**vars(parser.parse_args()))
research/token_readout/writing_review.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Present English sentence ratings and local wording candidates on the original draft."""
2
+
3
+ from html import escape
4
+ from math import floor, isfinite
5
+
6
+ from research.reading_validation.local_inference import SCHEMA
7
+ from research.token_readout import expectation_view, experimental_view, physical_view, summary_view
8
+ from research.token_readout import learner_view, reference_view, terminology_view
9
+ from research.token_readout.app import CHANNELS, initial_position, parse_analysis, plot_rows, render_article, source_html
10
+
11
+
12
+ EXAMPLE = ("A sensor measures how much light a leaf reflects. "
13
+ "The resulting hyperspectral reflectance signature varies with the concentration of pigments in the leaf. "
14
+ "This means that two leaves can reflect different amounts of light even when they look equally green.")
15
+ NARRATIVE_EXAMPLE = ("Mara and Leo spent the evening repairing their boat. Mara checked the engine while Leo worked on the hull. "
16
+ "By morning they were ready to leave.\n\nNatascha met them at the dock. She handed Mara a faded photograph.")
17
+
18
+ TERMINOLOGY_EXAMPLE = ("A light wave can change direction at the boundary between air and water. "
19
+ "This effect is called refraction. The refractive index of a material "
20
+ "is the ratio of the speed of light in a vacuum to its speed in that material.")
21
+
22
+ MODEL_CARD = "https://huggingface.co/JacobLinCool/CogLLM-Qwen3.5-2B"
23
+
24
+ STYLE = """
25
+ .writing-review .term-review { border-top:1px solid #cbd7cf; padding-top:.9rem; margin-top:.65rem; }
26
+ .writing-review .term-review h3,.writing-review .term-review p,.writing-review .term-review li { color:#23352f!important; }
27
+ .writing-review .term-review h3 { font-size:1.1rem; margin:.2rem 0; }
28
+ .writing-review .term-source { border-bottom:3px solid #3d685a; }
29
+ .writing-review .term-cue { border-bottom:3px dotted #3d685a; }
30
+ .writing-review .term-chart { display:grid; grid-template-columns:1.5em minmax(0,1fr); margin-top:.6rem; }
31
+ .writing-review .term-chart svg { display:block; width:100%; height:4.1rem; }
32
+ .writing-review .term-chart span { display:flex; flex-direction:column; justify-content:space-between; font-size:.8rem; }
33
+ .writing-review .term-x { display:flex; justify-content:space-between; flex-wrap:wrap; padding-left:1.5em; font-size:.8rem; }
34
+ .writing-review .term-scope { font-size:.83rem; }
35
+ .writing-review { --ink: #182b24; color: var(--ink)!important; background: #fcfcf8;
36
+ border: 1px solid #cbd7cf; border-radius: .65rem; padding: 1.1rem 1.25rem; }
37
+ .writing-review .summary-understanding { margin-top:.8rem; padding-top:.65rem; border-top:1px solid #c4d1cc; }
38
+ .writing-review .summary-understanding h3,.writing-review .summary-understanding p,
39
+ .writing-review .summary-understanding strong { color:#23352f!important; }
40
+ .writing-review .reading-key,.writing-review .reading-caption { color: #394c42!important; font-size: .87rem; }
41
+ .writing-review .reading-key { display: flex; flex-wrap: wrap; gap: .35rem .72rem; align-items: center; }
42
+ .writing-review .key-swatch { display: inline-block; width: 1.3em; height: .82em; border: 1px solid #b2b0a3;
43
+ border-radius: .15em; vertical-align: middle; margin-right: .18em; }
44
+ .writing-review .draft { white-space: pre-wrap; overflow-wrap: anywhere; font: 1.16rem/2.1 Georgia, "Times New Roman", serif;
45
+ max-width: 85ch; padding: 1.05rem 0; }
46
+ .writing-review .draft mark { color: var(--ink)!important; padding: .14em 0; box-decoration-break: clone;
47
+ -webkit-box-decoration-break: clone; border-radius: .16rem; }
48
+ .writing-review .phrase { text-decoration: underline solid #6e4218; text-underline-offset: .23em; }
49
+ .writing-review .character { box-shadow: inset 0 3px 0 #624a8b; padding-top: .11em; }
50
+ .writing-review .connection { outline: 2px dashed #28568c; outline-offset: .08em; }
51
+ .writing-review .review-list { margin: .6rem 0 0; padding-left: 1.5rem; }
52
+ .writing-review .review-list li { margin-bottom: .4rem; }
53
+ .writing-review h2 { margin: 0 0 .65rem; font-size: 1.3rem; }
54
+ .writing-review .reading-key { margin: .3rem 0; }
55
+ .writing-review .key-description { display: inline-block; margin-inline-end: .65rem; }
56
+ .gradio-container:has(#writer-heading) { max-width: 960px!important; margin-inline: auto; }
57
+ #writer-heading p { max-width: 68ch; }
58
+ #writer-actions { align-items: center; }
59
+ #writer-result:empty { display: none; }
60
+ @media (max-width: 550px) {
61
+ .writing-review { padding: .85rem .75rem; }
62
+ .writing-review .draft { font-size: 1.06rem; }
63
+ }
64
+ """ + learner_view.STYLE + reference_view.STYLE
65
+ COLORS = ("#d78353", "#e9a774", "#f0c796", "#e7e1b8", "#e8f3e7")
66
+
67
+
68
+ STYLE += physical_view.STYLE + expectation_view.STYLE + experimental_view.STYLE
69
+
70
+ # Gradio assigns foreground colors to individual HTML descendants in dark mode.
71
+ # Each fixed, light reading surface therefore supplies both its own theme variables
72
+ # and a foreground for nested source words, legend labels, links and disclosures.
73
+ STYLE += """
74
+ :is(.writing-review,.physical-review,.learner-result) {
75
+ --reading-surface-ink:#182b24;
76
+ --body-text-color:var(--reading-surface-ink);
77
+ --body-text-color-subdued:var(--reading-surface-ink);
78
+ color-scheme:light;
79
+ color:var(--reading-surface-ink)!important;
80
+ }
81
+ :is(.writing-review,.physical-review,.learner-result) :where(*) {
82
+ color:var(--reading-surface-ink)!important;
83
+ }
84
+ :is(.writing-review,.physical-review,.learner-result) a:any-link {
85
+ color:#183b45!important;
86
+ text-decoration:underline;
87
+ }
88
+ :is(.writing-review,.physical-review,.learner-result) :is(a,summary):focus-visible {
89
+ outline:2px solid #284e62; outline-offset:2px;
90
+ }
91
+ """
92
+
93
+
94
+ def fixed_color(score):
95
+ if not isfinite(score) or not 1 <= score <= 5:
96
+ raise ValueError("Reading ease must be on the validated 1–5 scale.")
97
+ lo = min(3, floor(score) - 1)
98
+ fraction = score - (lo + 1)
99
+ lower, upper = COLORS[lo], COLORS[lo + 1]
100
+ channels = (round((1 - fraction) * int(lower[i:i+2], 16) + fraction * int(upper[i:i+2], 16))
101
+ for i in (1, 3, 5))
102
+ return "#" + "".join(f"{channel:02x}" for channel in channels)
103
+
104
+
105
+ def validate(text, local):
106
+ if local["schema"]!=SCHEMA or local["language"]!="en" or not local["bundle_sha256"]:
107
+ raise ValueError("The selected readout is not the English wording model.")
108
+ previous=0
109
+ for s in local["sentences"]:
110
+ a,b=s["start"],s["end"]
111
+ if type(a) is not int or type(b) is not int or not previous<=a<b<=len(text):
112
+ raise ValueError("Sentence boundaries differ from the original passage.")
113
+ previous=b
114
+ if s["rating"] is not None and any(not isfinite(s["rating"][key]) or not 1<=s["rating"][key]<=5
115
+ for key in ("ease","understanding")):
116
+ raise ValueError("A sentence rating falls outside the human rating scale.")
117
+ intervals=[]
118
+ for i,p in enumerate(s["phrases"],1):
119
+ lo,hi=p["start"],p["end"]
120
+ if (p["rank"]!=i or not a<=lo<hi<=b or not isfinite(p["score"]) or
121
+ any(lo<d and c<hi for c,d in intervals)):
122
+ raise ValueError("A phrase rank or interval differs from the sentence being reviewed.")
123
+ intervals.append((lo,hi))
124
+ if len(local["transitions"])!=max(0,len(local["sentences"])-1):
125
+ raise ValueError("The coherence readout does not cover the expected sentence boundaries.")
126
+ for i,(t,s) in enumerate(zip(local["transitions"],local["sentences"][1:],strict=True),2):
127
+ if (t["start"],t["end"],t["sentence_index"])!=(s["start"],s["end"],i):
128
+ raise ValueError("A coherence score refers to another sentence.")
129
+ if (t["risk"] is None)!=(t["flagged"] is None) or (t["risk"] is not None and
130
+ (not 0<=t["risk"]<=1 or t["flagged"]!=(t["risk"]>t["threshold"]))):
131
+ raise ValueError("Invalid coherence probability or alert threshold.")
132
+
133
+
134
+ last = 0
135
+ for word in local.get("narrative_words", []):
136
+ start, end = word["start"], word["end"]
137
+ if (type(start) is not int or type(end) is not int or not last <= start < end <= len(text)
138
+ or not isfinite(word["risk"]) or not 0 <= word["risk"] <= 1 or type(word["flagged"]) is not bool):
139
+ raise ValueError("An unexplained-character estimate falls outside the draft.")
140
+ last = end
141
+
142
+
143
+ def sentence_markup(text, sentence, characters, terms=(), references=()):
144
+ start, end = sentence["start"], sentence["end"]
145
+ phrase = sentence["phrases"][0] if sentence["phrases"] else None
146
+ bounds = {start, end}
147
+ if phrase:
148
+ bounds.update((phrase["start"], phrase["end"]))
149
+ for word in characters:
150
+ bounds.update((word["start"], word["end"]))
151
+ for a,b,_ in (*terms,*references):
152
+ bounds.update((max(start,a),min(end,b)))
153
+ parts = []
154
+ edges = sorted(bounds)
155
+ for left, right in zip(edges, edges[1:]):
156
+ css, notes = [], []
157
+ if phrase and phrase["start"] <= left < phrase["end"]:
158
+ css.append("phrase")
159
+ notes.append("Top wording candidate within this sentence")
160
+ if any(w["start"] <= left < w["end"] for w in characters):
161
+ css.append("character")
162
+ notes.append("This person may need an introduction")
163
+ for kind in ("source","cue"):
164
+ if any(k==kind and a<=left<b for a,b,k in terms):
165
+ css.append("term-"+kind)
166
+ notes.append("Earlier technical term" if kind=="source" else "Possible explanatory wording")
167
+ css.extend(key for a,b,key in references if a<=left<b)
168
+ value = source_html(text[left:right])
169
+ if css:
170
+ value = (f'<span class="{" ".join(css)}" data-start="{left}" data-end="{right}" '
171
+ f'title="{". ".join(notes)}">{value}</span>')
172
+ parts.append(value)
173
+ return "".join(parts)
174
+
175
+
176
+ def render(text, local):
177
+ validate(text,local)
178
+ sentences=local["sentences"]
179
+ if not sentences:
180
+ raise ValueError("Enter an English passage containing at least one word.")
181
+ term_record=local.get("terminology")
182
+ panel=terminology_view.markup(text,term_record) if term_record is not None else ""
183
+ marks=terminology_view.marked_spans(term_record) if term_record is not None else []
184
+ ref_spans,ref_panel=reference_view.result(text,local["references"]) if "references" in local else ([], "")
185
+ expectations, expectation_panel = (expectation_view.present(text, local["expectations"])
186
+ if "expectations" in local else ([], ""))
187
+ summary_panel = summary_view.panel(local["summary"]) if "summary" in local else ""
188
+ chunks=[]
189
+ end=0
190
+ for i,s in enumerate(sentences,1):
191
+ a,b=s["start"],s["end"]
192
+ chunks.append(source_html(text[end:a]))
193
+ rating=s["rating"]
194
+ if rating is None:
195
+ color="transparent"
196
+ tip=f"Sentence {i}. No rated endpoint for this sentence."
197
+ else:
198
+ color=fixed_color(rating["ease"])
199
+ tip=f"Sentence {i}. Estimated ease {rating['ease']:.2f} of 5."
200
+ flag=i>1 and local["transitions"][i-2]["flagged"]
201
+ if flag:
202
+ tip+=" Check how this sentence connects to the preceding text."
203
+ css=' class="connection"' if flag else ""
204
+ chunks.append(f'<mark{css} style="background:{color}" data-start="{a}" data-end="{b}" title="{tip}">')
205
+ characters = [w for w in local.get("narrative_words", []) if w["flagged"] and a <= w["start"] < w["end"] <= b]
206
+ chunks.append(sentence_markup(text,s,characters,[m for m in marks if m[0]<b and m[1]>a],
207
+ [m for m in (*ref_spans,*expectations) if m[0]<b and m[1]>a]))
208
+ chunks.append("</mark>")
209
+ end=b
210
+ chunks.append(source_html(text[end:]))
211
+ ranked=sorted(((s["rating"]["ease"],i,s) for i,s in enumerate(sentences,1) if s["rating"] is not None),
212
+ key=lambda row:(row[0],row[1]))
213
+ detail=[]
214
+ for ease,i,s in ranked[:3]:
215
+ phrase=s["phrases"][0] if s["phrases"] else s
216
+ label=source_html(text[phrase["start"]:phrase["end"]])
217
+ detail.append(f'<li>Sentence {i} · <strong>{ease:.2f}/5</strong> ease · “{label}”</li>')
218
+ short=(f'<details><summary>Lowest estimated ease ({min(3,len(ranked))} of {len(ranked)} rated sentences)</summary>'
219
+ f'<ol class="review-list">{"".join(detail)}</ol></details>') if ranked else ""
220
+ key=''.join(f'<span><i class="key-swatch" style="background:{COLORS[i]}" aria-hidden="true"></i>{label}</span>'
221
+ for i,label in ((0,"Harder · 1"),(2,"3"),(4,"Easier · 5")))
222
+ narrative_key = (' <span class="character">Purple overline</span> · a person may need an introduction.'
223
+ if "narrative_words" in local else "")
224
+ term_key = (' <span class="term-source">Solid green</span> · earlier term. '
225
+ '<span class="term-cue">Dotted green</span> · possible explanatory wording.' if marks else "")
226
+ expectation_key = (' <span class="expectation-increase">Solid brown</span> · next guesses spread out. '
227
+ '<span class="expectation-decrease">Dotted blue</span> · guesses narrow. '
228
+ 'These marks show changes of at least 20 percentage points.' if expectation_panel else "")
229
+ return (f'<section class="writing-review" data-model="{escape(local["bundle_sha256"],quote=True)}">'
230
+ '<h2>Reviewed draft</h2>'
231
+ f'<div class="reading-key" aria-label="Estimated sentence ease"><strong>Sentence ease</strong>{key}</div>'
232
+ '<p class="reading-caption"><span class="key-description"><span class="phrase">Underline</span> · wording to review</span> '
233
+ '<span class="key-description"><span class="connection">Dashed outline</span> · check the connection '
234
+ f'to earlier sentences</span>{narrative_key}{term_key}{expectation_key}</p>'
235
+ f'<div class="draft" aria-label="Original passage">{"".join(chunks)}</div>{summary_panel}{expectation_panel}{ref_panel}{panel}{short}</section>')
236
+
237
+
238
+ def build_app(runner, *, study_tools=True, max_tokens=2048):
239
+ import gradio as gr
240
+ if type(max_tokens) is not int or max_tokens < 1:
241
+ raise ValueError("The interface needs a positive model token limit.")
242
+
243
+ with gr.Blocks(title="CogLLM Writing Review",analytics_enabled=False) as ui:
244
+ gr.Markdown(
245
+ "# CogLLM Writing Review\n"
246
+ "See where an English draft may be harder to read and which sentences may be hard to connect. "
247
+ "Review the example below or replace it with your own text.",
248
+ elem_id="writer-heading",
249
+ )
250
+ article = gr.Textbox(
251
+ label="English draft", lines=5, value=EXAMPLE, placeholder="Paste your English draft.",
252
+ info=f"Up to {max_tokens:,} model tokens. A token can be a word, part of a word, or punctuation.",
253
+ )
254
+ with gr.Row(elem_id="writer-actions"):
255
+ submit = gr.Button("Review draft", variant="primary", scale=2)
256
+ demo = gr.Button("Load example", scale=1)
257
+ result = gr.HTML(elem_id="writer-result")
258
+ with gr.Accordion("How to read the marks", open=False):
259
+ gr.Markdown(
260
+ "**Sentence color.** Orange means lower estimated reading ease. Pale green means higher ease. "
261
+ "The scale comes from readers’ ratings of biomedical abstracts.\n\n"
262
+ "**Underlined words.** Consider whether your audience knows this expression. Given the sentence, "
263
+ "the model’s first suggestion overlapped 45 of 94 expressions that readers named as difficult.\n\n"
264
+ "**Dashed outline.** Reread this sentence with the one before it. In 100 student essays, "
265
+ "this alert found 114 of 446 editor-marked breaks and flagged 131 of 906 unmarked boundaries.\n\n"
266
+ f"[Model and evaluation]({MODEL_CARD})"
267
+ )
268
+ if not study_tools:
269
+ def review_draft(text):
270
+ if not isinstance(text, str) or not text.strip():
271
+ raise gr.Error("Paste an English passage or load the example.")
272
+ try:
273
+ reviewed = runner.review_english(text)
274
+ analysis = parse_analysis(text, reviewed)
275
+ return render(text, reviewed["english"]) + experimental_view.panel(analysis)
276
+ except ValueError as error:
277
+ raise gr.Error(escape(str(error))) from error
278
+
279
+ submit.click(review_draft, inputs=article, outputs=result, api_name="review_english",
280
+ concurrency_limit=1)
281
+ article.input(fn=None, inputs=None, outputs=result, js="() => ''",
282
+ queue=False, api_visibility="private")
283
+ demo.click(lambda: (EXAMPLE, ""), outputs=[article, result], api_visibility="private",
284
+ show_progress="hidden", queue=False)
285
+ return ui
286
+ gr.Markdown("## Additional reading tasks\nSelect any that apply to your draft, then choose **Review draft**.")
287
+ summary = gr.Checkbox(label="Check whether this summary is understandable", value=False,
288
+ info="For a short English summary. Estimates a reader’s verdict on the whole draft.")
289
+ expectations = gr.Checkbox(label="Show where readers’ next guesses change", value=False,
290
+ info="For a short English passage. See the estimates alongside the original words.")
291
+ narrative = gr.Checkbox(label="Check character introductions in narrative summaries", value=False,
292
+ info="Marks English names or references that may leave readers wondering who the person is.")
293
+ terminology = gr.Checkbox(label="Track technical terms and their explanations",value=False,
294
+ info="For English passages up to 1,024 model tokens.")
295
+ references = gr.Checkbox(label="Inspect a pronoun that refers back",value=False,
296
+ info="Choose the pronoun after reviewing your draft.")
297
+ with gr.Accordion("Experimental token signals", open=False):
298
+ gr.Markdown("These signals track model estimates of questions opening or closing. "
299
+ "In an eight-passage-pair test, the current curve identified both question–answer links in zero pairs.")
300
+ trace=gr.HTML(elem_id="cogllm-reading")
301
+ plot=gr.LinePlot(x="token",y="score",color="signal",height=300,
302
+ x_title="Token position",y_title="Model score",
303
+ color_map={label:color for label,color in CHANNELS.values()})
304
+ learner_view.add_learner_check(runner)
305
+ physical_view.add_physical_check(runner)
306
+ def review(text, show_narrative=False, show_terminology=False, show_references=False, show_expectations=False, show_summary=False):
307
+ if not isinstance(text,str) or not text.strip():
308
+ raise gr.Error("Paste an English passage or load the example.")
309
+ try:
310
+ options={}
311
+ if show_narrative:
312
+ options["narrative"]=True
313
+ if show_terminology:
314
+ options["terminology"]=True
315
+ if show_references:
316
+ options["references"]=True
317
+ if show_expectations:
318
+ options["expectations"]=True
319
+ if show_summary:
320
+ options["summary"]=True
321
+ raw=runner.review_english(text,**options)
322
+ analysis=parse_analysis(text,raw)
323
+ selected,_=initial_position(analysis)
324
+ return render(text,raw["english"]),render_article(analysis,selected),plot_rows(analysis)
325
+ except ValueError as error:
326
+ raise gr.Error(escape(str(error))) from error
327
+ submit.click(review,[article,narrative,terminology,references,expectations,summary],[result,trace,plot],api_name="review_english",concurrency_limit=1)
328
+ def load_example(show_narrative, show_terminology, show_references, show_expectations, show_summary):
329
+ if show_narrative or show_references:
330
+ return NARRATIVE_EXAMPLE, "", "", None
331
+ if show_expectations and not show_terminology:
332
+ return expectation_view.EXAMPLE, "", "", None
333
+ if show_summary and not show_terminology:
334
+ return summary_view.EXAMPLE, "", "", None
335
+ return TERMINOLOGY_EXAMPLE if show_terminology else EXAMPLE, "", "", None
336
+ demo.click(load_example, inputs=[narrative,terminology,references,expectations,summary], outputs=[article,result,trace,plot], api_name=False, show_progress="hidden")
337
+ return ui