File size: 12,824 Bytes
1acb00e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"""Forecast how readers respond to an English passage with the CogLLM four-depth reader.

One causal pass through the frozen FP32 Qwen3.5-2B text model gives its states at depths 6, 12, 18
and 24.  A shared projection turns the states at a reading stop into one vector, and each response
type reads that vector through its own head, as in training.  Every response type reads its own
stops: the end of a word, the end of a sentence, or the end of the passage.  The state at a stop
depends only on the text up to that stop.  The marking of a hard word also reads the end of the
passage, because the annotators of that study saw the whole paragraph.
"""

from dataclasses import dataclass
from hashlib import file_digest
import json
import math
from pathlib import Path
import re

import torch
from torch.nn import functional as F


SCHEMA = 'cogllm-reader-v2'
WEIGHTS = 'reader.safetensors'
CONFIG = 'reader.json'
MIN_SCALE = 0.02            # smallest predicted spread, as in training
WORD = re.compile(r"[^\W_]+(?:[’'\-][^\W_]+)*")
# A sentence ends at ., ! or ? (with any closing quotes or brackets) before whitespace and a capital,
# digit or opening quote, or at a line break.
END = re.compile(r'[.!?…]+["”’\')\]]*(?=\s+["β€œβ€˜(\[]?[A-Z0-9])|\n')
ABBREVIATIONS = frozenset({
    'mr', 'mrs', 'ms', 'dr', 'prof', 'sr', 'jr', 'st', 'mt', 'vs', 'etc', 'e.g', 'i.e', 'cf', 'al', 'fig',
    'no', 'vol', 'approx', 'inc', 'ltd', 'co', 'corp', 'u.s', 'u.k', 'jan', 'feb', 'mar', 'apr', 'jun',
    'jul', 'aug', 'sep', 'sept', 'oct', 'nov', 'dec',
})


def digest(path):
    with Path(path).open('rb') as stream:
        return file_digest(stream, 'sha256').hexdigest()


def sentences(text):
    """Half-open character spans of the sentences, without surrounding whitespace."""
    spans, start = [], 0
    for match in END.finditer(text):
        if match.group() != '\n':
            words = WORD.findall(text[start:match.start()])
            if words and words[-1].lower() in ABBREVIATIONS:
                continue
            if words and len(words[-1]) == 1 and words[-1].isupper():   # an initial, as in "J. Smith"
                continue
        end = match.start() if match.group() == '\n' else match.end()
        spans.append((start, end))
        start = end
    spans.append((start, len(text)))
    trimmed = []
    for left, right in spans:
        segment = text[left:right]
        left, right = left + len(segment) - len(segment.lstrip()), left + len(segment.rstrip())
        if left < right and WORD.search(text, left, right):
            trimmed.append((left, right))
    return trimmed


def token_at(offsets, end):
    """Index of the token that holds the character just before `end`, and whether it ends exactly there."""
    for index, (left, right) in enumerate(offsets):
        if left < end <= right:
            return index, right == end
    raise ValueError('No token covers this position')


@dataclass(frozen=True)
class Endpoint:
    name: str
    likelihood: str
    stops: str          # word, word_and_passage_end, sentence, sentence_path or passage_end
    center: float
    spread: float


class Reader(torch.nn.Module):
    """The fitted projection and the heads of the shown response types (evaluation mode only)."""

    def __init__(self, weights, config):
        super().__init__()
        self.depths = tuple(config['depths'])
        self.endpoints = {name: Endpoint(name, item['likelihood'], item['stops'], item['center'], item['spread'])
                          for name, item in config['endpoints'].items() if item.get('stops')}
        prefix = 'projections.p_shared.'
        self.maps = [weights[f'{prefix}maps.{i}.weight'].float() for i in range(len(self.depths))]
        self.bias = weights[prefix + 'bias'].float()
        self.heads = {name: (weights[f'heads.{name}.linear.weight'].float(), weights[f'heads.{name}.linear.bias'].float())
                      for name in self.endpoints}

    def project(self, states):
        """states: [stops, depths, hidden], rounded to BF16 as the training cache stored them -> [stops, width]"""
        states = F.layer_norm(states.to(torch.bfloat16).float(), states.shape[-1:])
        total = sum(states[:, depth] @ matrix.T for depth, matrix in enumerate(self.maps))
        return torch.tanh((total + self.bias) / len(self.maps) ** 0.5)

    def head(self, name, vectors):
        weight, bias = self.heads[name]
        return vectors @ weight.T + bias


class ReaderModel:
    """Backbone, tokenizer and reader; `analyze` returns every shown forecast for one passage."""

    def __init__(self, backbone, tokenizer, reader, config, *, max_tokens=None):
        self.backbone, self.tokenizer, self.reader, self.config = backbone, tokenizer, reader, config
        self.max_tokens = max_tokens
        self.forwards = 0

    @classmethod
    def load(cls, folder, backbone_folder, *, device='cpu', max_tokens=None):
        """Load a release folder that holds reader.json, reader.safetensors and manifest.json."""
        import transformers
        from safetensors.torch import load_file
        from tokenizers import Tokenizer

        from research.backbone_transfer.extract import load_language_model

        folder, backbone_folder = Path(folder), Path(backbone_folder)
        manifest = json.loads((folder / 'manifest.json').read_text(encoding='utf-8'))
        if manifest.get('schema') != SCHEMA:
            raise ValueError('This folder does not hold a CogLLM reader release')
        for name, expected in manifest['files'].items():
            if digest(folder / name) != expected:
                raise ValueError(f'Released file differs from its manifest: {name}')
        config = json.loads((folder / CONFIG).read_text(encoding='utf-8'))
        if backbone_folder.name != config['backbone']['revision']:
            raise ValueError('The backbone snapshot is not the revision the reader was trained on')
        encoder, spec = load_language_model(backbone_folder, 'qwen', torch, transformers, serving_device=device)
        if len(encoder.layers) != config['depths'][-1]:
            raise ValueError('The backbone has a different number of layers')
        tokenizer = Tokenizer.from_file(str(backbone_folder / 'tokenizer.json'))
        reader = Reader(load_file(str(folder / WEIGHTS)), config)
        return cls(encoder, tokenizer, reader, config, max_tokens=max_tokens)

    def encode(self, text):
        encoded = self.tokenizer.encode(text, add_special_tokens=False)
        if not encoded.ids:
            raise ValueError('The passage has no tokens')
        if self.max_tokens is not None and len(encoded.ids) > self.max_tokens:
            raise ValueError(f'Please shorten the passage to {self.max_tokens} model tokens or fewer.')
        return encoded

    @torch.inference_mode()
    def states(self, ids, positions):
        """Backbone states at the given token positions: [positions, depths, hidden], from one forward."""
        device = next(self.backbone.parameters()).device
        answer = self.backbone(input_ids=torch.tensor([list(ids)], device=device), use_cache=False,
                               output_hidden_states=True, output_attentions=False)
        self.forwards += 1
        count = len(self.backbone.layers)
        shift = len(answer.hidden_states) - count     # 1 when the embedding output comes first
        layers = [answer.last_hidden_state if depth == count else answer.hidden_states[depth - 1 + shift]
                  for depth in self.reader.depths]
        index = torch.tensor(list(positions), device=device)
        return torch.stack([layer[0, index] for layer in layers], dim=1).float().cpu()

    def forecast(self, vectors, *, words, sentences_at, passage):
        """Forecasts from projected vectors.  `words` and `sentences_at` index rows of `vectors`."""
        out = {}
        for name, endpoint in self.reader.endpoints.items():
            if endpoint.stops == 'word_and_passage_end':
                pair = torch.cat((vectors[words], vectors[passage].expand(len(words), -1)), dim=1)
                out[name] = F.softmax(self.reader.head(name, pair), dim=1)[:, 1]
            elif endpoint.stops == 'word':
                out[name] = F.softmax(self.reader.head(name, vectors[words]), dim=1)[:, 1]
            elif endpoint.stops == 'sentence_path':     # first report along the sentences after the first
                hazard = torch.sigmoid(self.reader.head(name, vectors[sentences_at[1:]])[:, 0])
                survival = torch.cumprod(torch.cat((hazard.new_ones(1), 1 - hazard)), dim=0)
                out[name] = {'hazard': hazard, 'first': survival[:-1] * hazard, 'never': survival[-1]}
            elif endpoint.stops == 'sentence':      # a log time, from the second sentence on as in the study
                raw = self.reader.head(name, vectors[sentences_at[1:]])
                out[name] = {'mean': raw[:, 0] * endpoint.spread + endpoint.center,
                             'scale': (F.softplus(raw[:, 1]) + MIN_SCALE) * endpoint.spread}
            elif endpoint.stops == 'passage_end':
                raw = self.reader.head(name, vectors[passage:passage + 1])[0]
                out[name] = {'mean': raw[0] * endpoint.spread + endpoint.center,
                             'scale': (F.softplus(raw[1]) + MIN_SCALE) * endpoint.spread}
            else:
                raise ValueError(f'Unknown stop type for {name}')
        return out

    def analyze(self, text):
        """Every shown forecast for one passage, with character offsets into `text`."""
        if not isinstance(text, str) or not text.strip():
            raise ValueError('Paste a passage first.')
        encoded = self.encode(text)
        offsets = [tuple(pair) for pair in encoded.offsets]
        words = [match.span() for match in WORD.finditer(text)]
        spans = sentences(text)
        if not words or not spans:
            raise ValueError('The passage has no words.')
        word_tokens = [token_at(offsets, end) for _, end in words]
        sentence_tokens = [token_at(offsets, end) for _, end in spans]
        passage_token = token_at(offsets, len(text.rstrip()))
        positions = sorted({index for index, _ in word_tokens + sentence_tokens + [passage_token]})
        row = {position: i for i, position in enumerate(positions)}
        before = self.forwards
        vectors = self.reader.project(self.states(encoded.ids, positions))
        if self.forwards != before + 1:
            raise RuntimeError('Each passage requires exactly one backbone forward')
        values = self.forecast(vectors, words=[row[i] for i, _ in word_tokens],
                               sentences_at=[row[i] for i, _ in sentence_tokens], passage=row[passage_token[0]])
        shown = self.config['shown']
        result = {'tokens': len(encoded.ids), 'words': [], 'sentences': [], 'passage': {}}
        for k, ((start, end), (token, exact)) in enumerate(zip(words, word_tokens)):
            item = {'start': start, 'end': end, 'text': text[start:end], 'token': token, 'exact_stop': exact}
            for name in shown['word']:
                item[name] = float(values[name][k])
            result['words'].append(item)
        path = values[shown['path']]
        times = values[shown['time']]
        for k, ((start, end), (token, exact)) in enumerate(zip(spans, sentence_tokens)):
            item = {'start': start, 'end': end, 'token': token, 'exact_stop': exact}
            if k:
                item[shown['path'] + '.hazard'] = float(path['hazard'][k - 1])
                item[shown['path'] + '.first'] = float(path['first'][k - 1])
                item[shown['time'] + '.seconds'] = math.exp(float(times['mean'][k - 1]))
            result['sentences'].append(item)
        if len(spans) > 1:
            result['passage'][shown['path'] + '.anywhere'] = 1 - float(path['never'])
        ease = values[shown['passage']]
        result['passage'][shown['passage']] = float(ease['mean'])
        result['passage'][shown['passage'] + '.scale'] = float(ease['scale'])
        quantiles = self.config['endpoints'][shown['passage']]['fitting_quantiles']
        result['passage'][shown['passage'] + '.percentile'] = percentile(quantiles, float(ease['mean']))
        result['passage']['exact_stop'] = passage_token[1]
        return result


def percentile(quantiles, value):
    """Share (0-100) of the fitting excerpts whose observed value lies below `value`, from 101 quantiles."""
    if value <= quantiles[0]:
        return 0.0
    if value >= quantiles[-1]:
        return 100.0
    for i in range(1, len(quantiles)):
        if value <= quantiles[i]:
            low, high = quantiles[i - 1], quantiles[i]
            return i - 1 + (value - low) / (high - low) if high > low else float(i)
    return 100.0