{"slug": "how-to-read-frozen-weights-without-a-forward-pass", "title": "How to read frozen weights without a forward pass", "summary": "A systems engineer published a guide showing how to inspect a frozen model's stored weights — tensor bytes, tokenizer strings and architecture wiring — directly from a SafeTensors file without loading a runtime or running a forward pass. The guide separates three layers: source data and architecture wiring traceable to exact byte spans, full-space measurements such as the cosine between two 1,024-element embedding rows, and display structures like 2D or 3D coordinates that do not exist inside the checkpoint. It notes that in tied-embedding models such as Qwen 3.5 the input and output vocabulary tables are the exact same bytes.", "body_md": "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.\n\nAfter 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.\n\nSo, here's the thing.\n\nYou 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.\n\nThis 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.\n\nBefore 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.\n\nBefore 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:\n\n1. **Source data and architecture wiring:** The raw tensor bytes in the file,\nthe token strings in the tokenizer table, and the architecture rules that\nsay which tensor dimensions connect to which. When an edge represents a\nstored weight, you can point to its tensor, row, column, and an exact byte span.\n2. **Derived full-space measurements:** Numbers computed directly from those\nstored arrays at their full width, such as the cosine between two\n1,024-element embedding rows.\n3. **Display structures:** The 2D or 3D coordinates, bounding hierarchies, and\nscreen layouts built so a human can move around the data without altering it.\nNone of these pictures exists inside the checkpoint file.\n\nThat separation gives you three rules when reading the map:\n\n- **A measured similarity edge** means two stored rows have a reported cosine\nin their full-width array space.\n- **Two nearby dots on screen** only mean two rows landed near each other after\nprojecting down to 2D or 3D. Check their full-width score before trusting\nscreen proximity.\n- **A structural wiring edge** means the architecture connects one array axis,\nweight, or stage to the next. By itself, it says nothing about how much\nsignal moved across that connection during a runtime execution.\n\nMy 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.\n\nMechanically, it made sense that a vector's **angle** (direction) would be what\nassociates with a token, since layer-by-layer execution works by offsetting and\nrotating that direction, while the **magnitude** (length) affects how strongly\neach contribution pulls.\n\nTo 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:\n\n- **Direction alone** identified which token was present**99.6%** of the time\nacross all layers (against a**14.3%** random baseline).\n- **Magnitude alone** identified the token only**31.3%** of the time.\n\nAnd across 480 layer observations with different surrounding context, the context\nnever once flipped a token's direction (`0 / 480` reversals; simple `prompt + token` addition also failed with `0.9038` relative error). What happened instead\nwas, when multiple paths met at a shared intersection, their relative incoming\nmagnitudes damped the radius and rotated the combined resultant into a\ncontext-conditioned cone, before realigning toward the output table at the final\nblock. Direct weight interventions showed the same split statically: scaling 16\ncomplete `gate_proj` rows across layers `0, 7, 15, 23` by `0.25x` and `4.0x`\nchanged `0 / 16` nearest-token owners, whereas rotating them halfway toward\n`'ĠRust'` at constant norm changed all `16 / 16`.\n\nTwo 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:\n\n1. **Weights step from layer to layer by `90 degrees + a small delta`:** When I\nmeasured corresponding projection rows (`gate` ,`up` ,`QKV` ,`Z` ) from one\nlayer to the next, the angle consistently shifted by`90 degrees` plus or\nminus a small signed delta (roughly`89° to 90°` , within a tight ~`2°` band).\nThink of it mechanically like a physical ring indexing one quarter-turn per\nlayer, plus a small signed offset that carries the specific adjustment onto\nthe next axis. Whether the math says`90°` is expected in high dimensions is\nnot the point. Mechanically, it means moving from layer to layer isn't an\nuntraceable black-box scramble: it follows a deterministic, observable\nstepping rule (`quarter-turn + signed delta` , paired with radius) that can be\nunderstood causally and exploited directly, for instance by stepping a single\nresident layer buffer in place from layer to layer instead of holding 18\nseparate linear layers as unrelated blobs.\n2. **Rotational activity concentrates late, especially around layer 18:** Qwen\n3.5 0.8B is built from a repeating**3 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` , and`20..22 -> 23` ). Watching both\ntoken-matched gate angles and accumulated block deltas across those six\ncycles, the directional shifts and norm buildup weren't spread evenly across\nall layers: most of the heavy rotational shift concentrated around**layer\n18** (the fifth`3 + 1` cycle,`16..18 -> 19` ), right before the final`20..23` block makes the large closing turn toward the output table.\n\nPut those pieces together and you can see why a flat tensor dump wasn't enough, and why a frozen spatial explorer makes sense structurally:\n\n- **Angle carries identity and membership** , and those frozen directions and\nshared intersections are already sitting in the checkpoint file at rest.\n- **Layer transitions follow a deterministic mechanical step** (`90° + delta` onto the next axis, while individual coordinates share superposed paths), so\nstructure across depth is something you can trace and index as a space rather\nthan treating layers as disconnected black boxes.\n- **Live magnitude belongs to the runtime:** when a prompt executes, incoming\nmagnitudes at shared intersections weight, damp, and rotate the resultant\nacross that static structure.\n\nTypically, 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 loading a multi-gigabyte checkpoint into RAM.\n\nA SafeTensors file is a flat binary container. It starts with an 8-byte\nunsigned little-endian integer `N` giving the byte length of a UTF-8 JSON\nheader, followed immediately by `N` bytes of JSON. The raw tensor payload\nstarts at byte `8 + N`. Each entry in the JSON header gives a `dtype`, a\n`shape` array, and a half-open byte range `data_offsets: [start, end]`\n**relative to the start of the payload**, not to byte zero of the file.\n\nFor a dense, row-major 2D matrix with `C` columns and `B` bytes per element:\n\n```\ntensor_start = 8 + N + start\nrow_start    = tensor_start + row * C * B\nscalar_start = row_start + column * B\n```\n\nValidate the rank, shape, dtype, file bounds, and exact byte span\n(`end - start == rows * C * B`) before seeking. Then read `B` bytes for a\nsingle weight or `C * B` bytes for a row. `F32` is a 4-byte little-endian IEEE\nfloat. `BF16` is 2 bytes: read them as a 16-bit little-endian unsigned integer,\nshift the bits left by 16, and reinterpret those 32 bits as `F32`. That decodes\nthe exact stored `BF16` value; it does not invent precision that wasn't saved\nin the file.\n\nTo look up a token's row, find the **input embedding table** declared by the\narchitecture. A tensor name like `model.embed_tokens.weight` or\n`model.language_model.embed_tokens.weight` is a hint, not a guarantee: always\nconfirm its role and `[vocab_slots, hidden_width]` shape against the model\nlayout. In that layout, integer token ID `t` indexes row `t`.\n\nJoin those row indices against the matching `tokenizer.json` (`model.vocab` and\n`added_tokens`). Don't assume every row in the embedding array has a token\nstring: checkpoints often pad `vocab_slots` up to an alignment boundary,\nleaving unused rows at the end of the table. Keep exact integer IDs,\nwhitespace, and special-token metadata intact. A raw vocabulary key is also not\nalways final display text: byte-level BPE stores markers such as `Ġ` for a\nleading space (`'ĠRust'` vs `'rust'`) or raw byte tokens. Keep the raw key\naccessible so distinct rows don't get collapsed under the same label.\n\nOnce you can read two rows of equal width from the same table, you can measure how closely they point in the same direction.\n\nTreat embedding row `e[t]` as a fixed-length array of `D` numbers. Divide each\nnonzero row by its Euclidean length to get its unit direction `u[t]`:\n\n```\ncosine(a, b) = dot(e[a], e[b]) / (norm(e[a]) * norm(e[b]))\n             = dot(u[a], u[b])\n```\n\n`+1` is the same direction, `0` is perpendicular, and `-1` is opposite.\nNormalizing splits direction away from length on purpose: `[1, 0]` and `[10, 0]`\nboth have unit direction `[1, 0]` and score `1`. Because direction is what\ncarries almost all token identity while magnitude acts as radial weight when\nvectors combine, a good data model stores unit direction and magnitude as two\nseparate fields rather than mixing them or throwing length away silently. Keep\nthe static claim clean too: cosine measures directional alignment between two\nstored rows, not synonymy and not how much live magnitude will arrive in a\ngiven prompt.\n\nTo inspect one token's neighborhood, normalize its row, stream sequentially\nacross the embedding table on disk or in a buffer, and maintain a fixed-size\nmin-heap of the top `k` scores. Skip the query ID itself, skip zero or\nnon-finite rows, and skip unmapped padding rows if you only want valid tokens.\nBreak ties deterministically by integer token ID so two implementations always\nreturn the exact same neighbor list.\n\nConnecting a query token to its top `k` neighbors gives you a simple hub. If\nyou also compute cosines **between** those `k` neighbors, you can see whether\nthe local web breaks into distinct pockets (say, lowercase/uppercase variants\non one side and related domain terms on another). If you want stricter grouping\nacross a larger set, keep edges only where two tokens appear in each other's\ntop `k` (mutual nearest neighbors), and test a few values of `k` so an\narbitrary cutoff doesn't fool you.\n\nData-structure-wise, a single query scan costs `O(V * D)` multiply-adds over `V`\nrows of width `D` plus `O(log k)` heap updates when a row enters the top `k`.\nYou never need to allocate a `V * V` matrix. If you later put an approximate\nindex in front of the table, mark those results as approximate and recompute\nexact cosines from the source rows for anything you display.\n\nTables of cosines are exact, but hard to browse. To put tens or hundreds of\nthousands of token roots on screen, you need a deterministic way to map `D`\nnumbers down to three coordinates `(x, y, z)`.\n\nA simple one-pass method of doing that is to pick three independent rows from\nthe table as anchors and orthogonalize them with Gram-Schmidt: from each anchor,\nsubtract its dot-product projections onto the previous axes, then normalize the\nremainder. That yields three perpendicular unit axes `(axis_x, axis_y, axis_z)`\nof width `D`. Every unit row `u` then projects to three numbers:\n\n```\np(u) = (dot(u, axis_x), dot(u, axis_y), dot(u, axis_z))\n```\n\nIn 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.\n\nThe main rule is to treat those 3D coordinates as **lossy display state**,\nnever as source truth. Take a 4D example and keep only the first three slots:\nthe unit vectors `(0.6, 0, 0, 0.8)` and `(0.6, 0, 0, -0.8)` both project to\n`(0.6, 0, 0)`, even though their actual 4D dot product is `0.36 - 0.64 = -0.28`.\nScreen layout is for navigation and culling; edges and scores must always come\nfrom the full-width vectors.\n\nFor a local view centered on a chosen token `q`, put `q` at the origin and\nsubtract `q`'s component from each normalized neighbor `u`:\n`t = u - dot(u, q) * q`. Orthogonalizing three independent residual vectors `t`\ngives a local 3D basis showing the directions in which neighbors spread away\nfrom `q`. You can set distance from the origin directly from angle\n(`acos(clamp(cosine, -1, 1))`), or space dense clusters out for label\nreadability, as long as your UI keeps layout spacing separate from the measured\ncosine.\n\nHere is a minimal standalone reader using only the Python 3.10+ standard\nlibrary (drafted with AI assistance and checked against my Rust index). It\nparses the 8-byte SafeTensors header, validates the target tensor's byte span,\noptionally joins `tokenizer.json` keys so unmapped reserve rows are skipped,\nstreams the rows once to build the 3-axis basis and top-`k` heap, and prints\nboth full-width cosines and 3D coordinates.\n\nOn a ~250k-row vocabulary in pure Python without NumPy, a full sequential scan takes roughly 10 to 20 seconds.\n\n``` python\nimport heapq\nimport json\nimport math\nfrom operator import mul\nimport os\nimport struct\nimport sys\n\ndot = getattr(math, \"sumprod\", lambda a, b: sum(map(mul, a, b)))\n\ndef read_exact(file, size):\n    data = file.read(size)\n    if len(data) != size:\n        raise ValueError(\"truncated file\")\n    return data\n\ndef unit(v):\n    length = math.hypot(*v)\n    if length == 0 or not math.isfinite(length):\n        return None\n    inv = 1.0 / length\n    return tuple(x * inv for x in v)\n\ndef load_labels(tokenizer_path):\n    with open(tokenizer_path, \"r\", encoding=\"utf-8\") as file:\n        tok = json.load(file)\n    labels = {idx: key for key, idx in tok.get(\"model\", {}).get(\"vocab\", {}).items()}\n    for entry in tok.get(\"added_tokens\", []):\n        labels[entry[\"id\"]] = entry[\"content\"]\n    return labels\n\ndef inspect(file, tensor_name, query_id, labels=None, k=8):\n    size = os.fstat(file.fileno()).st_size\n    header_size = struct.unpack(\"<Q\", read_exact(file, 8))[0]\n    if not 0 < header_size <= min(size - 8, 100_000_000):\n        raise ValueError(\"invalid header size\")\n    desc = json.loads(read_exact(file, header_size))[tensor_name]\n    dtype = desc[\"dtype\"]\n    if dtype not in (\"BF16\", \"F32\") or len(desc[\"shape\"]) != 2:\n        raise ValueError(\"expected rank-2 BF16 or F32 tensor\")\n    rows, width = desc[\"shape\"]\n    start, end = desc[\"data_offsets\"]\n    payload = 8 + header_size\n    row_bytes = width * (2 if dtype == \"BF16\" else 4)\n    if not (rows > 0 and width >= 3 and k > 0\n            and 0 <= query_id < rows and 0 <= start <= end <= size - payload\n            and end - start == rows * row_bytes):\n        raise ValueError(\"invalid matrix span, dimensions, or query\")\n\n    def read_row():\n        raw = read_exact(file, row_bytes)\n        if dtype == \"F32\":\n            return struct.unpack(f\"<{width}f\", raw)\n        # BF16 stores the upper two bytes of each little-endian F32 bit pattern.\n        expanded = bytearray(4 * width)\n        expanded[2::4] = raw[0::2]\n        expanded[3::4] = raw[1::2]\n        return struct.unpack(f\"<{width}f\", expanded)\n\n    file.seek(payload + start + query_id * row_bytes)\n    query = unit(read_row())\n    if query is None:\n        raise ValueError(\"query row has no valid direction\")\n\n    axes, anchors, neighbors = [], [], []\n    file.seek(payload + start)\n    for token_id in range(rows):\n        if labels is not None and token_id not in labels:\n            file.seek(row_bytes, os.SEEK_CUR)\n            continue\n        direction = unit(read_row())\n        if direction is None:\n            continue\n        if len(axes) < 3:\n            residual = direction\n            for axis in axes:\n                component = dot(residual, axis)\n                residual = tuple(\n                    x - component * y for x, y in zip(residual, axis)\n                )\n            if dot(residual, residual) > 1e-12:\n                axes.append(unit(residual))\n                anchors.append(token_id)\n        if token_id != query_id:\n            score = max(-1.0, min(1.0, dot(query, direction)))\n            item = (score, -token_id, direction)\n            if len(neighbors) < k:\n                heapq.heappush(neighbors, item)\n            elif item > neighbors[0]:\n                heapq.heapreplace(neighbors, item)\n\n    if len(axes) != 3:\n        raise ValueError(\"need three independent embedding directions\")\n    if labels is not None:\n        print(\"query:\", query_id, repr(labels.get(query_id, \"<unlabeled>\")))\n    print(\"axes from token IDs:\", anchors)\n    print(\"token_id\\tcosine\\tx\\ty\\tz\\tlabel\")\n    for score, negative_id, direction in sorted(neighbors, reverse=True):\n        tid = -negative_id\n        point = \"\\t\".join(f\"{dot(direction, axis):.6f}\" for axis in axes)\n        label = repr(labels.get(tid, \"\")) if labels is not None else \"\"\n        print(f\"{tid}\\t{score:.6f}\\t{point}\\t{label}\")\n\nif __name__ == \"__main__\":\n    path, tensor_name, query, *rest = sys.argv[1:]\n    labels = load_labels(rest[0]) if rest else None\n    with open(path, \"rb\") as file:\n        inspect(file, tensor_name, int(query), labels)\n```\n\nRunning that script against Qwen 3.5 0.8B (`model.safetensors` and\n`tokenizer.json`) on token ID `32671` (`'ĠRust'`):\n\n```\npython3 inspect_frozen.py model.safetensors model.language_model.embed_tokens.weight 32671 tokenizer.json\n```\n\nprints:\n\n```\nquery: 32671 'ĠRust'\naxes from token IDs: [0, 1, 2]\ntoken_id\tcosine\tx\ty\tz\tlabel\n22353\t0.620285\t-0.096485\t-0.076601\t-0.024758\t'Ġrust'\n34602\t0.546217\t-0.120175\t-0.070902\t-0.000364\t'rust'\n55355\t0.344299\t-0.115195\t-0.164201\t-0.028394\t'Ġrustic'\n94092\t0.340527\t-0.169135\t-0.170923\t-0.049361\t'Ġrusty'\n59218\t0.330591\t-0.182653\t-0.127535\t-0.008338\t'ĠCargo'\n24822\t0.320358\t-0.061104\t-0.060072\t-0.014342\t'.rs'\n22984\t0.318060\t-0.092266\t-0.091563\t0.004938\t'ĠRuby'\n35202\t0.313016\t-0.145921\t-0.141656\t-0.024726\t'ĠRails'\n```\n\nEven from this single table scan, two data-level facts are easy to verify:\n\n1. Purely from stored `BF16` rows and integer IDs,`'ĠRust'` already sits next\nto casing variants (`'Ġrust'` ,`'rust'` ), surface English relatives\n(`'Ġrustic'` ,`'Ġrusty'` ), Rust build/file tokens (`'ĠCargo'` ,`'.rs'` ), and\nrelated language/framework names (`'ĠRuby'` ,`'ĠRails'` ). Keeping the raw BPE\nkey also shows why`'Ġrust'` (`22353` , with a leading space) and`'rust'` (`34602` , no leading space) are separate entries in the array.\n2. Compare `'ĠCargo'` (`59218` ) and`'.rs'` (`24822` ): their 1,024-wide cosines\nto`'ĠRust'` are nearly identical (`0.331` vs`0.320` ), while their projected`x` coordinates differ by 3x (`-0.183` vs`-0.061` ). That is the projection\nrule in practice: 3D coordinates organize the viewport, while the full-width\ndot product carries the measurement.\n\nReading 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?\n\nLook at the sizes in Qwen 3.5 0.8B. The embedding table has `248,320` rows of\nwidth `H = 1,024`. A single MLP matrix like layer `0`'s `gate_proj.weight` has\nshape `[3584, 1024]`, which is `3,670,016` scalars. If you tried to build an\nexplicit pointer graph from every token to every scalar in just that one\nmatrix, you would allocate nearly a trillion edges before touching the rest of\nthe 24 blocks.\n\nYou avoid that explosion by **factorizing the graph through shared array\ndimensions** instead of copying or materializing token-by-weight edges:\n\n``` php\nTokenRoot(t)\n  -> Component(i)               (shared axis index i in 0 .. H-1)\n  -> Weight(tensor, j, i)       (column i fixed, row j in 0 .. out-1)\n  -> Intersection(tensor, j)    (row j fixed, where all H columns meet)\n```\n\nBecause `embed_tokens[vocab, H]` and a downstream matrix `W[out, H]` both have\nwidth `H` on their shared bus, index `i` is the exact join key between them:\n\n- **From `Component(i)` into consumer matrices:** hold column`i` fixed and\nvary row`j` across`0 .. out-1` . Direct offset arithmetic gives you every\nindividual weight`W[j, i]` that reads from axis`i` , along with its exact\n2-byte or 4-byte file span.\n- **From `Weight(tensor, j, i)` to its row intersection:** hold row`j` fixed\nand vary column`i` across`0 .. H-1` . That enumerates every weight converging\non output slot`j` of that matrix.\n\nNo weights are copied per token, and no billion-edge adjacency list exists in\nRAM. Each weight remains one immutable byte span on disk, reachable from any\ntoken root through shared column `i`.\n\nYou can also inspect how strongly a specific token's unit direction lines up\nwith individual weights along their shared column. Token `t` has unit entry\n`u[t][i]` at column `i`. If the architecture places a per-column normalization\nscale vector directly before `W`, column `i` also has a stored scale value\n(`gamma[i]`, or `1 + gamma[i]` when the checkpoint stores zero-centered norm\nweights, as Qwen 3.5 does). Pairing `u[t][i]` with that scaled weight gives an\nexact static per-column relationship for `(t, j, i)` without copying the matrix.\n\nWhen I ran that exact check across all `3,670,016` scalars of layer `0`'s\n`gate_proj.weight` in Qwen 3.5 0.8B, both `'ĠRust'` (`32671`) and `'Ġking'`\n(`11148`) had `gate_proj.weight[5, 30]` (at absolute file byte `537068196`) in\ntheir top eight individual weight relationships, while `'Ġwater'` (`2919`) and\n`'Ġking'` shared `gate_proj.weight[5, 166]` (at byte `537068468`). Two distinct\ntoken roots point to the exact same 2-byte address in the file; the weight\nlives once, and ownership is just a typed relationship to its coordinate.\n\nFour structural rules to keep this trustworthy:\n\n1. **A shared index is a wiring slot, and ownership is shared rather than\nexclusive.** Column`30` is where two arrays align by dimension, not a\ndedicated \"Rust/king feature.\" One token reaches many weights, and one\nweight or row intersection can participate in several token directions at\nonce without collision.\n2. **Don't prune away diffuse mass; group it losslessly.** Even when the\nstrongest individual weights stand out clearly,`95%` of a token's static\ncontribution mass in layer`0` spans roughly`75%` of the matrix (`2,682` to`2,704` of`3,584`` gate_proj` rows), and assigning one permanent token label\nper unrotated row leaves common tokens with zero rows. Instead of dropping\n\"weak\" weights, collapse wide runs (such as`1,024` shared axes) into\nlossless power-of-two ranges when zoomed out and split them down to exact\nleaves as you zoom in.\n3. **Frozen direction stays fixed; live magnitude rotates the resultant at\nintersections.** At`Intersection(tensor, j)` , all`H` columns meet. In the\ncheckpoint, the participating weight directions and signs are fixed. During\nruntime execution, the relative magnitudes arriving along those inputs\ndetermine how much the combined vector damps and rotates at that\nintersection. In a static explorer, label`abs(W[j, i])` as a stored\ncoefficient and keep its sign separate.\n4. **Only join dimensions that the architecture actually wires together.** Two\narrays having length`1,024` does not automatically mean they share the same\nslot layout. Check the model's architecture definition for transposed\nmatrices, packed multi-head or gate/up layouts, multi-file shard indexes\n(`model.safetensors.index.json` ), and quantized block encodings.\n\nOnce single matrices are indexed by `(tensor, row, column)`, walking across\nblocks is an architecture-schema problem. **The SafeTensors header tells you\neach array's shape and byte offset; the architecture plan tells you which output\ndimension becomes the next stage's input dimension.**\n\nBefore writing traversal code, encode a strict table of the expected block\nfamilies and their shapes. For instance, in Qwen 3.5 0.8B's 24-layer text\nbackbone, 18 blocks use linear-attention tensor families and 6 blocks\n(`3, 7, 11, 15, 19, 23`) use full-attention tensor families, while every block\ncarries norms, `gate_proj`, `up_proj`, `down_proj`, and residual returns, and\nvision tensors sit in a separate submodel namespace. Validating names and\nshapes up front ensures your walker never joins incompatible tensors by\naccident because two names happened to end in `down_proj`.\n\nTake a text block with shared hidden width `H = 1,024` and MLP width\n`M = 3,584`. Here `gate_proj.weight` and `up_proj.weight` are `[M, H]`, and\n`down_proj.weight` is `[H, M]`. Think of the residual stream simply as the\nshared `H`-slot bus carried from block boundary to block boundary.\n\nUsing zero-based indices (`7`, `23`, and `11` are arbitrary example slots to\nshow how indices hand off across `model.language_model.layers.0` and `layers.1`):\n\n1. **Token slot to MLP input column:** Start at`embed_tokens.weight[t, 7]` , or\nat shared slot`7` after block`0` 's attention return. Pass through the\nper-slot scale entry`layers.0.post_attention_layernorm.weight[7]` into\ncolumn`7` of`layers.0.mlp.gate_proj.weight[23, 7]` and`layers.0.mlp.up_proj.weight[23, 7]` . Column`7` is the input slot they both\nread from; row`23` is the intermediate slot they both write toward.\n2. **Represent the gated join as a structural node:** At intermediate slot`23` ,\nthe architecture combines the`gate` and`up` branches elementwise after\nsumming across all`1,024` columns and applying a gate nonlinearity. In a\nfrozen data structure, represent that meeting point as a typed`Product` node`(layer = 0, feature = 23)` , not as`gate_proj[23, 7] * up_proj[23, 7]` .\nMultiplying two isolated weights across a nonlinear join would invent a\nnumber that neither the file nor the runtime actually uses.\n3. **Flip row to column on the way back out:** Leaving intermediate slot`23` ,\nthat index changes role from a**row** of`[M, H]` to a**column** of`[H, M]` in`layers.0.mlp.down_proj.weight[11, 23]` . Row`11` of`down_proj` lands back on shared residual slot`11` at the end of block`0` , which is\nthe exact same slot`11` entering block`1` . In the graph, that residual\nreturn is a zero-byte structural link, not a weight read.\n4. **Branch into the next block and to the output table:** At block`1` 's entry\nboundary, slot`11` connects forward both into block`1` 's attention input\ntensors and straight along the residual bus to block`1` 's MLP (such as`layers.1.mlp.up_proj.weight[5, 11]` ). Both paths exist simultaneously in the\nstatic topology. After the final block and final norm (`norm.weight[i]` ),\nslot`i` reaches the output vocabulary table: either a separate`lm_head` matrix or, when embeddings are tied, the exact same`embed_tokens[vocab_id, i]` byte address where token`vocab_id` started.\n\nAttention and linear-attention stages fit the same data-model boundary. Their\nprojection matrices, convolution weights, and per-head or per-channel norm\narrays are ordinary static tensors with exact `(tensor, row, column)` addresses\nand byte spans. Where the architecture mixes information across sequence\npositions or recurrent state, there is no static token-to-token weight in the\nfile to read, because that routing only exists when a runtime processes a\nsequence. Representing that boundary explicitly as a typed `Context` node lets\nyou walk into the projection weights and back out through `out_proj` without\npretending the checkpoint contains prompt-specific attention maps.\n\nIf you implement this in your own viewer, resist the urge to materialize the\ngraph in memory. Keep the checkpoint read-only and make the graph **virtual**:\n\n- **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 }` , and`OutputRoot(u32)` takes only a few bytes and\nneeds no heap allocation.\n- **Compute neighbors by arithmetic, one page at a time:** A`neighbors(pos)` function consults your validated layer table and tensor shapes, yielding only\nthe slice of outgoing or incoming positions needed for the current view or\ninspector page.\n- **Seek and decode only what is inspected:** Every`Weight` position already\ncarries`(tensor, row, col)` . Combine that with the tensor descriptor's`source_data_offset` and`dtype` to read the 2 or 4 bytes on demand when\nselected or displayed.\n- **Keep screen layout separate from graph identity:** Laying blocks out left\nto right with lanes for residual, context, and MLP stages gives a clean\ndiagram of the wiring. Moving a lane on screen changes pixel or cell\ncoordinates only; every node identity and file offset stays untouched.\n\nThat 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.\n\nThe first script in Section 4 only touched `embed_tokens`. Here is a second\nstandalone Python 3.10+ stdlib script (`inspect_across_layers.py`) so you can\ntest the cross-tensor and cross-layer claims directly on the same checkpoint\nfile in under 20 seconds, again with zero external packages.\n\nIt checks three things straight from the raw `BF16` bytes:\n\n1. **Cross-tensor individual weight addressing:** folds layer`0` 's`post_attention_layernorm.weight` (`1 + gamma` ) into all`3,670,016` scalars\nof`layers.0.mlp.gate_proj.weight` and prints the exact`(row, col)@byte` addresses aligned with`'ĠRust'` (`32671` ) and`'Ġking'` (`11148` ).\n2. **The `90 degrees + signed delta` layer step:** measures the exact angle\nbetween corresponding rows of`layers.0` and`layers.1` across projection\nfamilies, and checks the local two-axis rule`dest = sin(theta) * tangent + cos(theta) * source` .\n3. **Depth behavior across Qwen's six `3 linear + 1 full` blocks:** follows\ntoken-matched`gate_proj` directions across all 24 layers to show where the\nstep angle tightens around layer`18` (`L16..L18 -> L19` ).\n\n``` python\nimport heapq\nimport json\nimport math\nfrom operator import mul\nimport struct\nimport sys\n\ndot = getattr(math, \"sumprod\", lambda a, b: sum(map(mul, a, b)))\n\ndef open_safetensors(file):\n    header_size = struct.unpack(\"<Q\", file.read(8))[0]\n    header = json.loads(file.read(header_size))\n    return 8 + header_size, header\n\ndef read_row_f32(file, payload, desc, row):\n    cols = desc[\"shape\"][-1] if len(desc[\"shape\"]) > 1 else desc[\"shape\"][0]\n    dtype = desc[\"dtype\"]\n    bpe = 2 if dtype == \"BF16\" else 4\n    offset = payload + desc[\"data_offsets\"][0] + row * cols * bpe\n    file.seek(offset)\n    raw = file.read(cols * bpe)\n    if dtype == \"F32\":\n        return offset, bpe, struct.unpack(f\"<{cols}f\", raw)\n    expanded = bytearray(4 * cols)\n    expanded[2::4] = raw[0::2]\n    expanded[3::4] = raw[1::2]\n    return offset, bpe, struct.unpack(f\"<{cols}f\", expanded)\n\ndef read_matrix_units(file, payload, desc):\n    rows, cols = desc[\"shape\"]\n    dtype = desc[\"dtype\"]\n    bpe = 2 if dtype == \"BF16\" else 4\n    file.seek(payload + desc[\"data_offsets\"][0])\n    out = []\n    for _ in range(rows):\n        raw = file.read(cols * bpe)\n        if dtype == \"F32\":\n            vals = struct.unpack(f\"<{cols}f\", raw)\n        else:\n            expanded = bytearray(4 * cols)\n            expanded[2::4] = raw[0::2]\n            expanded[3::4] = raw[1::2]\n            vals = struct.unpack(f\"<{cols}f\", expanded)\n        length = math.hypot(*vals)\n        if length > 0 and math.isfinite(length):\n            inv = 1.0 / length\n            out.append(tuple(x * inv for x in vals))\n        else:\n            out.append(None)\n    return out\n\ndef unit(v):\n    inv = 1.0 / math.hypot(*v)\n    return tuple(x * inv for x in v)\n\ndef verify(path):\n    p = \"model.language_model.\"\n    with open(path, \"rb\") as f:\n        payload, h = open_safetensors(f)\n        emb = h[p + \"embed_tokens.weight\"]\n        norm0 = h[p + \"layers.0.post_attention_layernorm.weight\"]\n        gate0 = h[p + \"layers.0.mlp.gate_proj.weight\"]\n\n        seeds = [(32671, \"Rust\"), (11148, \"king\")]\n        seed_dirs = [unit(read_row_f32(f, payload, emb, tid)[2]) for tid, _ in seeds]\n        gamma0 = [1.0 + g for g in read_row_f32(f, payload, norm0, 0)[2]]\n        rows, _ = gate0[\"shape\"]\n        top = [[] for _ in seeds]\n        for r in range(rows):\n            row_off, bpe, vals = read_row_f32(f, payload, gate0, r)\n            for c, w in enumerate(vals):\n                folded = w * gamma0[c]\n                byte_addr = row_off + c * bpe\n                for idx, u in enumerate(seed_dirs):\n                    contrib = u[c] * folded\n                    item = (abs(contrib), -r, -c, contrib, byte_addr)\n                    heap = top[idx]\n                    if len(heap) < 8:\n                        heapq.heappush(heap, item)\n                    elif item > heap[0]:\n                        heapq.heapreplace(heap, item)\n\n        print(\"1. CROSS-TENSOR INDIVIDUAL WEIGHTS (layers.0.mlp.gate_proj.weight)\")\n        for (_, name), heap in zip(seeds, top):\n            entries = sorted(heap, reverse=True)\n            formatted = \", \".join(\n                f\"({-r},{-c})@{addr}\" for _, r, c, _, addr in entries[:6]\n            )\n            print(f\"  {name:<4} top scalars: {formatted}\")\n\n        print(\"\\n2. LAYER 0 -> LAYER 1 ROW ANGLES (90 degrees + signed delta)\")\n        for label, suffix in [\n            (\"mlp.gate_proj\", \"mlp.gate_proj.weight\"),\n            (\"mlp.up_proj\", \"mlp.up_proj.weight\"),\n            (\"linear_attn.in_proj_z\", \"linear_attn.in_proj_z.weight\"),\n        ]:\n            u0 = read_matrix_units(f, payload, h[f\"{p}layers.0.{suffix}\"])\n            u1 = read_matrix_units(f, payload, h[f\"{p}layers.1.{suffix}\"])\n            angles, tan_cos = [], []\n            for a, b in zip(u0, u1):\n                if a is None or b is None:\n                    continue\n                c_val = max(-1.0, min(1.0, dot(a, b)))\n                angles.append(math.degrees(math.acos(c_val)))\n                t_raw = tuple(bv - c_val * av for av, bv in zip(a, b))\n                t_len = math.hypot(*t_raw)\n                if t_len > 0:\n                    tan_cos.append(dot(b, tuple(x / t_len for x in t_raw)))\n            mean_a = sum(angles) / len(angles)\n            std_a = math.sqrt(sum((x - mean_a) ** 2 for x in angles) / len(angles))\n            mean_tc = sum(tan_cos) / len(tan_cos)\n            print(\n                f\"  {label:<22} rows={len(angles):>4}  \"\n                f\"mean={mean_a:6.3f} deg  std={std_a:5.3f} deg  \"\n                f\"delta_from_90={mean_a - 90.0:+.3f} deg  \"\n                f\"cos(tangent, dest)={mean_tc:.6f}\"\n            )\n\n        print(\"\\n3. TOKEN-MATCHED GATE STEP ANGLES ACROSS 3+1 BLOCKS\")\n        probe_ids = [32671, 11751, 2919, 11148, 59218, 24822, 22984, 35202]\n        probe_dirs = [unit(read_row_f32(f, payload, emb, tid)[2]) for tid in probe_ids]\n        layer_best = []\n        for layer in range(24):\n            mat = read_matrix_units(f, payload, h[f\"{p}layers.{layer}.mlp.gate_proj.weight\"])\n            layer_best.append([\n                max((u for u in mat if u is not None), key=lambda u: dot(td, u))\n                for td in probe_dirs\n            ])\n\n        for block in range(6):\n            base = block * 4\n            steps = []\n            for s in range(3):\n                angs = [\n                    math.degrees(math.acos(max(-1.0, min(1.0, dot(\n                        layer_best[base + s][t], layer_best[base + s + 1][t]\n                    )))))\n                    for t in range(len(probe_dirs))\n                ]\n                steps.append(sum(angs) / len(angs))\n            tag = f\"L{base:02d}->L{base+1:02d}->L{base+2:02d}->L{base+3:02d}(full)\"\n            print(\n                f\"  block {block} ({tag}):  \"\n                f\"steps = {steps[0]:6.2f} deg, {steps[1]:6.2f} deg, {steps[2]:6.2f} deg  \"\n                f\"(mean {sum(steps)/3:6.2f} deg)\"\n            )\n\nif __name__ == \"__main__\":\n    verify(sys.argv[1])\n```\n\nRunning `python3 inspect_across_layers.py model.safetensors` on Qwen 3.5 0.8B\nprints:\n\n```\n1. CROSS-TENSOR INDIVIDUAL WEIGHTS (layers.0.mlp.gate_proj.weight)\n  Rust top scalars: (5,30)@537068196, (87,977)@537238026, (1004,54)@539114196, (149,157)@537363362, (1523,1002)@540179004, (550,1002)@538186300\n  king top scalars: (5,166)@537068468, (5,5)@537068146, (42,5)@537143922, (59,166)@537179060, (2,5)@537062002, (5,30)@537068196\n\n2. LAYER 0 -> LAYER 1 ROW ANGLES (90 degrees + signed delta)\n  mlp.gate_proj          rows=3584  mean=89.339 deg  std=1.987 deg  delta_from_90=-0.661 deg  cos(tangent, dest)=0.999333\n  mlp.up_proj            rows=3584  mean=90.067 deg  std=1.916 deg  delta_from_90=+0.067 deg  cos(tangent, dest)=0.999441\n  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\n\n3. TOKEN-MATCHED GATE STEP ANGLES ACROSS 3+1 BLOCKS\n  block 0 (L00->L01->L02->L03(full)):  steps =  87.38 deg,  88.01 deg,  86.83 deg  (mean  87.41 deg)\n  block 1 (L04->L05->L06->L07(full)):  steps =  86.62 deg,  87.72 deg,  89.52 deg  (mean  87.95 deg)\n  block 2 (L08->L09->L10->L11(full)):  steps =  89.16 deg,  87.99 deg,  88.19 deg  (mean  88.45 deg)\n  block 3 (L12->L13->L14->L15(full)):  steps =  90.04 deg,  87.36 deg,  89.07 deg  (mean  88.83 deg)\n  block 4 (L16->L17->L18->L19(full)):  steps =  82.54 deg,  82.88 deg,  86.06 deg  (mean  83.83 deg)\n  block 5 (L20->L21->L22->L23(full)):  steps =  82.97 deg,  82.65 deg,  72.37 deg  (mean  79.33 deg)\n```\n\nAll three mechanical patterns show up directly in the numbers:\n\n- **Shared byte addresses:**`'ĠRust'` ranks`(5, 30)` at file byte`537068196` first out of`3,670,016` scalars, and`'Ġking'` hits that exact same`(5, 30)@537068196` scalar sixth.\n- **Quarter-turn stepping:** Every tested projection family steps from layer`0` to layer`1` by`90 degrees` plus a small signed delta (`-0.661°` ,`+0.067°` ,`+0.075°` , with`std` under`2°` ), and the orthogonal tangent axis captures\nover`0.9993` cosine with the destination row.\n- **The shift around layer 18:** Blocks`0` through`3` (`L00..L15` ) hold steady\nbetween`87.4°` and`88.8°` , then**block 4 (`L16 -> L17 -> L18 -> L19`)** drops sharply to` 82.54°` and`82.88°` (mean`83.83°` ), followed by the final`72.37°` turn into full-attention layer`23` .\n\nOnce you have those data structures in place, two static experiments are easy to build on top without changing any files on disk:\n\n1. **Trace step-by-step token chains (`rust -> memory`):** Pick two present\ntoken rows, step across evenly spaced interpolated directions between their\nunit vectors (normalizing each step), and scan which present vocabulary row\naligns closest to each intermediate direction. Store those hops as a\nmeasured overlay rather than structural model wiring: they show how the\nvocabulary is populated between two directions in input space, not how\nlayers execute.\n2. **Test a candidate token vector in RAM first:** Pick two anchor tokens and\nspecify target cosines, say`0.8` to`'Ġrust'` and`0.6` to`'Ġmemory'` .\nConstruct a temporary unit vector in memory that meets both targets, scan\nthe frozen table to see which existing tokens end up as its neighbors, and\ncompare a second vector that satisfies the same two cosines using the\nremaining dimensions. If you ask for mutually impossible cosines against two\nnearly identical anchors, the math fails immediately before you ever allocate\na new tokenizer ID or touch a checkpoint file.\n\nMy 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.\n\n- [Toy Models of Superposition](https://transformer-circuits.pub/2022/toy_model/index.html) (Elhage et al., 2022) shows why\nlearned representations often pack many overlapping directions into fewer\ncoordinates. From a data-structure standpoint, that is why an array index`i` should be treated as a shared addressing slot rather than a single semantic\nfield.\n- [A Mathematical Framework for Transformer Circuits](https://transformer-circuits.pub/2021/framework/index.html) (Elhage et al.,\n2021) is an example of pushing static weight analysis further by multiplying\nadjacent weight matrices into composed`QK` and`OV` operators. That is a\nderived matrix view built on top of the raw per-tensor addressing described\nhere, while still sitting on the static side of the boundary before runtime\nexecution.", "url": "https://wpnews.pro/news/how-to-read-frozen-weights-without-a-forward-pass", "canonical_source": "https://github.com/Mauitron/How-to-read-a-model-weights", "published_at": "2026-12-02 23:48:30+00:00", "updated_at": "2026-12-03 00:17:42.672546+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "large-language-models", "ai-tools"], "entities": ["SafeTensors", "Qwen 3.5"], "also_reported_by": [], "takeaway": "Read a frozen checkpoint's structure from the raw SafeTensors bytes, tokenizer table and architecture map, and treat projected 2D/3D positions as display-only — verify similarity with full-width cosines such as between two 1,024-element embedding rows before trusting screen proximity.", "recommendation": {"advice": "Inspect frozen weights directly from SafeTensors byte spans and tokenizer tables instead of loading a runtime, and confirm any visual clustering with full-width cosine scores before drawing conclusions.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/how-to-read-frozen-weights-without-a-forward-pass", "markdown": "https://wpnews.pro/news/how-to-read-frozen-weights-without-a-forward-pass.md", "text": "https://wpnews.pro/news/how-to-read-frozen-weights-without-a-forward-pass.txt", "jsonld": "https://wpnews.pro/news/how-to-read-frozen-weights-without-a-forward-pass.jsonld"}}