"""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 '
' SCENE = '''
AUTOMATIC WRITING / TOKEN SPACEWaiting for tokens
A space for the next thought.Press Begin. Tokens appear here, then fade.
Live
Connection details
Click a token to inspect its earlier neighbours.
Drag to orbit · Shift-drag to pan · Wheel to zoom · Double-click a token to focusEmbedding PCA
'''