When I showed my frozen model viewer, someone asked where the names and edges even came from. Someone else asked how I could map weights to behavior without running the model. Those are two different questions, and I hadn't made clear which one I was trying to answer.
After building that viewer, I noticed it isn't widely known how much structure you can read straight from a frozen model before a runtime ever touches it. I'm not writing this to argue, or to claim that a spatial geometric view is equal to a behavioral one. I'm sharing a practical way to read what is stored in the frozen weights, follow how tensors connect across the blocks, and show that all that traces back to the raw bytes. In the hopes it well be valuable to you.
So, here's the thing.
You do not need to run a model to explore the geometry of its stored parameters, or walk its wiring. What you need is to choose a checkpoint to read, the model's matching tokenizer (so you can display token names), a way to create an architecture map so you can know which parts connect, and finally, a way to measure the things I explain here, mechanically.
This guide is my attempt to walk you through how to go from a byte offset in a SafeTensors file to a token neighborhood graph, a 3D map, and a cross-layer weight walk, all without needing to load a model runtime or a forward pass.
Before we begin, it is important to understand that I come at this as a systems engineer working at the architecture and data-structure level, not the runtime level. And because my interest has always been in the data and data structures themselves, the language I use is likely more mechanical than what you might be used to in other machine learning posts. When I describe something in terms of byte spans, array axes, or structural nodes, don't read that as me being vague: treat it more as me trying to be exact about what is actually stored on disk, and not from a runtime calculation perspective.
Before doing anything, I want to know what is in the file I am working on and if I can trace every visual element back to its bytes. So when you look at a frozen model for the first time, those are the parts you should be interested in. I'd say you can view it as three strictly separate layers:
- Source data and architecture wiring: The raw tensor bytes in the file, the token strings in the tokenizer table, and the architecture rules that say which tensor dimensions connect to which. When an edge represents a stored weight, you can point to its tensor, row, column, and an exact byte span.
- Derived full-space measurements: Numbers computed directly from those stored arrays at their full width, such as the cosine between two 1,024-element embedding rows.
- Display structures: The 2D or 3D coordinates, bounding hierarchies, and screen layouts built so a human can move around the data without altering it. None of these pictures exists inside the checkpoint file.
That separation gives you three rules when reading the map:
- A measured similarity edge means two stored rows have a reported cosine in their full-width array space.
- Two nearby dots on screen only mean two rows landed near each other after projecting down to 2D or 3D. Check their full-width score before trusting screen proximity.
- A structural wiring edge means the architecture connects one array axis, weight, or stage to the next. By itself, it says nothing about how much signal moved across that connection during a runtime execution.
My starting point was simple: when a model isn't running, everything it knows has to sit somewhere in its weights. Looking at the arrays mechanically, and realizing inference must be a chain of offsets applied to a carried vector from block to block, and at the end (especially in a tied-embedding model like Qwen 3.5, where the input and output vocabulary tables are the exact same bytes), the final vector is compared back against those token rows.
Mechanically, it made sense that a vector's angle (direction) would be what associates with a token, since layer-by-layer execution works by offsetting and rotating that direction, while the magnitude (length) affects how strongly each contribution pulls.
To test this, I separated the magnitudes from the angles to make them more observable. And then I tested that split with paired probes across all 24 layers of the Qwen 3.5 0.8B model I had been working on, the separation was stark:
- Direction alone identified which token was present99.6% of the time across all layers (against a14.3% random baseline).
- Magnitude alone identified the token only31.3% of the time.
And across 480 layer observations with different surrounding context, the context
never once flipped a token's direction (0 / 480 reversals; simple prompt + token addition also failed with 0.9038 relative error). What happened instead
was, when multiple paths met at a shared intersection, their relative incoming
magnitudes damped the radius and rotated the combined resultant into a
context-conditioned cone, before realigning toward the output table at the final
block. Direct weight interventions showed the same split statically: scaling 16
complete gate_proj rows across layers 0, 7, 15, 23 by 0.25x and 4.0x
changed 0 / 16 nearest-token owners, whereas rotating them halfway toward
'ĠRust' at constant norm changed all 16 / 16.
Two other mechanical observations while inspecting Qwen 3.5 0.8B pushed me the rest of the way toward building the spatial viewer I shared before:
- Weights step from layer to layer by
90 degrees + a small delta: When I measured corresponding projection rows (gate,up,QKV,Z) from one layer to the next, the angle consistently shifted by90 degreesplus or minus a small signed delta (roughly89° to 90°, within a tight ~2°band). Think of it mechanically like a physical ring indexing one quarter-turn per layer, plus a small signed offset that carries the specific adjustment onto the next axis. Whether the math says90°is expected in high dimensions is not the point. Mechanically, it means moving from layer to layer isn't an untraceable black-box scramble: it follows a deterministic, observable stepping rule (quarter-turn + signed delta, paired with radius) that can be understood causally and exploited directly, for instance by stepping a single resident layer buffer in place from layer to layer instead of holding 18 separate linear layers as unrelated blobs. - Rotational activity concentrates late, especially around layer 18: Qwen
3.5 0.8B is built from a repeating3 linear-attention + 1 full-attention block pattern across its 24 layers (
0..2 -> 3,4..6 -> 7,8..10 -> 11,12..14 -> 15,16..18 -> 19, and20..22 -> 23). Watching both token-matched gate angles and accumulated block deltas across those six cycles, the directional shifts and norm buildup weren't spread evenly across all layers: most of the heavy rotational shift concentrated aroundlayer 18 (the fifth3 + 1cycle,16..18 -> 19), right before the final20..23block makes the large closing turn toward the output table.
Put those pieces together and you can see why a flat tensor dump wasn't enough, and why a frozen spatial explorer makes sense structurally:
- Angle carries identity and membership , and those frozen directions and shared intersections are already sitting in the checkpoint file at rest.
- Layer transitions follow a deterministic mechanical step (
90° + deltaonto the next axis, while individual coordinates share superposed paths), so structure across depth is something you can trace and index as a space rather than treating layers as disconnected black boxes. - Live magnitude belongs to the runtime: when a prompt executes, incoming magnitudes at shared intersections weight, damp, and rotate the resultant across that static structure.
Typically, I start with the smallest concrete question: where does one weight live inside the file? Once you can compute that address, you can read one scalar or one row on demand without a multi-gigabyte checkpoint into RAM.
A SafeTensors file is a flat binary container. It starts with an 8-byte
unsigned little-endian integer N giving the byte length of a UTF-8 JSON
header, followed immediately by N bytes of JSON. The raw tensor payload
starts at byte 8 + N. Each entry in the JSON header gives a dtype, a
shape array, and a half-open byte range data_offsets: [start, end]
relative to the start of the payload, not to byte zero of the file.
For a dense, row-major 2D matrix with C columns and B bytes per element:
tensor_start = 8 + N + start
row_start = tensor_start + row * C * B
scalar_start = row_start + column * B
Validate the rank, shape, dtype, file bounds, and exact byte span
(end - start == rows * C * B) before seeking. Then read B bytes for a
single weight or C * B bytes for a row. F32 is a 4-byte little-endian IEEE
float. BF16 is 2 bytes: read them as a 16-bit little-endian unsigned integer,
shift the bits left by 16, and reinterpret those 32 bits as F32. That decodes
the exact stored BF16 value; it does not invent precision that wasn't saved
in the file.
To look up a token's row, find the input embedding table declared by the
architecture. A tensor name like model.embed_tokens.weight or
model.language_model.embed_tokens.weight is a hint, not a guarantee: always
confirm its role and [vocab_slots, hidden_width] shape against the model
layout. In that layout, integer token ID t indexes row t.
Join those row indices against the matching tokenizer.json (model.vocab and
added_tokens). Don't assume every row in the embedding array has a token
string: checkpoints often pad vocab_slots up to an alignment boundary,
leaving unused rows at the end of the table. Keep exact integer IDs,
whitespace, and special-token metadata intact. A raw vocabulary key is also not
always final display text: byte-level BPE stores markers such as Ġ for a
leading space ('ĠRust' vs 'rust') or raw byte tokens. Keep the raw key
accessible so distinct rows don't get collapsed under the same label.
Once you can read two rows of equal width from the same table, you can measure how closely they point in the same direction.
Treat embedding row e[t] as a fixed-length array of D numbers. Divide each
nonzero row by its Euclidean length to get its unit direction u[t]:
cosine(a, b) = dot(e[a], e[b]) / (norm(e[a]) * norm(e[b]))
= dot(u[a], u[b])
+1 is the same direction, 0 is perpendicular, and -1 is opposite.
Normalizing splits direction away from length on purpose: [1, 0] and [10, 0]
both have unit direction [1, 0] and score 1. Because direction is what
carries almost all token identity while magnitude acts as radial weight when
vectors combine, a good data model stores unit direction and magnitude as two
separate fields rather than mixing them or throwing length away silently. Keep
the static claim clean too: cosine measures directional alignment between two
stored rows, not synonymy and not how much live magnitude will arrive in a
given prompt.
To inspect one token's neighborhood, normalize its row, stream sequentially
across the embedding table on disk or in a buffer, and maintain a fixed-size
min-heap of the top k scores. Skip the query ID itself, skip zero or
non-finite rows, and skip unmapped padding rows if you only want valid tokens.
Break ties deterministically by integer token ID so two implementations always
return the exact same neighbor list.
Connecting a query token to its top k neighbors gives you a simple hub. If
you also compute cosines between those k neighbors, you can see whether
the local web breaks into distinct pockets (say, lowercase/uppercase variants
on one side and related domain terms on another). If you want stricter grouping
across a larger set, keep edges only where two tokens appear in each other's
top k (mutual nearest neighbors), and test a few values of k so an
arbitrary cutoff doesn't fool you.
Data-structure-wise, a single query scan costs O(V * D) multiply-adds over V
rows of width D plus O(log k) heap updates when a row enters the top k.
You never need to allocate a V * V matrix. If you later put an approximate
index in front of the table, mark those results as approximate and recompute
exact cosines from the source rows for anything you display.
Tables of cosines are exact, but hard to browse. To put tens or hundreds of
thousands of token roots on screen, you need a deterministic way to map D
numbers down to three coordinates (x, y, z).
A simple one-pass method of doing that is to pick three independent rows from
the table as anchors and orthogonalize them with Gram-Schmidt: from each anchor,
subtract its dot-product projections onto the previous axes, then normalize the
remainder. That yields three perpendicular unit axes (axis_x, axis_y, axis_z)
of width D. Every unit row u then projects to three numbers:
p(u) = (dot(u, axis_x), dot(u, axis_y), dot(u, axis_z))
In my Rust explorer, opening the checkpoint builds this basis from the first three present tokenizer IDs and writes a compact 8-byte display record for each present token root (three signed 16-bit coordinates plus presence flags), then indexes those 3D points in a static bounding-volume hierarchy (BVH). That way, camera orbit, pan, and frustum culling only traverse small integer bounds in RAM and never re-read the checkpoint. You could swap in PCA axes if you prefer axes aligned with table-wide spread, and nothing in the underlying source index would change.
The main rule is to treat those 3D coordinates as lossy display state,
never as source truth. Take a 4D example and keep only the first three slots:
the unit vectors (0.6, 0, 0, 0.8) and (0.6, 0, 0, -0.8) both project to
(0.6, 0, 0), even though their actual 4D dot product is 0.36 - 0.64 = -0.28.
Screen layout is for navigation and culling; edges and scores must always come
from the full-width vectors.
For a local view centered on a chosen token q, put q at the origin and
subtract q's component from each normalized neighbor u:
t = u - dot(u, q) * q. Orthogonalizing three independent residual vectors t
gives a local 3D basis showing the directions in which neighbors spread away
from q. You can set distance from the origin directly from angle
(acos(clamp(cosine, -1, 1))), or space dense clusters out for label
readability, as long as your UI keeps layout spacing separate from the measured
cosine.
Here is a minimal standalone reader using only the Python 3.10+ standard
library (drafted with AI assistance and checked against my Rust index). It
parses the 8-byte SafeTensors header, validates the target tensor's byte span,
optionally joins tokenizer.json keys so unmapped reserve rows are skipped,
streams the rows once to build the 3-axis basis and top-k heap, and prints
both full-width cosines and 3D coordinates.
On a ~250k-row vocabulary in pure Python without NumPy, a full sequential scan takes roughly 10 to 20 seconds.
import heapq
import json
import math
from operator import mul
import os
import struct
import sys
dot = getattr(math, "sumprod", lambda a, b: sum(map(mul, a, b)))
def read_exact(file, size):
data = file.read(size)
if len(data) != size:
raise ValueError("truncated file")
return data
def unit(v):
length = math.hypot(*v)
if length == 0 or not math.isfinite(length):
return None
inv = 1.0 / length
return tuple(x * inv for x in v)
def load_labels(tokenizer_path):
with open(tokenizer_path, "r", encoding="utf-8") as file:
tok = json.load(file)
labels = {idx: key for key, idx in tok.get("model", {}).get("vocab", {}).items()}
for entry in tok.get("added_tokens", []):
labels[entry["id"]] = entry["content"]
return labels
def inspect(file, tensor_name, query_id, labels=None, k=8):
size = os.fstat(file.fileno()).st_size
header_size = struct.unpack("<Q", read_exact(file, 8))[0]
if not 0 < header_size <= min(size - 8, 100_000_000):
raise ValueError("invalid header size")
desc = json.loads(read_exact(file, header_size))[tensor_name]
dtype = desc["dtype"]
if dtype not in ("BF16", "F32") or len(desc["shape"]) != 2:
raise ValueError("expected rank-2 BF16 or F32 tensor")
rows, width = desc["shape"]
start, end = desc["data_offsets"]
payload = 8 + header_size
row_bytes = width * (2 if dtype == "BF16" else 4)
if not (rows > 0 and width >= 3 and k > 0
and 0 <= query_id < rows and 0 <= start <= end <= size - payload
and end - start == rows * row_bytes):
raise ValueError("invalid matrix span, dimensions, or query")
def read_row():
raw = read_exact(file, row_bytes)
if dtype == "F32":
return struct.unpack(f"<{width}f", raw)
expanded = bytearray(4 * width)
expanded[2::4] = raw[0::2]
expanded[3::4] = raw[1::2]
return struct.unpack(f"<{width}f", expanded)
file.seek(payload + start + query_id * row_bytes)
query = unit(read_row())
if query is None:
raise ValueError("query row has no valid direction")
axes, anchors, neighbors = [], [], []
file.seek(payload + start)
for token_id in range(rows):
if labels is not None and token_id not in labels:
file.seek(row_bytes, os.SEEK_CUR)
continue
direction = unit(read_row())
if direction is None:
continue
if len(axes) < 3:
residual = direction
for axis in axes:
component = dot(residual, axis)
residual = tuple(
x - component * y for x, y in zip(residual, axis)
)
if dot(residual, residual) > 1e-12:
axes.append(unit(residual))
anchors.append(token_id)
if token_id != query_id:
score = max(-1.0, min(1.0, dot(query, direction)))
item = (score, -token_id, direction)
if len(neighbors) < k:
heapq.heappush(neighbors, item)
elif item > neighbors[0]:
heapq.heapreplace(neighbors, item)
if len(axes) != 3:
raise ValueError("need three independent embedding directions")
if labels is not None:
print("query:", query_id, repr(labels.get(query_id, "<unlabeled>")))
print("axes from token IDs:", anchors)
print("token_id\tcosine\tx\ty\tz\tlabel")
for score, negative_id, direction in sorted(neighbors, reverse=True):
tid = -negative_id
point = "\t".join(f"{dot(direction, axis):.6f}" for axis in axes)
label = repr(labels.get(tid, "")) if labels is not None else ""
print(f"{tid}\t{score:.6f}\t{point}\t{label}")
if __name__ == "__main__":
path, tensor_name, query, *rest = sys.argv[1:]
labels = load_labels(rest[0]) if rest else None
with open(path, "rb") as file:
inspect(file, tensor_name, int(query), labels)
Running that script against Qwen 3.5 0.8B (model.safetensors and
tokenizer.json) on token ID 32671 ('ĠRust'):
python3 inspect_frozen.py model.safetensors model.language_model.embed_tokens.weight 32671 tokenizer.json
prints:
query: 32671 'ĠRust'
axes from token IDs: [0, 1, 2]
token_id cosine x y z label
22353 0.620285 -0.096485 -0.076601 -0.024758 'Ġrust'
34602 0.546217 -0.120175 -0.070902 -0.000364 'rust'
55355 0.344299 -0.115195 -0.164201 -0.028394 'Ġrustic'
94092 0.340527 -0.169135 -0.170923 -0.049361 'Ġrusty'
59218 0.330591 -0.182653 -0.127535 -0.008338 'ĠCargo'
24822 0.320358 -0.061104 -0.060072 -0.014342 '.rs'
22984 0.318060 -0.092266 -0.091563 0.004938 'ĠRuby'
35202 0.313016 -0.145921 -0.141656 -0.024726 'ĠRails'
Even from this single table scan, two data-level facts are easy to verify:
- Purely from stored
BF16rows and integer IDs,'ĠRust'already sits next to casing variants ('Ġrust','rust'), surface English relatives ('Ġrustic','Ġrusty'), Rust build/file tokens ('ĠCargo','.rs'), and related language/framework names ('ĠRuby','ĠRails'). Keeping the raw BPE key also shows why'Ġrust'(22353, with a leading space) and'rust'(34602, no leading space) are separate entries in the array. - Compare
'ĠCargo'(59218) and'.rs'(24822): their 1,024-wide cosines to'ĠRust'are nearly identical (0.331vs0.320), while their projectedxcoordinates differ by 3x (-0.183vs-0.061). That is the projection rule in practice: 3D coordinates organize the viewport, while the full-width dot product carries the measurement.
Reading one embedding table is straightforward. The harder data-structure problem shows up the moment you ask: how do I connect tokens to internal layer weights without blowing up memory?
Look at the sizes in Qwen 3.5 0.8B. The embedding table has 248,320 rows of
width H = 1,024. A single MLP matrix like layer 0's gate_proj.weight has
shape [3584, 1024], which is 3,670,016 scalars. If you tried to build an
explicit pointer graph from every token to every scalar in just that one
matrix, you would allocate nearly a trillion edges before touching the rest of
the 24 blocks.
You avoid that explosion by factorizing the graph through shared array dimensions instead of copying or materializing token-by-weight edges:
TokenRoot(t)
-> Component(i) (shared axis index i in 0 .. H-1)
-> Weight(tensor, j, i) (column i fixed, row j in 0 .. out-1)
-> Intersection(tensor, j) (row j fixed, where all H columns meet)
Because embed_tokens[vocab, H] and a downstream matrix W[out, H] both have
width H on their shared bus, index i is the exact join key between them:
- From
Component(i)into consumer matrices: hold columnifixed and vary rowjacross0 .. out-1. Direct offset arithmetic gives you every individual weightW[j, i]that reads from axisi, along with its exact 2-byte or 4-byte file span. - From
Weight(tensor, j, i)to its row intersection: hold rowjfixed and vary columniacross0 .. H-1. That enumerates every weight converging on output slotjof that matrix.
No weights are copied per token, and no billion-edge adjacency list exists in
RAM. Each weight remains one immutable byte span on disk, reachable from any
token root through shared column i.
You can also inspect how strongly a specific token's unit direction lines up
with individual weights along their shared column. Token t has unit entry
u[t][i] at column i. If the architecture places a per-column normalization
scale vector directly before W, column i also has a stored scale value
(gamma[i], or 1 + gamma[i] when the checkpoint stores zero-centered norm
weights, as Qwen 3.5 does). Pairing u[t][i] with that scaled weight gives an
exact static per-column relationship for (t, j, i) without copying the matrix.
When I ran that exact check across all 3,670,016 scalars of layer 0's
gate_proj.weight in Qwen 3.5 0.8B, both 'ĠRust' (32671) and 'Ġking'
(11148) had gate_proj.weight[5, 30] (at absolute file byte 537068196) in
their top eight individual weight relationships, while 'Ġwater' (2919) and
'Ġking' shared gate_proj.weight[5, 166] (at byte 537068468). Two distinct
token roots point to the exact same 2-byte address in the file; the weight
lives once, and ownership is just a typed relationship to its coordinate.
Four structural rules to keep this trustworthy:
- A shared index is a wiring slot, and ownership is shared rather than
exclusive. Column
30is where two arrays align by dimension, not a dedicated "Rust/king feature." One token reaches many weights, and one weight or row intersection can participate in several token directions at once without collision. - Don't prune away diffuse mass; group it losslessly. Even when the
strongest individual weights stand out clearly,
95%of a token's static contribution mass in layer0spans roughly75%of the matrix (2,682to2,704of3,584`` gate_projrows), and assigning one permanent token label per unrotated row leaves common tokens with zero rows. Instead of dropping "weak" weights, collapse wide runs (such as1,024shared axes) into lossless power-of-two ranges when zoomed out and split them down to exact leaves as you zoom in. - Frozen direction stays fixed; live magnitude rotates the resultant at
intersections. At
Intersection(tensor, j), allHcolumns meet. In the checkpoint, the participating weight directions and signs are fixed. During runtime execution, the relative magnitudes arriving along those inputs determine how much the combined vector damps and rotates at that intersection. In a static explorer, labelabs(W[j, i])as a stored coefficient and keep its sign separate. - Only join dimensions that the architecture actually wires together. Two
arrays having length
1,024does not automatically mean they share the same slot layout. Check the model's architecture definition for transposed matrices, packed multi-head or gate/up layouts, multi-file shard indexes (model.safetensors.index.json), and quantized block encodings.
Once single matrices are indexed by (tensor, row, column), walking across
blocks is an architecture-schema problem. The SafeTensors header tells you
each array's shape and byte offset; the architecture plan tells you which output
dimension becomes the next stage's input dimension.
Before writing traversal code, encode a strict table of the expected block
families and their shapes. For instance, in Qwen 3.5 0.8B's 24-layer text
backbone, 18 blocks use linear-attention tensor families and 6 blocks
(3, 7, 11, 15, 19, 23) use full-attention tensor families, while every block
carries norms, gate_proj, up_proj, down_proj, and residual returns, and
vision tensors sit in a separate submodel namespace. Validating names and
shapes up front ensures your walker never joins incompatible tensors by
accident because two names happened to end in down_proj.
Take a text block with shared hidden width H = 1,024 and MLP width
M = 3,584. Here gate_proj.weight and up_proj.weight are [M, H], and
down_proj.weight is [H, M]. Think of the residual stream simply as the
shared H-slot bus carried from block boundary to block boundary.
Using zero-based indices (7, 23, and 11 are arbitrary example slots to
show how indices hand off across model.language_model.layers.0 and layers.1):
- Token slot to MLP input column: Start at
embed_tokens.weight[t, 7], or at shared slot7after block0's attention return. Pass through the per-slot scale entrylayers.0.post_attention_layernorm.weight[7]into column7oflayers.0.mlp.gate_proj.weight[23, 7]andlayers.0.mlp.up_proj.weight[23, 7]. Column7is the input slot they both read from; row23is the intermediate slot they both write toward. - Represent the gated join as a structural node: At intermediate slot
23, the architecture combines thegateandupbranches elementwise after summing across all1,024columns and applying a gate nonlinearity. In a frozen data structure, represent that meeting point as a typedProductnode(layer = 0, feature = 23), not asgate_proj[23, 7] * up_proj[23, 7]. Multiplying two isolated weights across a nonlinear join would invent a number that neither the file nor the runtime actually uses. - Flip row to column on the way back out: Leaving intermediate slot
23, that index changes role from arow of[M, H]to acolumn of[H, M]inlayers.0.mlp.down_proj.weight[11, 23]. Row11ofdown_projlands back on shared residual slot11at the end of block0, which is the exact same slot11entering block1. In the graph, that residual return is a zero-byte structural link, not a weight read. - Branch into the next block and to the output table: At block
1's entry boundary, slot11connects forward both into block1's attention input tensors and straight along the residual bus to block1's MLP (such aslayers.1.mlp.up_proj.weight[5, 11]). Both paths exist simultaneously in the static topology. After the final block and final norm (norm.weight[i]), slotireaches the output vocabulary table: either a separatelm_headmatrix or, when embeddings are tied, the exact sameembed_tokens[vocab_id, i]byte address where tokenvocab_idstarted.
Attention and linear-attention stages fit the same data-model boundary. Their
projection matrices, convolution weights, and per-head or per-channel norm
arrays are ordinary static tensors with exact (tensor, row, column) addresses
and byte spans. Where the architecture mixes information across sequence
positions or recurrent state, there is no static token-to-token weight in the
file to read, because that routing only exists when a runtime processes a
sequence. Representing that boundary explicitly as a typed Context node lets
you walk into the projection weights and back out through out_proj without
pretending the checkpoint contains prompt-specific attention maps.
If you implement this in your own viewer, resist the urge to materialize the graph in memory. Keep the checkpoint read-only and make the graph virtual:
- Use small value types for positions: An enum or tagged struct such as
TokenRoot(u32),Component { boundary, index },Weight { tensor, row, col },Intersection { tensor, row },MlpProduct { layer, feature },Context { layer, family, feature },Residual { layer, index }, andOutputRoot(u32)takes only a few bytes and needs no heap allocation. - Compute neighbors by arithmetic, one page at a time: A
neighbors(pos)function consults your validated layer table and tensor shapes, yielding only the slice of outgoing or incoming positions needed for the current view or inspector page. - Seek and decode only what is inspected: Every
Weightposition already carries(tensor, row, col). Combine that with the tensor descriptor'ssource_data_offsetanddtypeto read the 2 or 4 bytes on demand when selected or displayed. - Keep screen layout separate from graph identity: Laying blocks out left to right with lanes for residual, context, and MLP stages gives a clean diagram of the wiring. Moving a lane on screen changes pixel or cell coordinates only; every node identity and file offset stays untouched.
That is the whole architectural boundary in one sentence: the frozen file already holds the identity-bearing directions and the shared intersections where paths meet, while a runtime supplies the live magnitudes that weight, damp, and rotate resultants across those intersections.
The first script in Section 4 only touched embed_tokens. Here is a second
standalone Python 3.10+ stdlib script (inspect_across_layers.py) so you can
test the cross-tensor and cross-layer claims directly on the same checkpoint
file in under 20 seconds, again with zero external packages.
It checks three things straight from the raw BF16 bytes:
- Cross-tensor individual weight addressing: folds layer
0'spost_attention_layernorm.weight(1 + gamma) into all3,670,016scalars oflayers.0.mlp.gate_proj.weightand prints the exact(row, col)@byteaddresses aligned with'ĠRust'(32671) and'Ġking'(11148). - The
90 degrees + signed deltalayer step: measures the exact angle between corresponding rows oflayers.0andlayers.1across projection families, and checks the local two-axis ruledest = sin(theta) * tangent + cos(theta) * source. - Depth behavior across Qwen's six
3 linear + 1 fullblocks: follows token-matchedgate_projdirections across all 24 layers to show where the step angle tightens around layer18(L16..L18 -> L19).
import heapq
import json
import math
from operator import mul
import struct
import sys
dot = getattr(math, "sumprod", lambda a, b: sum(map(mul, a, b)))
def open_safetensors(file):
header_size = struct.unpack("<Q", file.read(8))[0]
header = json.loads(file.read(header_size))
return 8 + header_size, header
def read_row_f32(file, payload, desc, row):
cols = desc["shape"][-1] if len(desc["shape"]) > 1 else desc["shape"][0]
dtype = desc["dtype"]
bpe = 2 if dtype == "BF16" else 4
offset = payload + desc["data_offsets"][0] + row * cols * bpe
file.seek(offset)
raw = file.read(cols * bpe)
if dtype == "F32":
return offset, bpe, struct.unpack(f"<{cols}f", raw)
expanded = bytearray(4 * cols)
expanded[2::4] = raw[0::2]
expanded[3::4] = raw[1::2]
return offset, bpe, struct.unpack(f"<{cols}f", expanded)
def read_matrix_units(file, payload, desc):
rows, cols = desc["shape"]
dtype = desc["dtype"]
bpe = 2 if dtype == "BF16" else 4
file.seek(payload + desc["data_offsets"][0])
out = []
for _ in range(rows):
raw = file.read(cols * bpe)
if dtype == "F32":
vals = struct.unpack(f"<{cols}f", raw)
else:
expanded = bytearray(4 * cols)
expanded[2::4] = raw[0::2]
expanded[3::4] = raw[1::2]
vals = struct.unpack(f"<{cols}f", expanded)
length = math.hypot(*vals)
if length > 0 and math.isfinite(length):
inv = 1.0 / length
out.append(tuple(x * inv for x in vals))
else:
out.append(None)
return out
def unit(v):
inv = 1.0 / math.hypot(*v)
return tuple(x * inv for x in v)
def verify(path):
p = "model.language_model."
with open(path, "rb") as f:
payload, h = open_safetensors(f)
emb = h[p + "embed_tokens.weight"]
norm0 = h[p + "layers.0.post_attention_layernorm.weight"]
gate0 = h[p + "layers.0.mlp.gate_proj.weight"]
seeds = [(32671, "Rust"), (11148, "king")]
seed_dirs = [unit(read_row_f32(f, payload, emb, tid)[2]) for tid, _ in seeds]
gamma0 = [1.0 + g for g in read_row_f32(f, payload, norm0, 0)[2]]
rows, _ = gate0["shape"]
top = [[] for _ in seeds]
for r in range(rows):
row_off, bpe, vals = read_row_f32(f, payload, gate0, r)
for c, w in enumerate(vals):
folded = w * gamma0[c]
byte_addr = row_off + c * bpe
for idx, u in enumerate(seed_dirs):
contrib = u[c] * folded
item = (abs(contrib), -r, -c, contrib, byte_addr)
heap = top[idx]
if len(heap) < 8:
heapq.heappush(heap, item)
elif item > heap[0]:
heapq.heapreplace(heap, item)
print("1. CROSS-TENSOR INDIVIDUAL WEIGHTS (layers.0.mlp.gate_proj.weight)")
for (_, name), heap in zip(seeds, top):
entries = sorted(heap, reverse=True)
formatted = ", ".join(
f"({-r},{-c})@{addr}" for _, r, c, _, addr in entries[:6]
)
print(f" {name:<4} top scalars: {formatted}")
print("\n2. LAYER 0 -> LAYER 1 ROW ANGLES (90 degrees + signed delta)")
for label, suffix in [
("mlp.gate_proj", "mlp.gate_proj.weight"),
("mlp.up_proj", "mlp.up_proj.weight"),
("linear_attn.in_proj_z", "linear_attn.in_proj_z.weight"),
]:
u0 = read_matrix_units(f, payload, h[f"{p}layers.0.{suffix}"])
u1 = read_matrix_units(f, payload, h[f"{p}layers.1.{suffix}"])
angles, tan_cos = [], []
for a, b in zip(u0, u1):
if a is None or b is None:
continue
c_val = max(-1.0, min(1.0, dot(a, b)))
angles.append(math.degrees(math.acos(c_val)))
t_raw = tuple(bv - c_val * av for av, bv in zip(a, b))
t_len = math.hypot(*t_raw)
if t_len > 0:
tan_cos.append(dot(b, tuple(x / t_len for x in t_raw)))
mean_a = sum(angles) / len(angles)
std_a = math.sqrt(sum((x - mean_a) ** 2 for x in angles) / len(angles))
mean_tc = sum(tan_cos) / len(tan_cos)
print(
f" {label:<22} rows={len(angles):>4} "
f"mean={mean_a:6.3f} deg std={std_a:5.3f} deg "
f"delta_from_90={mean_a - 90.0:+.3f} deg "
f"cos(tangent, dest)={mean_tc:.6f}"
)
print("\n3. TOKEN-MATCHED GATE STEP ANGLES ACROSS 3+1 BLOCKS")
probe_ids = [32671, 11751, 2919, 11148, 59218, 24822, 22984, 35202]
probe_dirs = [unit(read_row_f32(f, payload, emb, tid)[2]) for tid in probe_ids]
layer_best = []
for layer in range(24):
mat = read_matrix_units(f, payload, h[f"{p}layers.{layer}.mlp.gate_proj.weight"])
layer_best.append([
max((u for u in mat if u is not None), key=lambda u: dot(td, u))
for td in probe_dirs
])
for block in range(6):
base = block * 4
steps = []
for s in range(3):
angs = [
math.degrees(math.acos(max(-1.0, min(1.0, dot(
layer_best[base + s][t], layer_best[base + s + 1][t]
)))))
for t in range(len(probe_dirs))
]
steps.append(sum(angs) / len(angs))
tag = f"L{base:02d}->L{base+1:02d}->L{base+2:02d}->L{base+3:02d}(full)"
print(
f" block {block} ({tag}): "
f"steps = {steps[0]:6.2f} deg, {steps[1]:6.2f} deg, {steps[2]:6.2f} deg "
f"(mean {sum(steps)/3:6.2f} deg)"
)
if __name__ == "__main__":
verify(sys.argv[1])
Running python3 inspect_across_layers.py model.safetensors on Qwen 3.5 0.8B
prints:
1. CROSS-TENSOR INDIVIDUAL WEIGHTS (layers.0.mlp.gate_proj.weight)
Rust top scalars: (5,30)@537068196, (87,977)@537238026, (1004,54)@539114196, (149,157)@537363362, (1523,1002)@540179004, (550,1002)@538186300
king top scalars: (5,166)@537068468, (5,5)@537068146, (42,5)@537143922, (59,166)@537179060, (2,5)@537062002, (5,30)@537068196
2. LAYER 0 -> LAYER 1 ROW ANGLES (90 degrees + signed delta)
mlp.gate_proj rows=3584 mean=89.339 deg std=1.987 deg delta_from_90=-0.661 deg cos(tangent, dest)=0.999333
mlp.up_proj rows=3584 mean=90.067 deg std=1.916 deg delta_from_90=+0.067 deg cos(tangent, dest)=0.999441
linear_attn.in_proj_z rows=2048 mean=90.075 deg std=1.808 deg delta_from_90=+0.075 deg cos(tangent, dest)=0.999502
3. TOKEN-MATCHED GATE STEP ANGLES ACROSS 3+1 BLOCKS
block 0 (L00->L01->L02->L03(full)): steps = 87.38 deg, 88.01 deg, 86.83 deg (mean 87.41 deg)
block 1 (L04->L05->L06->L07(full)): steps = 86.62 deg, 87.72 deg, 89.52 deg (mean 87.95 deg)
block 2 (L08->L09->L10->L11(full)): steps = 89.16 deg, 87.99 deg, 88.19 deg (mean 88.45 deg)
block 3 (L12->L13->L14->L15(full)): steps = 90.04 deg, 87.36 deg, 89.07 deg (mean 88.83 deg)
block 4 (L16->L17->L18->L19(full)): steps = 82.54 deg, 82.88 deg, 86.06 deg (mean 83.83 deg)
block 5 (L20->L21->L22->L23(full)): steps = 82.97 deg, 82.65 deg, 72.37 deg (mean 79.33 deg)
All three mechanical patterns show up directly in the numbers:
- Shared byte addresses:
'ĠRust'ranks(5, 30)at file byte537068196first out of3,670,016scalars, and'Ġking'hits that exact same(5, 30)@537068196scalar sixth. - Quarter-turn stepping: Every tested projection family steps from layer
0to layer1by90 degreesplus a small signed delta (-0.661°,+0.067°,+0.075°, withstdunder2°), and the orthogonal tangent axis captures over0.9993cosine with the destination row. - The shift around layer 18: Blocks
0through3(L00..L15) hold steady between87.4°and88.8°, thenblock 4 (L16 -> L17 -> L18 -> L19) drops sharply to82.54°and82.88°(mean83.83°), followed by the final72.37°turn into full-attention layer23.
Once you have those data structures in place, two static experiments are easy to build on top without changing any files on disk:
- Trace step-by-step token chains (
rust -> memory): Pick two present token rows, step across evenly spaced interpolated directions between their unit vectors (normalizing each step), and scan which present vocabulary row aligns closest to each intermediate direction. Store those hops as a measured overlay rather than structural model wiring: they show how the vocabulary is populated between two directions in input space, not how layers execute. - Test a candidate token vector in RAM first: Pick two anchor tokens and
specify target cosines, say
0.8to'Ġrust'and0.6to'Ġmemory'. Construct a temporary unit vector in memory that meets both targets, scan the frozen table to see which existing tokens end up as its neighbors, and compare a second vector that satisfies the same two cosines using the remaining dimensions. If you ask for mutually impossible cosines against two nearly identical anchors, the math fails immediately before you ever allocate a new tokenizer ID or touch a checkpoint file.
My viewer already implements the multi-step token route overlay on top of the same root table; temporary target-vector solving is a natural next tool on the same substrate. If you eventually write a new token back into a copy of a checkpoint, you update the tokenizer table and both input/output arrays to match, and only then hand it to a runtime to test how the model actually uses it.
- Toy Models of Superposition (Elhage et al., 2022) shows why
learned representations often pack many overlapping directions into fewer
coordinates. From a data-structure standpoint, that is why an array index
ishould be treated as a shared addressing slot rather than a single semantic field. - A Mathematical Framework for Transformer Circuits (Elhage et al.,
- is an example of pushing static weight analysis further by multiplying
adjacent weight matrices into composed
QKandOVoperators. That is a derived matrix view built on top of the raw per-tensor addressing described here, while still sitting on the static side of the boundary before runtime execution.