File size: 12,118 Bytes
bc415db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""A fixed three-dimensional PCA projection of input token embeddings."""
import html
import json

import torch


def text_snapshot(tokens, tokenizer, projection):
    """Map displayed text back to actual token occurrences, including byte fragments."""
    from tokenizers.decoders import DecodeStream
    text = tokenizer.decode(tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False)
    points = [{"n": n, "id": token_id, "xyz": projection.point(token_id),
               "label": tokenizer.decode([token_id], skip_special_tokens=False,
                                          clean_up_tokenization_spaces=False)}
              for n, token_id in enumerate(tokens)]
    segments, pending, decoded = [], [], ""
    try:
        decoder = DecodeStream(skip_special_tokens=True)
        special = set(tokenizer.all_special_ids)
        for n, token_id in enumerate(tokens):
            if token_id not in special:
                pending.append(n)
            chunk = decoder.step(tokenizer.backend_tokenizer, token_id)
            if chunk:
                segments.append({"text": chunk, "indices": pending})
                pending = []
                decoded += chunk
        if text.startswith(decoded) and decoded != text:
            segments.append({"text": text[len(decoded):], "indices": pending})
            decoded = text
        if decoded != text:
            segments = []
    except (AttributeError, TypeError, ValueError):
        segments = []
    return {"text": text, "segments": segments, "points": points}


class TokenProjection:
    def __init__(self, weights):
        weights = weights.detach().float().cpu()
        self.weights = weights
        indices = torch.linspace(0, len(weights) - 1, min(2048, len(weights))).long()
        sample = weights[indices]
        center = sample.mean(0)
        sample = sample - center
        dimensions = min(3, *sample.shape)
        with torch.random.fork_rng(devices=[]):
            torch.manual_seed(42)
            _, _, basis = torch.pca_lowrank(sample, q=dimensions, center=False, niter=3)
        coords = (weights - center) @ basis
        scale = torch.linalg.vector_norm(sample @ basis, dim=1).quantile(.95).clamp_min(1e-6)
        coords = coords / scale * 2.4
        self.coords = torch.nn.functional.pad(coords, (0, 3 - dimensions)).tolist()
        from projection_axes import projected_dimension_axes
        padded_basis=torch.nn.functional.pad(basis,(0,3-dimensions))
        self.dimension_axes=projected_dimension_axes(padded_basis,center,scale,"input_embeddings")

    def point(self, token_id):
        return self.coords[token_id]

    def relatives(self, token_id, previous):
        """Closest distinct earlier tokens, scored in the original embedding space."""
        latest = {other_id: index for index, other_id in previous if other_id != token_id}
        if not latest:
            return []
        ids = list(latest)
        scores = torch.nn.functional.cosine_similarity(self.weights[ids].float(), self.weights[token_id][None].float(), dim=1)
        results = []
        for position in torch.argsort(scores, descending=True)[:3].tolist():
            score = float(scores[position])
            if torch.isfinite(scores[position]) and score > 0:
                results.append({"n": latest[ids[position]], "score": round(score, 5)})
        return results


def frame(flow, store, full=False):
    with flow.view_lock:
        return _frame(flow, store, full)


def _frame(flow, store, full=False):
    flow.view_revision += 1
    tokens = flow.tokens.copy()
    points = []
    if store.projection is not None and flow.model_key == store.key:
        first_new = flow.space_history[-1]["n"] + 1 if flow.space_history else 0
        for index in range(first_new, len(tokens)):
            token_id = tokens[index]
            piece = store.tokenizer.decode([token_id], skip_special_tokens=False,
                                            clean_up_tokenization_spaces=False)
            previous = list(enumerate(tokens[max(0, index - 512):index], start=max(0, index - 512)))
            links = store.projection.relatives(token_id, previous)
            flow.space_history.append({"n": index, "id": token_id, "label": piece,
                                       "xyz": store.projection.point(token_id), "links": links})
        flow.space_history = flow.space_history[-512:]
        for point in flow.space_history:
            row = flow.attention_history.get(point["n"])
            if row is not None:
                point["attention"] = row
                for link in point["attention"]["links"]:
                    if "id" in link and "xyz" not in link:
                        link["xyz"] = store.projection.point(link["id"])
                        link["label"] = ("[boundary]" if link["n"] == -1 else
                                         store.tokenizer.decode([link["id"]], skip_special_tokens=False,
                                                                clean_up_tokenization_spaces=False))
        points = flow.space_history[-512 if full else -48:]
    data = {"continue_automatically": flow.continue_automatically, "stream": flow.stream_id, "revision": flow.view_revision, "paused": flow.paused, "running": flow.running,
            "ended": flow.ended, "points": points}
    axes=getattr(store.projection,"dimension_axes",None)
    if axes is not None and (full or flow.sent_dimension_axes_key != store.key):
        data["dimension_axes"]=axes
        flow.sent_dimension_axes_key=store.key
    if flow.layer_rows is not None and store.projection is not None:
        queries = sorted(q for q in flow.layer_queries if q >= max(0, len(tokens) - 513))
        if not flow.paused:
            queries = queries[-1:]
        rows, target_indices = [], set()
        for query in queries:
            slot = query % 512
            packed = flow.layer_rows[slot]
            indices = packed[:, :, 0].to(torch.int32).tolist()
            rows.append({"query": query, "indices": indices,
                         "scores": packed[:, :, 1].tolist(), "keys": flow.layer_keys[slot].tolist()})
            if not flow.paused:
                target_indices.update(n for layer in indices for n in layer if -1 <= n < len(tokens))
        from engine import start_id
        boundary = start_id(store.model, store.tokenizer)
        targets = []
        if flow.paused:
            target_indices.add(-1)  # other targets are already in the full text snapshot
        for n in sorted(target_indices):
            token_id = boundary if n == -1 else tokens[n]
            targets.append({"n": n, "id": token_id, "xyz": store.projection.point(token_id),
                            "label": "[boundary]" if n == -1 else store.tokenizer.decode(
                                [token_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)})
        data["attention_layers"] = {"count": flow.layer_rows.shape[1], "rows": rows, "targets": targets}
    if flow.paused and store.projection is not None and flow.model_key == store.key:
        if flow.text_snapshot_cache is None or flow.text_snapshot_cache[0] != len(tokens):
            flow.text_snapshot_cache = (len(tokens), text_snapshot(tokens, store.tokenizer, store.projection))
        data["text_view"] = flow.text_snapshot_cache[1]
    if flow.representations is not None:
        data["representations"] = flow.representations.snapshot(len(tokens), full=full or flow.paused)
    payload = json.dumps(data, ensure_ascii=True)
    return '<div data-flow-frame="' + html.escape(payload, quote=True) + '"></div>'


SCENE = '''<div id="token-universe">
  <canvas aria-label="Live 3D projection of generated token embeddings. Drag to orbit; scroll to zoom."></canvas>
  <div class="space-top"><span class="space-brand">AUTOMATIC WRITING / TOKEN SPACE</span><span class="space-count">Waiting for tokens</span></div>
  <div class="space-empty">A space for the next thought.<small>Press Begin. Tokens appear here, then fade.</small></div>
  <div class="space-tools">
    <label>View <select data-space-mode><option value="live">Live · fade after 6s</option><option value="history">History · last 512 tokens</option><option value="representations">Layer representations</option></select></label>
    <label>Connections <select data-space-links><option value="attention">Attention weights</option><option value="order">Generation order</option><option value="similarity">Embedding similarity</option><option value="none">None</option></select></label>
    <button type="button" data-space-reset>Reset camera</button>
    <button type="button" data-space-back disabled>Step back</button>
    <button type="button" data-space-forward disabled>Step forward</button>
    <span data-space-step>Live</span>
  </div>
    <section class="dimension-axes-controls" aria-label="Projected dimension axes">
      <div class="dimension-axes-top"><label><input type="checkbox" data-dimension-axes> All projected dimensions <span data-dimension-count></span></label><button type="button" data-dimension-options aria-expanded="false">Options</button></div>
      <div class="dimension-axes-options" hidden>
        <p class="dimension-axis-status" data-dimension-status></p>
        <label>Line opacity <input type="range" min="0.005" max="0.15" step="0.005" value="0.04" data-dimension-opacity aria-label="Dimension axis opacity"></label>
        <label>Origin <select data-dimension-origin><option value="mean">Projection centre</option><option value="raw">Original vector origin</option></select></label>
        <p>White lines show every original feature direction projected into this 3D space. They are not attention links, model layers, or individual learned parameters. All lines use one common extent for visibility, preserving their relative projected lengths. Length is not importance. The default translates directions to the projection centre; the other option uses the projected zero-vector origin. Hidden-state dimensions are unit-normalised in representation mode. Hover a line to identify its dimension index.</p>
      </div>
    </section>
  <div class="space-detail">
    <section class="representation-controls" hidden>
      <h3 class="attention-title">Representations through layers</h3>
      <p class="representation-note" data-representation-note></p>
      <label class="representation-layer-label">Layer <input type="range" data-representation-layer min="0" max="1" step="1" value="0" aria-label="Representation layer"></label>
      <p class="representation-stage" data-representation-stage>Input to first layer</p>
      <div class="representation-actions"><button type="button" data-representation-play>Play layers</button><label><input type="checkbox" data-representation-trail checked> Selected-token trail</label></div>
      <details class="attention-help"><summary>How to read representations</summary><p>Each token shows its hidden states recorded when it was processed to predict the following token. These are historical token recordings, not one full-context snapshot. One shared PCA projection is fitted across the first captured tokens and all layers, then frozen for the stream. These axes differ from the input-embedding view. Only context tokens with saved trajectories can be plotted. Vectors are normalised to compare directions. The input stage may include positional processing; the final stage includes the model's final normalisation. Animation interpolates between recorded stages. Movement is not a direct measure of meaning or importance. Only the most recent 128 processed tokens are retained.</p></details>
    </section>
    <details class="representation-connection-details" open><summary>Connection details</summary><div class="connection-detail" aria-live="polite">Click a token to inspect its earlier neighbours.</div></details>
  </div>
  <div class="space-edge-tooltip" role="tooltip" hidden></div>
  <div class="space-bottom"><span>Drag to orbit · Shift-drag to pan · Wheel to zoom · Double-click a token to focus</span><span>Embedding PCA</span></div>
</div>'''