2026/06/26 28.5k words

Transformer System #numinens#transformer#embeddings#lookup-table#initial-state#weight-tying#word2vec#bert

M2.2 — Embeddings and Initial Model State

M2.2 — Embeddings and Initial Model State

0x00 From Token IDs to Learned Vectors

In M2.1, we saw how a tokenizer divides text into tokens and assigns each token an integer ID. The next step is to convert these IDs into the vectors used in the Transformer’s calculations. This is the purpose of the input embedding layer, and the second stage of the text-to-vector conversion introduced at the beginning of Module 2.

Consider again the sentence:

The cat sleeps.

The DeepSeek-V3 tokenizer gives us four tokens and their IDs:

pieces: ["The", " cat", " sleeps", "."]
IDs:    [671, 7539, 114896, 16]

The ID 7539 identifies the token " cat" in the vocabulary. Its numerical value comes from the vocabulary’s numbering; it tells us nothing about how the word is used. Nearby IDs need not represent related words. We therefore associate each ID with a vector: an ordered list of numbers whose values can be adjusted as the model learns from text.

The model stores these vectors in an embedding table, with one row for each possible input ID. All rows have the same number of values, called the embedding dimension. The tokenizer’s ID tells us which row to select, an operation called an embedding lookup. If we call the table E, the four lookups for our sentence are:

671     selects E[671]       for "The"
7539    selects E[7539]      for " cat"
114896  selects E[114896]    for " sleeps"
16      selects E[16]        for "."

For example, E[7539] is the entire row for " cat". In DeepSeek-V3, the model configuration specifies 7,168 values per vector. Placing the four selected vectors in sentence order gives a matrix with four rows and 7,168 columns. This describes the sentence alone; the special tokens in M2.1’s formatted chat input select additional rows in exactly the same way.

The values in this table are learned along with the other model parameters. For a language model trained to predict the next token, training measures the errors in its predictions and adjusts the parameters to reduce those errors. This includes adjusting the embedding vectors. When we use a pretrained model, we load the resulting table from its saved weights.

At lookup, every occurrence of " cat" with ID 7539 selects the same row. Later layers use information from other tokens to change that representation. The input embedding is therefore the starting representation of a token; its representation in the context of a sentence is computed in the layers that follow.

Much of this article is devoted to how the embedding table behaves during training and how it is stored in a saved model. This accounts for its length: we will derive the updates to its rows, follow them through code, and examine what happens when the vocabulary or the way the table is stored changes.

We will first describe the table’s dimensions and explain how selecting a row relates to one-hot encoding. We will then implement lookup with PyTorch’s nn.Embedding and study initialization, the convention of multiplying the selected rows by sqrt(d_model), and training, including repeated tokens, padding, and whether the table’s gradient is stored densely or sparsely and how optimizers handle each form. Later sections examine ways to reduce the table’s memory use, add position and segment rows to the token rows, add rows for new tokens, share its values with the layer that predicts the next token, and divide the work across several GPUs. We will also compare lookup with the transformations used for image and audio features, and finish with tests and examples of implementation errors.

On a first reading, follow the lookup examples and the explanation of how training changes the selected rows. The longer derivations and checks for saving, sharing, or distributing the table can be revisited when working on those parts of a model.

0x01 Embedding Tables and Input Shapes

Our example has four tokens, each represented by a vector of 7,168 values. To describe the same operation for other sentences and models, we need notation for the number of rows and columns.

Let V be the number of rows in the embedding table, so valid IDs range from 0 to V - 1. We will begin with a table whose rows have the size used by the Transformer, written d_model. The table E then contains V × d_model learned values:

Some models instead give the table a smaller row width, written d_embed, and map each selected row to d_model values with a learned matrix P of shape [d_embed, d_model], which this article calls the bridge. 0x05A explains this factorization and what it costs. The main examples take d_embed = d_model; the small trace in 0x02A and 0x02B uses a bridge with d_embed = 3 and d_model = 5.

Models commonly process several sequences together in a batch. Let B be the number of sequences and L their common length, after padding where necessary. Their token IDs form a two-dimensional array, or tensor, with shape [B,L]:

For every entry in this tensor, lookup selects the corresponding row of E. We write the resulting collection of vectors as X_text:

The batch still contains B sequences of L tokens. Each token now has d_model values, giving the output three dimensions:

For our sentence alone, B = 1 and L = 4: the input shape is [1,4], and the output shape is [1,4,7168]. The leading 1 records the batch size; inside it is the four-row matrix described in the introduction.

In an encoder-decoder model used for translation, this lookup is performed for both the source text and the target text. If their lengths are S and T, the corresponding output shapes are [B,S,d_model] and [B,T,d_model]. Each uses the embedding table associated with its vocabulary; whether those tables can be shared is discussed later.

Inputs that are already vectors

An image or audio encoder produces feature vectors before the input reaches the language model. These vectors may have a different number of values from the model’s text embeddings. To use them as input, we need to transform them to the required size.

Let H_media contain n feature vectors per example, each with d_media values. Its shape is:

One way to change the size is a learned linear layer, often called a projector. Its matrix W_p maps the d_media input values to d_model output values:

We multiply each feature vector by this matrix and add a learned bias b, which has d_model values:

This operation preserves the number of feature vectors while changing their size:

The same reasoning applies to document features and to event or action inputs: a discrete ID selects a row, while a continuous feature vector is transformed using its values. Casting those values to integers would not turn them into meaningful vocabulary IDs.

Some models use a multilayer network instead, which still produces one vector per feature vector, or a resampler or query adapter, which changes the number of vectors; the later sections on projectors explain these alternatives. Matching the vector size lets the language model accept the result. Learning to use the image or audio information also requires appropriate training.

The following diagram compares the two paths into the model:

Token IDs select rows of the embedding table, while image or audio features pass through a projector; both become vectors of d_model values and are joined into one input sequence, and the language model supplies positions afterwards

Both paths end with vectors of d_model values. A linear projector keeps one output vector per feature vector; resamplers and query adapters change the count. “Position / layout / time” refers to the positions the language model supplies afterwards; a vision encoder may already have used patch positions to compute its features.


0x01A From symbols to addresses to learned rows

A neural layer needs numeric input of a fixed width, and if that input is to be learned, it must be a parameter that gradients can reach. Text arrives as discrete symbols. The vocabulary takes the first step and gives each symbol an address:

token string -> integer ID in [0,V)

An integer ID by itself is a poor numeric feature. Suppose a toy vocabulary assigns dog -> 4812 and cat -> 2314 (these two IDs are used in the small examples of this article; in the DeepSeek-V3 vocabulary of 0x00, " cat" is 7539). Arithmetic on those integers invents an ordering that the vocabulary never intended. One-hot encoding removes that false magnitude:

Every category is now equally distant from every other category, but the vector is sparse and V-dimensional. A learned matrix converts it to a dense row:

Because only component i of o_i is one, the product reduces to:

This is why embedding lookup has the form it has: the multiplication by a one-hot selector is implemented as a row gather, and the V-1 zeros are never materialized.

Flow from text and integer indices through sparse one-hot addresses into dense embedding rows

The figure’s annotations are in Chinese, but the flow it shows is the one just derived: text is segmented, the pieces receive integer indices, the one-hot vectors are sparse and V-dimensional, and lookup produces dense rows of a much smaller width. Sparse and dense here describe the vectors. Whether the table’s gradient is stored as a sparse tensor is a separate question, which 0x04A takes up.

Why a learned row can carry useful structure

At initialization the rows are only distinguishable coordinates. Training gives them structure that depends on the task. If a loss L depends on the selected row E_i, gradient descent applies:

Rows used in contexts that call for similar predictions can receive updates in related directions, which is how words used alike can end up with nearby rows. Nothing forces a clean semantic geometry or a readable meaning for each dimension: the table is optimized together with the rest of the model, and the structure of its rows is whatever that objective produces.

The table therefore plays three roles at once. It is an address map: row i must still mean tokenizer ID i. It is a parameter tensor: its rows are learned by the optimizer and saved in the checkpoint. And its gathered rows are the state the later layers consume, so it sets the width and the scale of that state. Each role can break while the tensor keeps its shape. A table loaded next to another tokenizer with the same V still has V rows; a table whose rows were never trained still has width d_model; an initial state scaled by sqrt(d_model) twice, or not at all (0x03A), still has width d_model. All three produce an output of the right shape and the wrong content.

From word rows to sentence vectors

Bengio et al. (2003) learned word rows together with a neural language model’s probability function. Similar words could then receive nearby vectors, so a word sequence never seen in training could still receive a high probability when its words resembled those of sentences that had been seen. Each row was still selected by a discrete word identity. Word2Vec (Mikolov et al., 2013) made such vectors cheap to train on billions of words with two simple architectures: CBOW predicts a word from its neighbours, and Skip-gram predicts the neighbours from the word. It exported a static table: each word, including a word with several meanings, kept exactly one row.

ELMo (Peters et al., 2018) made a token’s representation depend on its sentence by combining the internal layers of a bidirectional language model for each use of a word. Its input was not a word-table row: it computed each token’s context-independent representation from the token’s characters. In the Transformer (Vaswani et al., 2017) and BERT (Devlin et al., 2018), lookup rows became the initial state that attention layers transform. Sentence-BERT (Reimers and Gurevych, 2019) encodes each sentence once into a vector that can be compared by cosine similarity, instead of passing every pair of sentences through BERT. Finding the most similar pair among 10,000 sentences fell from about 65 hours to about 5 seconds.

A modern retrieval model contains several of these objects at once: token IDs, a lookup table, contextual token rows, a pooling rule, and a final indexed vector. The next section separates them.

0x01B “Embedding” names several different objects

The word embedding is overloaded. In model code, papers and APIs it refers to at least four objects, which are built differently, and a comparison that is valid for one is not valid for another:

  • an input lookup row, E[input_ids], of shape [B,L,d_model] ([B,L,d_embed] before the bridge of 0x01). It does not depend on the context (it is the state before the later layers run), and what makes it meaningful is the language-model or task training of the lookup table;
  • a contextual token state, produced by the Transformer stack over the input rows, also [B,L,d_model]. It depends on the surrounding rows, the masks, the positions and the layer weights;
  • a pooled or retrieval vector, [B,d_retrieval], obtained by pooling one or more contextual rows, often followed by a head and a normalization. It depends on the context, and its meaning comes from the pooling rule and the contrastive or retrieval objective;
  • a projected modality state, [B,N,d_model], produced by a projector from an encoder’s features. Whether it depends on context is decided by the encoder, and its meaning comes from paired multimodal training and from the exact encoder and projector it was trained with.

Here d_retrieval is the width of the final retrieval vector: d_model when no head follows the pooling, otherwise the head’s output width.

Input lookup rows

The object this article follows is the lookup result:

Before attention layers run, the same token ID selects the same table row regardless of sentence context, apart from any position/type additions made by the architecture:

"bank" in "river bank"   -> E[bank]
"bank" in "central bank" -> E[bank]

The context has not yet changed the token row. A classic Word2Vec table is also a lookup table; it differs in its training objective (CBOW or Skip-gram, described in 0x01A) and in its units (whole words, where M2.1 produces subword pieces).

Contextual token states

After the stack begins mixing rows, a token state depends on the sequence:

H_l["bank" | "river bank"]
    need not equal
H_l["bank" | "central bank"]

These outputs are often called contextual embeddings. They have the same [B,L,d_model] shape as the input lookup result, so the shape alone cannot tell whether a tensor came from the embedding table or from layer 20. Which layer produced it, under which mask and with which positions, is part of what the tensor is.

Pooled and retrieval vectors

An API that returns one embedding per sentence, document or image usually adds steps after the encoder: a pooling, an optional projection and, when the objective expects it, a normalization:

hidden = encoder(input_ids)                  # [B,L,d_model]
pooled = pool(hidden, attention_mask)        # [B,d_model]
z = projection(pooled)                       # [B,d_retrieval], optional
z = F.normalize(z, dim=-1)                   # only when the objective expects it

The pooling operation may use a designated row, masked mean pooling, attention pooling, or another learned head. A contrastive objective can then train nearby vectors to represent matched pairs and distant vectors to represent mismatches.

Without that objective, the cosine similarity between two hidden states is a number one can compute, but nothing has trained it to rank matching pairs above mismatched ones. Sentence-BERT shows the difference: it fine-tunes BERT with siamese and triplet networks so that the pooled sentence vectors can be compared by cosine similarity, and its authors report that averaging BERT’s output layer without that training gives sentence vectors that are often worse, on similarity tasks, than averaged GloVe vectors. The property comes from that training; a hidden state or a mean-pooled activation of a model trained for something else cannot be assumed to have it.

Pooling is not developed further in this article. M3.11 derives the selection of valid rows, the forward and backward rules of pooling, projection, normalization, contrastive objectives, task heads, and the ways a retrieval model compares a query with a document.

Projected modality states

The media branch of 0x01 produces rows the model can consume:

Z_media is often called an image embedding, but it is a sequence of patch or query rows that will take part in the language model’s attention; no single vector in it stands for the image. A CLIP-style image embedding is the other case: one pooled vector per image, trained for similarity with text. Both come from a vision encoder; they differ in row count, in the objective that trained them and in what consumes them.

When debugging, it helps to say which object is meant: token lookup embeddings, layer-l contextual states, pooled retrieval embeddings, or projected media rows. The bare word embedding says nothing about the shape, the objective, the normalization or the similarity metric that applies.

The following diagram traces two paths through three of these objects:

Two paths: token IDs select rows of a parameter table to form the model's initial input state; contextual rows are pooled, projected, and normalized into one retrieval vector per record for an index. Checks between the paths compare origin, producer, visibility, construction, objective, and consumer.

The upper path produces the model’s initial input state; the lower path produces one retrieval vector per record. Before reusing a tensor from one path in the other, compare where it came from, which checkpoint produced it, what it could see, how it was pooled or normalized, what objective trained it, what consumes it, and which similarity metric it expects.

0x01C From the initial state to later readout

This article ends with the model’s initial state, of width d_model:

input_ids [B,L]
    -> input table and optional lexical bridge
        -> composed/scaled X0 [B,L,d_model]

The Transformer stack then creates contextual rows, and a later readout may select, pool, project, or normalize them:

X0 [B,L,d_model]
    -> M3.1-M3.7 contextual computation
        -> H [B,L,d_model]
            -> M3.11 row selection / pooling / task head
                -> task logits, values, spans, or retrieval representations

Equal widths do not make these stages one object. The lookup row comes from the ID-addressed table and goes into the construction of the initial state; the initial state, after the optional bridge, the addition of other rows and the scaling, goes into the Transformer blocks. Both are this article’s subject.

The contextual rows are produced by the block stack and read by later blocks or by a readout; M3.1 to M3.7 cover them. A pooled or task representation is built from selected contextual rows by a chosen readout rule and feeds a task head or a similarity function; M3.11 covers it. A searchable index is built from a representation encoder and a corpus and is read by a retrieval runtime; it belongs to the retrieval system, and M8.10 covers its deployment.

What later code needs from this article

To rebuild the initial state, the code that follows needs to know:

  • which tokenizer and ordered vocabulary the table was trained with;
  • which checkpoint holds the table, and how its rows map to IDs;
  • how padding is handled, and which other rows (position, segment) are added;
  • whether a bridge, a projection or a scale is applied on the way to X0;
  • in which dtype and on which shards the table lives, and which parameters alias it;
  • in what order the rows of X0 come, and which of them are valid.

Each of these is treated in a later section.

What that code cannot take from this article is a default sentence vector, a pooling rule, a contrastive objective, a similarity threshold or an approximate nearest-neighbour index. None of these follows from X0.shape, or from the fact that an API uses the word embedding. M3.11 starts from the contextual rows H, derives mask-correct pooling and its backward paths, types the sequence, token and span heads, defines normalized retrieval representations and their objectives, and compares cross-, bi- and late-interaction readouts. Building the index itself and rolling it out are the retrieval system’s work, with deployment in M8.10. The terminology stays here because the confusion between these objects is common; the derivations are in M3.11.


0x02 Text path: IDs are addresses

From tokenization, the text side starts with integer IDs. In the toy vocabulary of 0x01A:

"cat" -> 2314
"dog" -> 4812
"."   -> 13

The integers carry no meaning of their own: 2314 < 4812 does not mean cat < dog. The ID is an address into a table with one row per vocabulary entry, and the learned row at that address is the first continuous representation the model sees.

For a small vocabulary:

IDtoken
0<pad>
1<bos>
2<eos>
13.
2314cat
4812dog

the tokenized sequence:

cat dog .

might become:

input_ids = tensor([[2314, 4812, 13]])  # [B=1, L=3]

The Transformer block should not receive [2314, 4812, 13] as a vector of three numeric features. It should receive the three rows those addresses select:

[
  E[2314],
  E[4812],
  E[13],
]

The token ID answers “which row?”; the embedding vector is the learned content of that row. This split is why a tokenizer/model mismatch is so destructive. If one tokenizer says ID 2314 means cat, but the loaded model trained row 2314 for another token, the shape is still valid and the row has the wrong meaning.


0x02A One complete tensor and code trace

Take a batch of two sequences of four IDs, a toy table with eight rows of width three, and a bridge to width five:

B = 2
L = 4
V = 8
d_embed = 3
d_model = 5
pad_id = 0

with IDs:

input_ids = torch.tensor([
    [1, 4, 6, 2],
    [1, 5, 2, 0],
])  # [2,4]

attention_mask = input_ids.ne(0)  # [2,4]

The table has eight rows of width three. The gather appends that width to the shape of the IDs, and the bridge maps the result to width five:

E:                    [V=8,d_embed=3]
E[input_ids]:         [2,4,3]
P:                    [3,5]
X = E[input_ids] @ P: [2,4,5]

Row by row:

X[0,0] = E[1] @ P
X[0,1] = E[4] @ P
X[0,2] = E[6] @ P
X[0,3] = E[2] @ P

X[1,3] = E[0] @ P  # physical PAD row; later visibility must mask it

Code with assertions:

lookup = nn.Embedding(8, 3, padding_idx=0)
bridge = nn.Linear(3, 5, bias=False)

lexical = lookup(input_ids)
initial = bridge(lexical)

assert input_ids.shape == (2, 4)
assert input_ids.dtype == torch.int64
assert lexical.shape == (2, 4, 3)
assert initial.shape == (2, 4, 5)
assert attention_mask.shape == (2, 4)
assert torch.equal(initial[0, 0], bridge(lookup.weight[1]))

nn.Embedding does not apply the mask: the PAD position (1,3) still receives a row, E[0]. Attention and pooling must read attention_mask to leave that position out; padding_idx only controls the gradient of that table row.

Dtype and device trace

The objects in this trace have different dtypes. input_ids is an integer index tensor; attention_mask is boolean, or an integer type when a kernel or an API requires one; the embedding rows have the dtype of the weights, bf16, fp16 or fp32; the position IDs that M3.3 introduces are integers. Lookup does not require casting the IDs to floating point, and casting the rows back to integers destroys them. The IDs and the table must also be on the same device, unless the runtime routes the IDs:

assert input_ids.device == lookup.weight.device or runtime_can_route_ids()

Keeping the table on the CPU while the blocks run on the GPU can be a deliberate offload design; the transfer of the [B,L,d] rows is then part of the latency. An accidental device copy can cost more than the lookup itself, whose arithmetic is small.

Batch duplicates and gradients

In the example, ID 1 appears twice and ID 2 appears twice. Their input-side row gradients combine contributions from both batch rows. PAD ID 0 is selected once but receives no ordinary embedding gradient when padding_idx=0. Inspecting this trace catches three bugs at once: wrong address map, wrong PAD policy, and a mistaken assumption that each table row is updated at most once per batch.

0x02B Storage, dtype and strides of the traced tensors

The previous trace established values and shapes. An implementation still has to answer where each tensor is stored, which dtype interprets its bytes, which stride maps a logical coordinate to a storage offset, which operation materializes a new tensor, and which file gives an integer its row meaning. A shape such as [2,4] cannot tell us whether its entries are integer addresses or floating features, and a shape such as [8,3] cannot tell us which vocabulary ordering its rows follow. This section follows the trace of 0x02A through those properties, on the CPU and in float32:

input_ids:         shape [2,4]    dtype int64    strides [4,1] elements
embedding.weight:  shape [8,3]    dtype float32  strides [3,1] elements
gathered_rows:     shape [2,4,3]  dtype float32  strides [12,3,1] elements

The IDs come from the tokenizer’s batch. The table is the parameter embedding.weight, whose rows follow the toy vocabulary’s order. The gathered rows are a new tensor, produced by the forward pass from the table and this exact batch of IDs.

The phrase row-major contiguous means that the last coordinate has stride one. If table row i has width d_embed, coordinate k begins at logical element offset:

For d_embed=3, the selected rows of the trace begin at:

IDtable row start, in elementsselected positions
00(1,3), the PAD position
13(0,0) and (1,0)
26(0,3) and (1,2)
412(0,1)
515(1,1)
618(0,2)

The contiguous output uses a different address equation:

The two occurrences of ID 1, at positions (0,0) and (1,0), therefore read the same source row but occupy distinct output ranges, beginning at offsets 0 and 12. They have equal values, and neither is an alias of the parameter row or of the other. This matters in the backward pass: forward has materialized two sequence positions, and backward must combine the contributions of both into the one parameter row.

PyTorch describes a tensor through storage, dtype, shape, stride, and storage offset, and warns that views and contiguous copies have different storage behavior. Its indexing note also distinguishes basic views from advanced indexing copies. The accelerator kernel may stage, cache, vectorize or fuse the row loads differently; the equations above describe the logical layout, not the memory transactions.

Index dtype and weight dtype have different jobs

The documentation of nn.Embedding accepts integer index tensors and appends embedding_dim to their shape. The parameter is floating point, and the output has the parameter’s dtype: PyTorch autocast does not cast the lookup itself, so the rows keep that dtype until the first operator that autocast does cast, such as the bridge matmul. The address itself is never converted into a floating feature:

assert input_ids.dtype in (torch.int32, torch.int64)
assert embedding.weight.dtype.is_floating_point

rows = embedding(input_ids)

assert rows.shape == (*input_ids.shape, embedding.embedding_dim)
assert rows.dtype == embedding.weight.dtype  # absent another runtime policy

A quantized table, CPU offload, distributed routing or another framework’s cast policy can change that last assertion, and the code should say which of them does. A plain local lookup cannot use IDs on one device and a table on another; a runtime that accepts that is performing a copy or a route, and the bytes it moves and the synchronization it needs are part of its cost.

The PAD row is also physically selected during forward. padding_idx=0 does not remove position (1,3) from rows; it controls the gradient of that table row, and a newly constructed PyTorch embedding initializes the row to zeros. Leaving the position out of attention or of pooling is a separate operation.

The optional bridge after the gather

For the same gathered tensor, the trace applies the bridge P, a [d_embed=3,d_model=5] float32 matrix on the CPU with strides [5,1]:

X_model = gathered_rows @ P
[2,4,3] @ [3,5] -> [2,4,5]

The first two selected rows become:

E[1]       = [1, 0,  1]
E[1] @ P   = [1.5, 0, 1.5, -0.5, -1]

E[4]       = [2, 0, -1]
E[4] @ P   = [1.5, 0,   0,  0.5, -2]

The lookup still answers which lexical row is selected; the bridge decides how that row enters the model width. It costs:

For this trace the bridge performs 2*4*3*5 = 120 MACs. 0x05A compares the direct and the factorized table in parameters and compute; here only the forward shapes matter.


0x03 nn.Embedding and Harvard Embeddings.forward

The Harvard-style Transformer code makes the text bridge explicit:

class Embeddings(nn.Module):
    def __init__(self, d_model, vocab):
        super(Embeddings, self).__init__()
        self.lut = nn.Embedding(vocab, d_model)
        self.d_model = d_model

    def forward(self, x):
        return self.lut(x) * math.sqrt(self.d_model)

In this class, x holds the integer token IDs (not strings, and not float features); nn.Embedding(vocab, d_model) is the trainable lookup table with vocab rows and d_model columns; self.lut(x) selects the rows; and math.sqrt(self.d_model) is the scaling convention of the original Transformer, which the Harvard code keeps. The return value holds the content embeddings, of shape [B,L,d_model].

PyTorch’s documentation calls nn.Embedding a lookup table. Its trainable parameter has shape [num_embeddings, embedding_dim], which for this article is [V, d_model]. The input is an integer tensor of indices, LongTensor[B, L], and the output appends the embedding dimension, FloatTensor[B, L, d_model]. The text bridge of the Harvard code is therefore:

embedding = nn.Embedding(
    num_embeddings=V,
    embedding_dim=d_model,
    padding_idx=pad_id,   # optional, but often important
)

x = embedding(input_ids)  # [B, L, d_model]

The Harvard wrapper then multiplies the rows by math.sqrt(d_model). The shape stays [B,L,d_model], so a missing or doubled factor passes every shape check; it changes the values that positional encoding and attention receive, and a close reproduction of the original Transformer applies it exactly once.

Token IDs select rows from an embedding matrix to produce dense vectors

The lookup table is also where training acts. During backpropagation, the rows used by the batch receive gradient updates: if token 2314 appears, row E[2314] is part of the computation graph, and a row that does not appear in the batch usually receives no update from that example. This is the first place where token IDs become learned continuous states.

0x03A Initialization and the sqrt(d_model) convention

Before training, an embedding row is an initialized parameter vector, and the question of what the multiplier does to it starts with the initializer.

Suppose the coordinates of row are independent with mean and variance . Linearity of expectation gives:

For a zero-mean initializer and a scalar multiplier :

If the desired coordinate variance is , the matching scale is . The choice therefore produces unit coordinate variance only when ; with any other initializer it produces a different variance, computed next for the Harvard code.

Xavier initialization and the multiplier in the Harvard code

The original Transformer paper states that the embedding weights are multiplied by , without deriving the choice from an initializer. The Harvard implementation applies the multiplier in Embeddings.forward:

return self.lut(x) * math.sqrt(self.d_model)

But make_model later applies Xavier uniform initialization to every parameter with more than one dimension. That includes each rectangular embedding table:

for p in model.parameters():
    if p.dim() > 1:
        nn.init.xavier_uniform_(p)

For gain , PyTorch defines Xavier uniform on a two-dimensional tensor as:

Since a zero-mean uniform variable on has variance :

For a PyTorch table stored as [V,d_model], the two-dimensional fan convention gives and . After the Harvard multiplier:

At V=32,000, d_model=512, and g=1:

Xavier coordinate variance before scale:  2 / 32,512 ~= 0.00006151
coordinate variance after sqrt(512):       0.03150
expected squared row norm after scale:     16.13
approximate RMS per scaled coordinate:     0.1775

The common sentence “Xavier has variance 1/d_model, so sqrt(d_model) restores variance one” holds for a square matrix. For the rectangular table of the Harvard code, the variance after scaling is 0.0315, not one.

The multiplier is often explained as balancing the token rows against the positional encoding. If the content coordinates have RMS and the positional coordinates at a given position have RMS , their RMS ratio before dropout is:

Sinusoidal coordinates are bounded by one, but their exact RMS depends on the position and the frequencies. Multiplying by raises the content side of this ratio; whether the two sides end up equal depends on and , and the derivation says nothing about training stability.

The convention is specific to one code lineage. In the original Transformer and its Harvard reconstruction, the global Xavier pass reaches the [V,d_model] table, the scaled token row is added to a fixed sinusoidal position and dropout follows, and the token scale is sqrt(d_model). In the original BERT code, the table is initialized from a truncated normal with the configured initializer_range (default 0.02), the token, token-type and learned-position rows are summed and followed by LayerNorm and dropout, and no scale is applied in the embedding path.

The GPT-2 code lineage uses a model-specific normal initialization, adds a learned-position row to the token row and applies dropout, again with no scale. A LLaMA-style decoder with RoPE initializes the table as its model code prescribes, sends the token row straight into the residual stream, and rotates the attention queries and keys instead of adding a position row, so there is no additive position to balance against. Other designs normalize the embedding output or scale the residual stream instead, with no explicit multiplier. These are the conventions of the source code and say nothing about model quality; when reproducing a checkpoint, apply the multiplier if its architecture does, and otherwise not. M3.3 covers the geometry and the extrapolation behavior of sinusoidal, learned, relative and rotary positions.

Another common explanation, that the multiplier keeps the attention dot products from exploding, is incomplete: attention scales QK^T by 1/sqrt(d_k) on its own. The input multiplier sets the scale of the content state before projection and composition; what reaches the dot products has passed through the learned projections and the normalization layers.

Fresh initialization, exact load and vocabulary growth

A constructor, a checkpoint loader and a vocabulary-resize procedure all produce a tensor of shape [V,d_model], and each may write different rows of it. A fresh initialization may write every row, according to a named initializer and a policy applied afterwards (zeroing the PAD row, for example); reproducing it needs the seed or generator, the initializer’s parameters, any later mutation of the rows and the place where the scale is applied, and the framework’s defaults must not be described as the trained distribution of a checkpoint.

An exact checkpoint load changes no row, apart from a dtype or device conversion that was decided in advance; it checks the source key, the shape, the address hash, the source and target dtypes, finiteness and, when one exists, the tensor hash, and it fails on a missing key instead of keeping the constructor’s random rows.

Vocabulary growth writes only the appended or explicitly remapped rows; it checks that the old prefix is equal, names the initializer of the new rows, updates the tokenizer and the configuration, expands the optimizer state and restores the ties, and it never resizes the input table without its output and optimizer dependents.

def materialize_embedding(spec, checkpoint=None):
    table = allocate(spec.shape, dtype=spec.parameter_dtype)

    if spec.state == "fresh_initialization":
        initialize_(table, spec.initializer, generator=spec.generator)
        apply_post_init_constraints_(table, spec.padding_policy)

    elif spec.state == "exact_checkpoint_load":
        saved = require_tensor(checkpoint, spec.source_key)
        require_shape_address_and_finite(saved, spec)
        table.copy_(admitted_cast(saved, spec.parameter_dtype))

    elif spec.state == "vocabulary_growth":
        old = require_tensor(checkpoint, spec.source_key)
        require_exact_old_prefix(old, spec)
        table[: old.shape[0]].copy_(old)
        initialize_(table[old.shape[0] :], spec.new_row_initializer)
        expand_optimizer_rows_and_restore_ties(spec)

    else:
        raise ValueError("unknown embedding materialization state")

    return table

An exact load checks more than shape:

def assert_embedding_checkpoint(module, state_dict, key, address_hash):
    saved = state_dict[key]
    assert saved.shape == module.weight.shape
    assert state_dict["tokenizer_address_hash"] == address_hash
    assert torch.isfinite(saved).all()
    assert saved.dtype == module.weight.dtype or can_safely_cast(saved.dtype)

The current Hugging Face resize_token_embeddings offers a model-default initializer and a growth option based on the mean and covariance of the old rows, and re-ties the weights when the model class implements tie_weights(); that is the behavior of one helper in one version. A custom implementation still has to check that the old rows were preserved, that the new output rows and biases were handled, that the optimizer state was expanded, that the aliases were restored, and that the tokenizer hash now names the larger address space. M2.1 covers the allocation of IDs on the tokenizer side; 0x05D covers the whole migration.

0x03B nn.Embedding options change training behavior

The compact constructor hides several independent policies:

nn.Embedding(
    num_embeddings=V,
    embedding_dim=d_model,
    padding_idx=pad_id,
    max_norm=None,
    norm_type=2.0,
    scale_grad_by_freq=False,
    sparse=False,
    _weight=None,
)

Each argument is a policy of its own:

  • padding_idx prevents that row from receiving ordinary embedding gradients; the masks and the tokenizer’s PAD ID must agree with it;
  • max_norm renormalizes the selected rows whose norm exceeds the threshold, so the forward pass modifies the weight in place;
  • norm_type chooses the norm used by max_norm, usually L2 but not fixed;
  • scale_grad_by_freq divides each row’s gradient by the frequency of its ID in the batch, which changes the weighting of repeated tokens;
  • sparse makes the table’s gradient a sparse tensor, which restricts the compatible optimizers and distributed paths;
  • _weight initializes the table from a supplied tensor, whose shape and padding semantics must match.

What padding_idx does to the PAD row

In the current PyTorch source, a freshly constructed nn.Embedding samples its weight with normal_() and then zeros weight[padding_idx]. Supplying _weight skips reset_parameters, so the supplied padding row is not automatically zeroed. A later global initializer, checkpoint load, direct assignment, or tied output path can also produce a nonzero row.

Forward lookup still returns whatever row is stored at padding_idx. The option suppresses the ordinary lookup gradient for that row; it does not hide the row from attention, remove it from the loss, or protect it from the other ways a row can change.

For example, with dense AdamW and a present gradient tensor, decoupled weight decay applies to the parameter before the gradient update:

A zero row stays zero under that multiplication; a nonzero custom PAD row shrinks at every step on which weight decay is applied to the table. Whether the equation applies at all depends on the optimizer: some skip a parameter whose gradient is absent, and the sparse paths differ, so the optimizer and the gradient layout in use decide.

max_norm makes lookup forward stateful

Let be the set of distinct row IDs selected by the input. Ignoring the kernel’s small numerical guard, max-norm applies:

Only the selected rows are candidates, and a row selected twice is renormalized once. With p=2, m=2 and the selected IDs [1,2,1,0]:

row 1 before: [3.0, 4.0, 0.0, 0.0]   norm 5.0
row 1 after:  [1.2, 1.6, 0.0, 0.0]   norm 2.0

row 2 before: [0.0, 0.0, 0.6, 0.8]   norm 1.0
row 2 after:  unchanged

row 3 before: [6.0, 8.0, 0.0, 0.0]   norm 10.0
row 3 after:  unchanged because row 3 was not selected

PyTorch performs this selected-row renormalization in-place during forward, before returning gathered rows. A checkpoint or table hash can therefore change after an inference-only call even when backward and the optimizer never run. If a differentiable computation uses embedding.weight before the embedding call, clone the weight or reorder operations according to the official API warning; otherwise autograd can see a versioned tensor modified in place.

embedding = nn.Embedding(V, d, max_norm=1.0)

# Clone if this pre-forward use participates in autograd.
penalty = regularizer(embedding.weight.clone())
x = embedding(input_ids)
loss = task_loss(x) + penalty

A trace of the forward pass should record which rows it changed:

selected = torch.unique(input_ids)
before = embedding.weight.detach()[selected].clone()
output = embedding(input_ids)  # may mutate selected rows when max_norm is set
after = embedding.weight.detach()[selected]

assert torch.linalg.vector_norm(after, ord=2, dim=-1).max() <= 1.0 + tolerance
record_rows_that_changed(selected, before, after)

With sparse=True, check that the optimizer accepts sparse gradients; 0x04A lists which do. Sparse gradients also behave differently from dense ones under gradient clipping, weight decay and distributed collectives.

0x03C The numerical states of one table

The sentence “the embedding is bf16” leaves open which of at least six numerical states it describes. For each state, the list gives its usual dtypes, who holds it, and what a run has to record:

  • the serialized checkpoint tensor, in fp32, bf16, fp16 or an encoded or quantized format, defined by the checkpoint format: the logical tensor key, the encoding, the source dtype and the hashes;
  • the live parameter storage, fp32, bf16 or fp16, held by the module or the runtime: its storage dtype, device, sharding and alias identity;
  • the gathered forward output, which for a direct lookup usually follows the live table, decided by operator dispatch: the observed output dtype and the cast policy of the scale and the addition that follow;
  • the autocast compute dtype, fp32, fp16 or bf16 per operator, chosen by the autocast dispatcher: the enabled region, the target dtype and what each operator actually does;
  • the gradient, dense or sparse, with a dtype that depends on the runtime, produced by autograd: its layout, dtype, scaling state and who reduces it;
  • the optimizer and master state, often fp32 moments with an optional master copy, held by the optimizer or the runtime: the dtype of the moments, whether a master copy exists and the dtype of the update.

PyTorch autocast chooses dtypes per operator; entering an autocast region does not prove that the parameter itself was converted. Gradient scaling multiplies the loss to protect small fp16 gradients and unscales before the optimizer step; it does not define checkpoint dtype or guarantee a separate fp32 master table. Some systems keep fp32 parameters and use lower-precision compute, some store lower-precision parameters with fp32 optimizer state, and some maintain an explicit master copy. A run should record which of the three it uses, for example:

embedding_numerical_state:
  checkpoint_dtype: float32
  parameter_storage_dtype: bfloat16
  lookup_output_dtype: bfloat16
  input_scale: sqrt_d_model
  scale_application_count: 1
  autocast:
    enabled: true
    target_dtype: bfloat16
    observed_lookup_policy: follows_parameter_storage
  gradient:
    layout: dense
    dtype: bfloat16
    grad_scaler: false
  optimizer:
    name: AdamW
    first_moment_dtype: float32
    second_moment_dtype: float32
    master_weight: explicit_float32_copy
  max_norm:
    enabled: false

This record is one example; PyTorch’s automatic mixed precision does not prescribe it. A reproducible run records the observed dtype of each tensor and of the optimizer state, and checks that values are finite after each cast: lower precision has a finite range and rounding limits, and mathematically equivalent operation orders need not be bitwise identical across devices or releases.

Embedding numerical-state lifecycle separating fresh initialization, exact checkpoint load, vocabulary growth, scaling, padding, max-norm mutation, and runtime dtype ledgers

The figure has two independent axes. The horizontal path shows which rows may be written: fresh initialization, exact load or growth. The vertical list shows which representation of those rows exists at each stage of a run. A valid shape on one axis says nothing about the other.

Checking the rules on a toy table

These rules can be checked on a [5,4] toy table with four initializers, a checkpoint whose PAD row is deliberately nonzero, and max_norm=2 applied to the IDs [1,2,1,0] of the max_norm example in 0x03B. The forward call changes row 1 from [3,4,0,0] to [1.2,1.6,0,0]; rows 0 and 2 are selected and unchanged; rows 3 and 4 are unchanged although row 3 has norm 10, because they were not selected. Growing the table keeps the old five-row prefix exactly, gives the new rows a zero optimizer state, and restores the weight tie afterwards.

The same checker should reject mixed state provenance, an undeclared initializer, an address, shape or cast mismatch, non-finite values, an invalid norm policy, out-of-range IDs, mutated old rows, a missing policy for the new rows, malformed optimizer state, a lost tied alias, double scaling and an assumed master weight. Such a check proves the rules on these values; it says nothing about a framework kernel, the sampling distribution of an initializer, convergence, or a production mixed-precision layout.


0x04 One-hot as conceptual row selection

One-hot vectors are useful for understanding embedding lookup.

For a vocabulary of size V, a token ID can be represented as a vector with one 1 and all other entries 0:

id = 3
one_hot(id) = [0, 0, 0, 1, 0, ...]

If:

then:

Write the scalar selector as , where:

Then coordinate of the product is:

The sum collapses to a gather because every term except row i is multiplied by zero. The algebra is exact; whether a lookup should build the sparse vector is a separate question, answered below.

For a sequence , stack the selectors into:

The sequence result is:

For a whole batch:

More explicitly, let:

Contracting the vocabulary axis gives:

This is how to think about lookup, and it is not how to compute it: for a real vocabulary the one-hot tensor would be mostly zeros and very large, so nn.Embedding does an indexed lookup instead and returns the same selected rows without materializing it. The distinction matters when reading code:

correct:
    nn.Embedding(...)(input_ids)

conceptual:
    one_hot(input_ids) @ E

wrong:
    nn.Embedding(...)(one_hot(input_ids))

nn.Embedding expects integer indices, not strings, one-hot vectors or already embedded floats.

The selector’s width is the declared V. Inferring num_classes from the largest ID in one batch gives a selector whose last dimension changes from sample to sample, while the table’s row order is fixed for the whole model; the selector uses V even when the batch touches only a few rows. The two paths, compared in code:

def one_hot_reference(ids, weight):
    V = weight.shape[0]  # declared table width, not ids.max()+1
    selectors = F.one_hot(ids, num_classes=V)
    selectors = selectors.to(dtype=weight.dtype, device=weight.device)
    return selectors @ weight

def gather_path(ids, weight):
    return F.embedding(ids, weight)

dense = one_hot_reference(input_ids, embedding.weight)
gathered = gather_path(input_ids, embedding.weight)
torch.testing.assert_close(dense, gathered)

torch.nn.functional.one_hot returns a LongTensor, so the conceptual matrix product needs an explicit cast to the table’s compute dtype. The gather path avoids both the casted selector and its vocabulary-sized intermediate.

Why materializing one-hot is the wrong execution plan

For B=8, L=2048, and V=128,000:

ID entries:              8 * 2048             = 16,384
one-hot entries:         8 * 2048 * 128,000   = 2,097,152,000

int64 IDs:                                      128 KiB
int64 one-hot result:                            15.625 GiB
float16 selector after cast:                      3.906 GiB
entry-count ratio:                              128,000x

These numbers count the logical payload only, without allocator, kernel or workspace overhead. Indexed lookup reduces the operation to what is needed: read BL addresses and produce BL*d_model floating values. Nothing in the mathematics requires the zero multiplications of a dense [BL,V] @ [V,d_model] product.

Scalar, sequence, and batched one-hot selectors reduce to row gather while preserving explicit tensor identity, layout, and materialization boundaries

0x04A Backward pass: gather becomes scatter-add

With repeated IDs, optional frequency scaling, a dense or sparse gradient, and a table spread across several ranks, two questions arise: which contributions belong to each row, and which process applies the update to it. The first has one answer, from the algebra: every occurrence of row j contributes to one logical dE[j]. The second is a choice of schedule: a declared rank stores, reduces and updates all or part of row j, through replication, routed rows, masked local lookup, column shards, fused optimizers or another arrangement. This section derives the first answer and then follows four schedules for the second.

Deriving scatter-add from the forward selector

Flatten the B x L position axes into N=BL. Let i_t be the global token ID at position t, let be the table, and define the conceptual selector:

The gather proof from 0x04 can be written as a matrix product without materializing S:

For upstream gradient , take a differential:

Therefore:

and row j receives:

The transpose changes a forward gather into a backward scatter-add. It also explains why duplicate IDs cannot use overwrite semantics: several rows of G map to the same parameter row.

If padding_idx=p, the embedding operation removes that row’s ordinary lookup gradient. Define:

Then the input-path gradient is . This does not erase the PAD row from other parameter uses, regularizers, or a tied output path.

One duplicate-ID tensor trace

Use V=8, d=3, padding_idx=0, and two local batches:

origin rank 0
IDs:       [1,       4,       1,       0]
G rows:    [[1,0,1], [0,2,0], [3,1,0], [9,9,9]]

origin rank 1
IDs:       [4,       6,       1,       4]
G rows:    [[2,0,1], [0,1,3], [1,2,1], [4,1,0]]

The PAD occurrence contributes nothing through this operator. Summing all other occurrences gives:

dE[1] = [1,0,1] + [3,1,0] + [1,2,1] = [5,3,2]
dE[4] = [0,2,0] + [2,0,1] + [4,1,0] = [6,3,1]
dE[6] = [0,1,3]
dE[0] = [0,0,0] through the lookup path
all other rows = [0,0,0]

In code, as a dense reference:

def embedding_backward_dense(ids, grad_output, vocab_size, padding_idx=None):
    ids = ids.reshape(-1)
    rows = grad_output.reshape(ids.numel(), -1)
    keep = torch.ones_like(ids, dtype=torch.bool)
    if padding_idx is not None:
        keep &= ids != padding_idx

    grad_weight = rows.new_zeros((vocab_size, rows.shape[-1]))
    grad_weight.index_add_(0, ids[keep], rows[keep])
    return grad_weight

The implementation may use atomics, sorting, a segmented reduction or a fused kernel. Only the sum is specified, not the order of the floating-point additions, so the device, and whether deterministic mode is on, can change the last bits of the result; the row that receives the sum is the same in every case.

Frequency scaling has a count scope

Let the non-PAD count of row j in the operator’s local mini-batch be:

With scale_grad_by_freq=True, PyTorch computes:

The count is taken inside one call of the embedding operator. In ordinary data parallelism, each rank makes that call before the gradients are synchronized, so rank-local frequency scaling followed by a sum is in general not the same as scaling by the global frequency:

For the trace above:

rank-local frequency scaling, then SUM
row 1: [4,1,1]/2 + [1,2,1]/1 = [3,2.5,1.5]
row 4: [0,2,0]/1 + [6,1,1]/2 = [3,2.5,0.5]

global effective-batch frequency scaling
row 1: [5,3,2]/3 = [1.6667,1,0.6667]
row 4: [6,3,1]/3 = [2,1,0.3333]

Neither expression is automatically the intended objective. The count scope, the data-parallel reduction (SUM or AVG), the gradient accumulation window and the loss normalization together decide the row update, so record all four: a change of world size or of microbatch partition changes the update while every tensor shape stays valid.

scale_grad_by_freq=True and sparse=True do not combine in current PyTorch: in the Embedding.cpp source linked in the references, embedding_sparse_backward rejects scale_grad_by_freq=True with a not-supported error. The equations above describe the dense frequency-scaled derivative; a sparse-layout execution has to leave frequency scaling off or implement and verify its own reduction.

Dense and sparse storage of the same gradient

The dense representation materializes [V,d], including zero rows. A sparse COO-style representation can initially store one row value per valid occurrence:

uncoalesced row indices: [1,4,1,4,6,1,4]
uncoalesced values:      seven [d] upstream rows

After coalescing duplicate indices:

coalesced row indices: [1,4,6]
coalesced values:      [[5,3,2], [6,3,1], [0,1,3]]
logical dense shape:   [8,3]

Coalescing does not change the derivative. It establishes one stored value per touched row and makes duplicate summation explicit:

def coalesced_sparse_rows(ids, grad_output, padding_idx=None):
    ids = ids.reshape(-1)
    values = grad_output.reshape(ids.numel(), -1)
    if padding_idx is not None:
        keep = ids != padding_idx
        ids, values = ids[keep], values[keep]

    unique_ids, inverse = torch.unique(ids, sorted=True, return_inverse=True)
    coalesced = values.new_zeros((unique_ids.numel(), values.shape[-1]))
    coalesced.index_add_(0, inverse, values)
    return unique_ids, coalesced

PyTorch’s current nn.Embedding documentation says sparse=True makes the weight gradient a sparse-layout tensor. That is narrower than saying the parameter, optimizer state, checkpoint, or every gradient path is sparse. SparseAdam explicitly targets dense-layout parameters receiving sparse-layout gradients and updates only materialized entries and their moments.

For V=128,000, d=4096, fp32 gradient values, and U=4096 unique touched rows:

dense gradient values:       V*d*4 = 1.953 GiB
coalesced sparse values:      U*d*4 = 64 MiB
int64 row indices:            U*8   = 32 KiB

These are logical payloads. Sparse tensor objects, allocator metadata, the sort and coalesce workspace, optimizer state and collective buffers add overhead, and if almost every row is touched, or a later path creates a dense contribution, the advantage shrinks or disappears.

Optimizers, clipping and weight decay with sparse gradients

The current nn.Embedding documentation lists only three built-in optimizers for sparse embedding gradients: SGD on CPU and CUDA, SparseAdam on CPU and CUDA, and Adagrad on CPU only. The list names optimizers, not their options: it does not say whether SGD with weight decay, momentum, foreach or a fused implementation works with a sparse gradient, and SparseAdam is a masked approximation of Adam for a dense parameter with a sparse-layout gradient, without the semantics of dense AdamW. Adam, AdamW and the unlisted optimizers need an explicitly compatible path or a dense gradient. A check after backward() should look at the gradient that was actually produced:

loss.backward()
grad = embedding.weight.grad

assert grad is not None
if embedding.sparse:
    assert grad.layout == torch.sparse_coo
    grad = grad.coalesce()
    require_sparse_optimizer_contract(optimizer, grad.device)
else:
    assert grad.layout == torch.strided

Gradient clipping also needs a representation and ownership policy. For a coalesced sparse gradient sharded by row, the global L2 norm can be computed without densifying:

A generic clipping helper may support neither sparse layouts nor sharded gradients; PyTorch FSDP, for example, provides its own global-norm method, because a local clip_grad_norm_ sees only the local shard.

Weight decay works against the idea of touching only the selected rows: dense decoupled weight decay updates every row at every step, including the rows absent from the batch. A sparse system has to choose among no decay, a supported masked approximation, a lazy decay applied with a timestamp when a row is next touched, periodic dense maintenance, or densification, and the choices give different numbers.

A tied output head can make the total gradient dense

0x0A treats weight tying in full; here only its effect on the gradient matters. If the logits use the same table:

then for :

D normally has a vocabulary-wide softmax contribution, so is generally dense even when the input lookup touched only a few rows. A tied parameter gets:

sparse=True on the input module therefore does not make the total gradient of a shared parameter sparse. The runtime needs one layout and one optimizer path that accept both contributions; dropping either one gives a wrong gradient.

The reduction convention comes first

Let origin rank r own a local batch and produce . For a replicated table with SUM reduction:

With AVG, either the collective or the loss convention introduces the factor 1/R; applying both divides twice, and applying neither changes the effective learning rate. The training configuration therefore has to state the loss reduction within each rank, the microbatch accumulation rule, whether the data-parallel collective is SUM or AVG, which axis the model-parallel ownership follows, and who holds the optimizer state.

Data parallelism and model parallelism are independent axes. A row can be partitioned across tensor-parallel ranks and each resulting shard can still be replicated across a data-parallel group.

Schedule A: replicated table plus data-parallel reduction

Each rank holds all V*d parameters and optimizer state:

local_grad = scatter_add(local_ids, local_upstream, shape=(V, d))
global_grad = all_reduce_sum(local_grad, data_parallel_group)
embedding.weight.grad.copy_(global_grad)
optimizer.step()  # identical state and update on every replica

This has simple address semantics but a dense gradient collective when the runtime uses ordinary dense DDP buckets. Sparse communication needs a separate supported design; sparse=True alone does not rewrite a data-parallel reducer.

Schedule B: row owners with routed IDs and gradients

Partition rows into disjoint intervals [s_r,e_r) that cover [0,V) exactly once. The owner function is:

Forward preserves origin-position metadata:

requests = pack_by_owner(input_ids, origin_rank, origin_position)
owner_requests = all_to_all(requests, model_parallel_group)

owner_rows = local_table[owner_requests.global_id - shard_start]
responses = pack_by_origin(owner_rows, owner_requests.origin_position)
X = all_to_all(responses, model_parallel_group).restore_position_order()

Backward reverses the route:

owner_grads = all_to_all(
    pack_by_saved_owner(grad_output, origin_position),
    model_parallel_group,
)

local_grad = scatter_add(
    owner_grads.global_id - shard_start,
    owner_grads.value,
    shape=local_table.shape,
)
local_optimizer.step(local_table, local_grad)

The origin rank keeps the sequence order; the row-owner rank holds the parameter and the optimizer state. Losing origin_position, applying global IDs directly to a local shard, or stepping a copy that is not the owner all produce plausible shapes and wrong rows.

TorchRec’s official sharding material uses the analogous input_dist -> lookup -> output_dist decomposition and supports table-wise, row-wise, column-wise, table-row-wise, and data-parallel plans. Its examples use embedding-bag systems, so TorchRec appears here as a general sharding design; its pooled operator is not the token-table lookup of a language model.

Schedule C: Megatron-Core masked local vocabulary lookup

Megatron-Core’s VocabParallelEmbedding is a language-model example of row ownership that does not route each ID to its owner. At commit 542ff5368611682f3f8d5487595647c13e02801b, each tensor-parallel rank:

  1. derives its contiguous [vocab_start_index,vocab_end_index);
  2. marks non-local IDs with input_mask;
  3. subtracts vocab_start_index from local IDs and maps non-local IDs to safe local index zero;
  4. performs local F.embedding;
  5. zeros outputs at non-local positions;
  6. reduces the partial outputs across the tensor-parallel group, or optionally reduce-scatters embedding outputs along the sequence-parallel path.

The core trace is:

input_mask = (ids < vocab_start) | (ids >= vocab_end)
masked_input = ids.clone() - vocab_start
masked_input[input_mask] = 0

output_parallel = F.embedding(masked_input, local_weight)
output_parallel[input_mask, :] = 0.0
output = reduce_from_tensor_model_parallel_region(output_parallel)

Because exactly one row shard contributes a nonzero value for each valid ID, the reduction reconstructs the full embedding output. In backward, each local table receives scatter-add contributions only for IDs in its vocabulary range. The tensor-parallel row owner can update its shard without all-reducing that shard’s weight gradient across the same ownership axis. A separate data-parallel group may still reduce replicas of the shard.

This is the trace of one version of one implementation; other vocabulary-parallel schedules exist. The optional reduce-scatter branch changes where the output lives and which backward collective autograd pairs with it, so a configuration has to say whether it is on.

Schedule D: column-wise table ownership

Partition the feature columns into disjoint intervals [a_r,b_r) that cover [0,d) exactly once. Every column owner needs the IDs, but rank r gathers only:

If the next operator needs a full hidden row, concatenate the partial outputs:

Backward splits G over the same column intervals and scatter-adds each slice into its owner:

for column_owner, (start, end) in column_shards:
    local_grad = scatter_add(ids, grad_output[:, start:end], shape=(V, end-start))
    column_owner.optimizer.step(local_grad)

Materializing X on one origin can pair forward concatenation/all-gather with a backward split. Replicating a full X and computing losses on several ranks can require reductions of partial-input gradients. Keeping X sharded can avoid a collective only when the next operator accepts that layout. “Column-wise” describes where the weights are; the activations still need a schedule of their own.

Bytes moved in the toy trace

Let values use b bytes, IDs use b_i, route metadata use b_m, and let N_remote count routed occurrences whose owner differs from their origin. A simple owner-routed logical payload is:

The two value terms are the forward row response and backward row gradient. For the two-rank trace, N_remote=2, d=3, b=4, and b_i=b_m=8:

ID + metadata requests: 2*(8+8) = 32 bytes
forward row responses:   2*3*4   = 24 bytes
backward row gradients:  2*3*4   = 24 bytes
logical routed payload:             80 bytes

For comparison:

replicated dense DP gradient buffer per rank: V*d*b = 8*3*4 = 96 bytes
Megatron masked-local output reduction buffer: N*d*b = 8*3*4 = 96 bytes
column-wise full-output concatenation payload: N*d*b = 96 bytes

These are the sizes of the tensors, not the time on the wire: the collective algorithm, the world size, local routes, deduplication, padding, topology, bucket fusion, overlap and the route metadata that is kept all change the actual traffic. M4 covers communication and performance accounting in general; the question here is only which tensor has to move.

Embedding backward ownership showing duplicate-ID scatter-add, dense and sparse gradient layouts, tied-output densification, and replicated, row-wise, masked-local, and column-wise distributed schedules

Checking the schedules on the toy trace

The [V=8,d=3] trace can be run under the five arrangements of this section: one table with dense scatter-add, replicated local scatter-add followed by SUM, row owners with routed gradients, Megatron-style masked local ownership, and column-wise ownership followed by concatenation. With these integer values, every distributed reconstruction equals the single-table result exactly. The same run shows that rank-local and global frequency scaling differ, with the values given above; that the coalesced sparse rows densify to the same input gradient; that a tied output contribution materializes every row of the toy total gradient; and that an optimizer check has to look at the gradient’s layout, its device, the clipping and the tying.

A checker should reject PAD leakage, out-of-range IDs, malformed upstream rows, gaps and overlaps in row or column shards, a wrong update owner, an unsupported sparse optimizer or device, a dense gradient sent to a sparse-only optimizer, undeclared clipping, a tied dense path under a sparse-only setup, the unsupported pairing of sparse gradients with frequency scaling, a wrong frequency scope, a wrong collective reduction, and missing coalescing. Such a check proves the arithmetic and the reconstruction of ownership; it says nothing about NCCL ordering, the performance of a topology, a fused optimizer kernel, or bitwise equality under arbitrary floating-point reduction orders.

0x04B Lookup, bag reduction and projection

The word embedding names APIs with different shapes and different meanings. Several of them produce outputs of the same width and still cannot replace one another.

Dense one-hot linear and indexed lookup

A bias-free linear layer over a materialized categorical selector can reproduce lookup. PyTorch stores a linear weight as [d_out,d_in], so set:

Then:

The values match, but the two operators take different inputs. The indexed lookup takes integer addresses [B,L] and the table [V,d_embed], and returns the selected rows [B,L,d_embed]; the dense one-hot linear layer takes floating selectors [B,L,V] and the transposed table [d_embed,V], and returns the contraction [B,L,d_embed]. Adding a bias would break the exact equivalence with lookup. Feeding raw integer IDs to the linear layer would treat each ID as a scalar feature, which is a different and invalid model.

EmbeddingBag gathers and removes the position axis

nn.EmbeddingBag computes a sum, mean, or coordinate-wise maximum over bags without exposing the full intermediate row tensor. Let offsets delimit bag as the half-open range . Excluding padding_idx, sum and mean are:

For the two sequences of the 0x02A trace, taken as bags, with the same toy table:

flat IDs = [1,4,6,2 | 1,5,2,0]
offsets  = [0,4,8]
pad ID   = 0, excluded from reduction

sum:
    bag 0 -> [2.0, 3.0, 1.5]
    bag 1 -> [1.5, 0.5, 3.0]

mean:
    bag 0 -> [0.5000, 0.7500, 0.3750]  # denominator 4
    bag 1 -> [0.5000, 0.1667, 1.0000]  # denominator 3, PAD excluded

The output shape is [num_bags,d_embed] instead of [B,L,d_embed]. This suits unordered bags of features; it cannot replace token lookup before a Transformer, which needs every position and its order.

Factorized lookup preserves addresses and positions

Factorized lookup composes two operators:

Unlike EmbeddingBag, it preserves every input position; unlike direct lookup, it adds a dense bridge and allows d_embed != d_model. 0x05A weighs its costs and savings; here it only has to be distinguished from pooling.

A continuous projector has no vocabulary row address

For encoder features:

a count-preserving projector computes:

Every floating input coordinate contributes through learned weights; no integer selects a row of a vocabulary table. A toy projector maps [2,2,2] @ [2,5] -> [2,2,5] without consuming input_ids, the tokenizer’s row order or padding_idx. X1.2 covers how real non-text encoders and projectors are trained and integrated; the comparison stays here because the two outputs can both be [B,N,d_model] while being built in different ways.

To sum up the five operators:

  • indexed lookup takes categorical addresses [*] and a [V,d_embed] table, returns [*,d_embed], and preserves every address position; the wrong use is to pass float features as IDs;
  • the one-hot linear layer takes categorical selectors [...,V] and a [d_embed,V] linear weight, returns [...,d_embed], and preserves the positions while materializing V; the wrong use is to infer the selector width from the batch maximum;
  • EmbeddingBag takes IDs plus bag boundaries and a [V,d_embed] table, returns [num_bags,d_embed], and reduces the positions inside each bag; the wrong use is to put it before order-sensitive attention;
  • factorized lookup takes categorical addresses [B,L], a [V,d_embed] table and a [d_embed,d_model] bridge, returns [B,L,d_model], and preserves the positions while changing the width; the wrong use is to call the bridge a second lookup;
  • a continuous projector takes float feature rows [...,d_in] and an affine map to d_out, returns [...,d_out], and usually preserves the row count; the wrong use is to feed token IDs as scalar features.

Checking the operators on the toy trace

On the toy trace, a check of the claims of 0x04 and of this section confirms that:

  • scalar one-hot multiplication equals scalar row selection, sequence one-hot multiplication equals the sequence gather, and the batched one-hot contraction equals the batched gather exactly;
  • num_classes comes from the declared address space, not from the batch maximum;
  • the IDs use an admitted integer dtype and lie in [0,V);
  • the table, the IDs, the bridge and the projector declare their shape and element strides, and the tensors of a primitive lookup are on one device, or a runtime route is named;
  • the gathered output is materialized separately from the table’s storage: ID 1 produces two output positions, (0,0) and (1,0), from one row;
  • PAD is physically selected, at position (1,3), while the gradient and visibility policies stay separate;
  • the bridge’s input width, dtype and device agree with the table;
  • the bag offsets form monotonic half-open ranges and exclude PAD as declared;
  • the continuous projector consumes floating features, never categorical addresses.

The same check rejects float IDs or another non-address dtype, an ID outside [0,V), a false contiguous-stride declaration, a local lookup split across undeclared devices, a bridge that does not consume the table width, bag offsets that do not delimit monotonic half-open ranges, and a continuous projector that receives categorical addresses. It proves the forward construction for these toy values; it says nothing about a production kernel’s speed, a distributed communication schedule, backward correctness, or the quality of the learned representation.


0x05 Table shape, training, PAD row, source/target tables

The embedding table has one row per vocabulary entry:

E: [V, d_model]

A batch of IDs selects rows:

input_ids: [B, L]
E[input_ids]: [B, L, d_model]

The table is usually trainable. Its rows are not a dictionary of fixed meanings: the row for cat becomes useful because the model is trained in contexts where that row helps to predict, classify, align or condition later computations.

There are four table details that cause real implementation bugs.

Vocabulary size

The tokenizer’s largest emitted ID must fit inside the table:

0 <= input_ids < V

If the tokenizer emits an ID outside the embedding table, the lookup fails. If the ID is in range but came from the wrong tokenizer, the lookup succeeds and retrieves the wrong learned row.

Source and target tables

Encoder-decoder code may use separate source and target vocabularies:

src_embed = Embeddings(d_model, src_vocab)
tgt_embed = Embeddings(d_model, tgt_vocab)

The shapes can look identical:

src: [B,S]
tgt: [B,T]

but the address spaces can differ:

E_src: [V_src,d_model]
E_tgt: [V_tgt,d_model]

Swapping the source and target embedding tables is a bug that no shape check catches: the integer tensor is still [B,L], and the rows come from the wrong address space.

PAD row

Padding adds rectangular shape:

input_ids:      [B,L_max]
attention_mask: [B,L_max]

The PAD token has an ID, and therefore a potential embedding row:

E[pad_id]: [d_model]

PyTorch’s padding_idx lets a specific row behave as padding in the embedding layer: the padding entry does not contribute gradient through the embedding module, and new embeddings initialize that row as zeros by default.

That is only one part of it. The PAD ID also has to agree with the attention masks, the loss masks, the label masks, the tokenizer’s conventions and the batching code. If one component thinks PAD is 0 and another thinks it is -1, the tensor shape can survive while lookup, masking, or supervision breaks.

A common LLaMA-style tokenizer convention is:

pad_id = -1

That value is metadata; it is not a valid row address for an ordinary nn.Embedding lookup, and the code has to replace, mask or otherwise handle it before the IDs reach the table.

Output vocabulary

The vocabulary dimension appears again at the output head:

hidden: [B,L,d_model]
logits: [B,L,V]

The input embedding table and the output head are related, and in some implementations they are the same object (tied weights); in others they are not. Tying the source embeddings, the target embeddings and the output projection only makes sense when their vocabularies agree, as 0x0A details.


0x05A Factorized embeddings: vocabulary width need not equal hidden width

The simplest Transformer chooses d_embed = d_model and has one table. This section and 0x0A write H for the hidden width d_model:

ALBERT makes a different choice. It first gathers a narrower row of width D (the article’s d_embed), then projects it into the hidden width H:

The factorization saves parameters when:

or equivalently:

For V=128,000, H=4096, and D=256:

direct table:
    128,000 * 4,096 = 524,288,000 parameters

factorized:
    128,000 * 256 + 256 * 4,096
    = 32,768,000 + 1,048,576
    = 33,816,576 parameters

parameter ratio:
    0.0645, about 15.5x smaller for this bridge

The saving is not free. Every token row passes through P, adding:

More importantly, all vocabulary rows enter hidden space through a D-dimensional bottleneck. ALBERT’s argument is that context-independent lexical identity may not require the full contextual hidden width. This is a modeling hypothesis and an architecture choice; nothing says that every model should factorize.

class FactorizedEmbedding(nn.Module):
    def __init__(self, vocab_size, embedding_dim, hidden_dim, padding_idx=None):
        super().__init__()
        self.lookup = nn.Embedding(
            vocab_size,
            embedding_dim,
            padding_idx=padding_idx,
        )
        self.bridge = nn.Linear(embedding_dim, hidden_dim, bias=False)

    def forward(self, input_ids):
        lexical = self.lookup(input_ids)  # [B,L,D]
        hidden = self.bridge(lexical)     # [B,L,H]
        return hidden

Factorization complicates naive weight tying. The input table is [V,D], while an ordinary output head expects [V,H]. A model can add an output bridge, tie only compatible factors, or keep the output head independent. That both are vocabulary matrices is not enough to make them one tensor.

0x05B Initial state may sum several address spaces

BERT-style inputs demonstrate another design: token identity, segment/type, and learned position each select a row of the same width, then are added:

BERT input construction from token, segment, and learned position embeddings

The sum is valid because every term has shape [B,L,H]. Addition preserves row count and hidden width. It also superposes the three sources, so downstream layers do not receive separate token/type/position channels.

The rigorous explanation is linear. Concatenate three one-hot selectors and a block-stacked parameter matrix:

Then:

No argument about “frequency bands” is needed: the model learns three row tables in a shared output space because their sum is what the next layer optimizes.

class BertStyleInitialState(nn.Module):
    def __init__(self, vocab_size, type_count, max_positions, hidden_dim):
        super().__init__()
        self.token = nn.Embedding(vocab_size, hidden_dim)
        self.token_type = nn.Embedding(type_count, hidden_dim)
        self.position = nn.Embedding(max_positions, hidden_dim)
        self.norm = nn.LayerNorm(hidden_dim)
        self.dropout = nn.Dropout(0.1)

    def forward(self, input_ids, token_type_ids, position_ids):
        x = (
            self.token(input_ids)
            + self.token_type(token_type_ids)
            + self.position(position_ids)
        )
        return self.dropout(self.norm(x))

This is a historical architecture example. M3.3 covers how position_ids are constructed and how modern alternatives inject geometry.

0x05C Training lifecycle of the input table

The table passes through distinct states:

  1. allocation, with one row per entry of the tokenizer’s vocabulary;
  2. initialization, or import of row values;
  3. joint training with the model objective;
  4. optionally freezing, factorizing, tying, sharding or quantizing;
  5. loading, with exact tokenizer and address compatibility;
  6. serving, with gathers under the runtime’s dtype and placement.

Random versus pretrained initialization

Random initialization is natural when the tokenizer and the model are trained together. Importing Word2Vec, GloVe or FastText rows is possible only when the two sides can be matched: the source embedding’s vocabulary to the model tokenizer’s vocabulary, the source’s word-level rows to the model’s word or subword rows, the source width d_source to the model width d_embed or d_model, and the source’s normalization to the model tokenizer’s normalization.

Exact vocabulary matches can copy rows. Partial matches need an initialization policy for missing rows. Word-level vectors do not directly define subword pieces; averaging characters or constituent rows is a heuristic.

def initialize_from_external(model_embedding, tokenizer, external):
    copied = 0
    with torch.no_grad():
        for token, token_id in tokenizer.vocab.items():
            if token in external and external[token].shape[-1] == model_embedding.embedding_dim:
                model_embedding.weight[token_id].copy_(external[token])
                copied += 1
    return copied

Report coverage and whether copied rows remain trainable. “Initialized from pretrained embeddings” without those details is not reproducible.

Row frequency and update opportunity

For input-side lookup, row v participates when ID v occurs. If corpus count is c_v, then the number of direct lookup-gradient contributions scales with c_v. High-frequency rows can dominate optimizer steps; rare rows may remain near initialization.

0x04A derives the exact local-count rule and shows why rank-local frequency scaling followed by data-parallel reduction is not the same as one global effective-batch count. This section adds the longer horizon: data sampling, tokenization, packing, gradient accumulation, world size, and output tying all affect how often a row receives an update.

Subsampling frequent words in classic Word2Vec and frequency-scaled embedding gradients are related responses to frequency imbalance, but they intervene at different layers: one changes training examples; the other changes gradient aggregation.

Freeze versus joint training

Freezing the input table keeps the imported geometry and removes the table’s optimizer state, but the frozen rows cannot adapt to rare or new pieces or align their scale to a new architecture. Training the table adapts it to the task and the model and lets the vocabulary specialize, at the price of full optimizer and checkpoint state and of a possible, sometimes catastrophic, drift away from the imported geometry.

In most modern language-model pretraining, the table is trained jointly. In transfer setups, freezing schedules and learning-rate multipliers are explicit hyperparameters.

Optimizer groups and weight decay

Embedding parameters can use a separate group:

optimizer = AdamW([
    {"params": dense_blocks, "lr": lr, "weight_decay": wd},
    {"params": [model.token_embedding.weight],
     "lr": embedding_lr,
     "weight_decay": embedding_wd},
])

Reasons include sparse-gradient compatibility, keeping the PAD row fixed, a pretrained initialization, and the different update frequency of the rows. There is no general rule on whether embeddings should receive weight decay; record the optimizer settings used for the checkpoint.

0x05D Growing the vocabulary: migrating the model state

When a tokenizer gains, loses or reorders addresses, which model tensors, optimizer states, distributed shards, release files and runtime routes have to change together, so that the preserved rows stay preserved and the new rows start from a stated and recorded state? “Add tokens and resize the embedding” describes only one local API call. A release migration crosses at least four kinds of state: the symbolic state (the ordered vocabulary, the normalizer, the pre-tokenizer, the special IDs, the template); the model state (input rows, output rows, output bias, aliases, factorization bridges); the training state (gradients, master weights, Adam moments, step counters, scheduler state); and the runtime state (tensor shards, quantized packs, the tokenizer/model routing, caches, the rollback pair).

M2.1 covers how a candidate vocabulary is fitted, evaluated and assigned addresses. This section starts from two fixed ordered vocabularies, old and new, and converts the model state row by row from one to the other. M3.8 covers the output distribution and decoding; M8 covers quantization and canaries in general. Output rows, quantized packs and canaries appear here only where the vocabulary’s identity makes them part of the migration.

Start by classifying the address change

Equal old and new vocabulary sizes do not imply compatibility. Before any tensor is allocated, the change has to be classified:

  • append-only: the old ordered vocabulary is an exact prefix of the new one, so every old row is reused at the same ID; what remains to check is that the old normalization, pieces, special roles and template are unchanged;
  • permutation or reindexing: the pieces may be identical but the IDs move; the rows are reusable through an explicit permutation, once every old piece and control role maps to exactly one new address;
  • removal or pruning: some old addresses disappear; the surviving rows are reused through an injective map, provided no retained dataset or session requires the removed IDs;
  • split: one old unit becomes several new units; no exact row exists for the new pieces, so an initializer and an adaptation policy are needed;
  • merge: several old units become one new unit; no unique exact source row exists, so a composition initializer and retraining evidence are needed;
  • replacement or joint vocabulary: many pieces and IDs change; only the overlapping rows are reusable, through a complete old-to-new overlap map, and the rest needs initialization.

Append-only is therefore a property to check; it is not enough that the new file contains the old strings. The check is:

V_new[0:V_old] == V_old
special_role_to_id_new == special_role_to_id_old
tokenizer_semantics_hash_new extends, rather than rewrites, the old contract

If one old ID moves, raw encoded datasets and persisted ID sequences no longer have the same meaning even though all tensor dimensions are valid.

The migration map separates exact copies from initialization

Let the old and new ordered vocabularies have sizes and . Define an exact-row map

where means new address has exactly the same symbolic meaning as old address . For an exact migration, each new row has at most one exact source and each preserved old row has at most one destination:

Define the preserved-row mask

For an old lexical table and explicit initializer rows , the new table is

Row-wise, this says exactly what the compact matrix notation can hide:

for new_id in range(V1):
    if exact_source[new_id] is not None:
        E1[new_id] = E0[exact_source[new_id]]
        row_status[new_id] = "exact_copy"
    else:
        E1[new_id] = initialize_new_row(new_id, policy, evidence)
        row_status[new_id] = "initialized"

A split, a merge, a decomposition average, a FOCUS combination or a semantic-neighbor copy belongs to initialize_new_row. It may be a good warm start, but it is not an exact edge of . Keeping the two records separate prevents an approximate guess from passing as an exact copy.

The same exact map applies to every vocabulary-indexed state:

For tied weights, and are one parameter: convert it once, then restore the alias, or the distributed replicas described in 0x0A.

New rows change every old probability

Suppose all old output rows and the context vector are unchanged. Their raw logits are then exactly preserved. Before expansion, the softmax denominator is

If new rows produce logits , their added mass is

Every old-token probability changes from to

The total probability assigned to new tokens is

and the KL divergence from the old distribution to the old coordinates of the expanded distribution is

This is why copying the old rows exactly does not leave the model’s behavior unchanged. The new rows enter the denominator immediately, before they have appeared in a prompt or target.

Hewitt’s vocabulary-expansion analysis derives the single-new-row form and motivates mean initialization. If every new output row is initialized to the mean old row

and the bias convention is compatible, then its logit is the mean old logit. By Jensen’s inequality,

For identical mean-initialized rows,

The bound holds for the initialization as stated; with covariance noise, different output biases, an untied input/output initialization, a changed hidden state or a full tokenizer replacement it no longer holds automatically and has to be re-derived, and it says nothing about downstream quality. A zero row is not neutral either: its dot-product logit is zero, so it contributes exp(0)=1, and if the trained old logits are all strongly negative, that mass can dominate.

Initializing the rows that have no exact source

Each policy for a row without an exact source uses different information and fails in its own way:

  • constructor-matched random uses the original model’s initializer and reproduces the convention of a fresh allocation; the new output mass can be too large, or the row norm mismatched;
  • zero uses no lexical prior and is deterministic and easy to audit; a zero logit can dominate a model whose logits are negative, and the new rows are all identical;
  • old mean, or mean and covariance, uses the global geometry of the old table and bounds the disturbance of the denominator under the mean assumptions above; covariance noise weakens the bound, and the global mean ignores the token’s meaning;
  • decomposition average uses the old tokenizer’s expansion of the new string and reuses pieces the model knows; several positions collapse into one static row, and their order is usually lost;
  • overlap or semantic combination uses shared pieces plus an auxiliary embedding space and suits tokenizer or language replacement; the auxiliary geometry and the overlap coverage become additional files to version with the checkpoint;
  • output-bias prior uses the desired initial token prior and controls the denominator mass directly; an overly negative bias can make the new rows too rare to learn;
  • exact row remap uses an identity proved by the old and new address maps and preserves one trained row exactly; it is invalid when the normalization, the boundaries or the control semantics changed.

FOCUS is one published alternative for vocabulary specialization: it represents target tokens using combinations of overlapping source/target tokens selected with semantic similarity in an auxiliary static embedding space. Its reported comparisons are specific to the paper’s multilingual-specialization setup; they do not make FOCUS a universal initializer. WECHSEL is another cross-lingual alternative. Both show why the record of an initializer has to name the code, the auxiliary model, the overlap set and the hyperparameters, and cannot just say “semantic initialization”.

Current Hugging Face Transformers exposes resize_token_embeddings(..., mean_resizing=True). The implementation at commit 85c307a184264643392ef37b6e902209812a6e23 allocates the new input rows, initializes them from the old mean and covariance when requested, resizes an untied language-model head separately, and calls tie_weights() after resizing. It handles the model tensors; the optimizer state, the datasets, the shards and the release remain to be migrated.

Architecture determines which vocabulary axes move

Which tensors have a vocabulary axis depends on the architecture, and the converter has to know it rather than guess from key names:

  • a direct tied decoder migrates one canonical [V,H] table and the output bias [V]; the Transformer trunk is unchanged;
  • a direct untied decoder migrates the input [V,H], the output [V,H] and the bias [V]; the trunk is unchanged;
  • a factorized lexical tie migrates the lexical [V,D] table and the bias [V]; the input bridge [D,H] and the output bridge [H,D] are unchanged unless the architecture changes;
  • a factorized input with a direct output migrates the lexical [V,D], the direct output [V,H] and the bias [V]; the input bridge [D,H] is unchanged;
  • a seq2seq target-only tie migrates the target lexical/output table and the target bias; the source table is unchanged when the source vocabulary is;
  • a compatible three-way tie migrates one joint source/target/output table and the target bias; the trunk is unchanged, and the tie holds only if all three roles share the same ordered map.

Resizing the bridge in a factorized model because V changed is a category error: the bridge does not have a vocabulary axis. Conversely, updating input rows while leaving an untied output head at produces a model that can read new IDs but cannot score them. Special IDs require their own semantic check. If PAD, BOS, EOS, or control IDs move, masks, templates, ignore-index rules, and runtime configuration migrate with them.

def migrate_vocabulary_state(old, spec):
    # Convert canonical logical tensors before creating physical aliases/shards.
    lexical = migrate_rows(old.lexical, spec.exact_map, spec.lexical_initializer)

    if spec.output_is_tied:
        output = lexical
    else:
        output = migrate_rows(old.output, spec.exact_map, spec.output_initializer)

    bias = migrate_vector(old.output_bias, spec.exact_map, spec.bias_initializer)

    model = construct_architecture(spec.new_config)
    model.load_canonical(lexical=lexical, output=output, output_bias=bias)
    model.restore_declared_aliases()
    assert_model_address_contract(model, spec)
    return model

Adam state migrates by row; its age usually does not

For Adam or AdamW, a vocabulary table commonly has first and second moments with the same logical shape as the parameter:

Under a zero-moment policy for new rows, migrate them as

The notation denotes the second moment, not vocabulary size. For an output bias, apply the same rule to vectors of length . Exact old rows retain their exact moment rows. New rows begin with zero moments unless a different warm start is chosen and checked.

At optimizer step , ignoring weight decay for the moment,

Many stock optimizers store one scalar step for the whole parameter, not one age per row. Preserving the old scalar step preserves old-row bias correction, but new rows inherit that large despite having zero moments. Resetting the whole parameter step makes new rows young by damaging the update convention for every old row. Per-row age requires a custom optimizer/state representation or separating new rows into a distinct parameter and reconciling that choice with lookup, tying, sharding, and checkpoint code.

def migrate_adam_table_state(old_state, exact_map, new_shape):
    exp_avg = zeros(new_shape, dtype=old_state.exp_avg.dtype)
    exp_avg_sq = zeros(new_shape, dtype=old_state.exp_avg_sq.dtype)
    for new_id, old_id in exact_map.items():
        exp_avg[new_id] = old_state.exp_avg[old_id]
        exp_avg_sq[new_id] = old_state.exp_avg_sq[old_id]
    return AdamState(
        exp_avg=exp_avg,
        exp_avg_sq=exp_avg_sq,
        step=old_state.step,  # parameter-level age, not a per-row claim
    )

PyTorch documents that optimizer state is keyed by parameter IDs and that load matches saved IDs to live parameters by zipping parameter-group order, without additional verification. Parameter names do not change this default behavior. If resized parameters differ from those in the saved optimizer, a custom register_load_state_dict_pre_hook must adapt the state dictionary before load. The official Optimizer.load_state_dict documentation also requires scheduler construction before optimizer-state load so loaded learning rates are not overwritten.

The safe order is therefore:

  1. construct the new model architecture;
  2. load or migrate the canonical model tensors;
  3. restore the tied aliases or the declared replicas;
  4. construct the optimizer over the final live Parameters;
  5. migrate the optimizer state by canonical parameter identity and row map;
  6. construct or load the scheduler in the order the framework documents;
  7. run one deterministic reconciliation step.

Loading optimizer state before re-tying can leave state attached to a stale parameter object. Registering both endpoints of a tie creates two moment sets for one logical parameter.

What freezing the old rows requires

A continued-training schedule may train everything (full continued pretraining), the new rows only, the new rows plus the output head, the new rows plus adapters, or the new rows first and then everything jointly.

For a tied decoder, zeroing only the sparse input-lookup gradient does not freeze the old rows. The output softmax generally contributes a dense gradient over the full vocabulary. Adam moments can also carry an old update forward, and AdamW’s decoupled weight decay can move a row even when its current gradient is zero. A real freeze of the old rows masks the combined gradient, prevents moment-driven updates and decay for those rows, and stays valid under sharding and aliasing. A separate parameter for the new rows simplifies the optimizer age but complicates the classifier and the checkpoint topology; each schedule has a cost.

Convert the logical state, then prove physical placement

Vocabulary migration and resharding are two transformations. The logical conversion turns the old ordered rows and the old optimizer state into the new ordered rows and the new state; the physical materialization turns the new logical tensors into TP/PP/DP shards, replicas, optimizer fragments and packs. The simplest auditable schedule converts a canonical logical tensor and then partitions it. A streaming converter is acceptable only if concatenating its outputs reproduces the same canonical result.

For tensor-parallel vocabulary shards, new intervals must form an exact cover:

Tied input and output roles have to use the same row intervals, and the output bias has to follow the same partition. Pipeline replicas have to receive the same migrated row shard, logical parameter ID, moments and step convention, and the same rule for reconciling gradients and updates, described in 0x0A.

Distributed optimizer formats add another compatibility axis. PyTorch’s distributed checkpoint state-dictionary APIs canonicalize optimizer parameter IDs to fully qualified names and can return state that is reshardable across supported parallelisms, but the API is documented as experimental. Megatron Core’s current distributed-checkpoint documentation distinguishes a faster dp_reshardable optimizer format, which does not permit arbitrary model-parallel changes, from a slower fully_reshardable format. It also documents version-specific legacy optimizer compatibility limits. Record the framework version and checkpoint format; do not infer reshardability from the word “distributed.”

Quantized or packed embedding and output tensors are derived from the high-precision state. The conservative order is to migrate the canonical high-precision logical state, then restore the aliases or replicas, then recalibrate or regenerate the quantized packs and their group metadata. Appending packed bytes directly is valid only when the group boundaries, the scale and zero-point state, the padding, the alignment, the row order and the loader’s expectations are all migrated explicitly; M8 covers how those packs are derived.

The four tokenizer/model pairs

Let T0/M0 be the active tokenizer/model pair and T1/M1 the candidate. T0 with M0 is the control: the original ordered addresses and rows agree. T0 with M1 is a compatibility test only: an append-only vocabulary preserves the old IDs, but continued training may still have changed the behavior. T1 with M0 is rejected: T1 may emit IDs outside M0, or attach a changed meaning to an old ID. T1 with M1 is the candidate, valid only after the checks below on the record of the migration, the tensors, the optimizer and runtime state, and the behavior.

An API receiving text can route the text to the tokenizer paired with the model. An API receiving pre-tokenized IDs has to require the tokenizer’s semantic revision and reject an incompatible pair. Persisted IDs without tokenizer provenance cannot be replayed safely after a migration.

A release records, together:

  • the old and new ordered-vocabulary digests;
  • the old-to-new exact row map and the record of the initializers;
  • the tokenizer semantics and the digests of the raw release files;
  • the model configuration and the digests of the canonical tensors;
  • the input/output/bias role map and the alias graph;
  • the optimizer format, the parameter identity map, the moments, the step and the scheduler state;
  • the TP/PP/DP shard and replica map;
  • the quantized-pack and calibration revision, when deployed;
  • the compatibility of the encoded datasets and the retokenization decision;
  • the identity of the runtime/model/tokenizer route;
  • the reference cases, the offline report, the canary record and the rollback target.

The tokenizer and the model advance together, as one pair that the router switches at once; M8.10’s release procedure has to keep that pairing.

From proposed change to active pair

A migration goes through these stages in order: the proposed change; the logical state converted; the shards and packs materialized; an offline mechanical audit; one training step reconciled; the version pair run in shadow; the pair on a canary; the ramp; the pair active.

Every live stage keeps a way back to the complete T0/M0 pair: the old tokenizer, model, runtime and configuration, and the capacity they need, stay available. Do not send a session from T1/M1 back to T0/M0 while reusing its token IDs, prefix-cache entries or K/V rows; reconstruct them from the source text or from another representation known to be compatible. M5 covers the cache mechanics; M8.10 covers traffic control and recovery-time objectives in general.

Vocabulary migration contract showing exact row mapping, new-row initialization and softmax mass, optimizer-state migration, distributed rematerialization, version-pair admission, and rollback

What to check before the new pair serves traffic

One perplexity number cannot approve the migration. The checks, in order, the mechanical ones first and the behavioral one last:

  • addresses: the old and new vocabulary digests, the uniqueness of the exact map, the semantics of the special IDs;
  • tensors: preserved rows bitwise equal, new rows finite, the expected shapes and dtypes;
  • classifier: old raw logits preserved where required, and the new probability mass measured;
  • optimizer: old moments and step preserved, the policy for the new state explicit, one update step reconciled;
  • ownership: aliases restored, the tensor-parallel cover exact, the pipeline replicas with their state and update rule valid;
  • files: the digests of the shards and quantized packs tied to the candidate pair;
  • behavior: regressions on old text, gains on the new domain, the behavior of special and control tokens, generation;
  • release: T1/M0 rejected, and T1/M1 admitted only with a warm, loadable T0/M0 to fall back on.

These rules can be checked on a toy append-only migration: deriving the softmax mass and the KL term, migrating direct, factorized and tied tensor roles with their Adam states, reconciling one deterministic update, reconstructing tensor-parallel shards, and evaluating the four tokenizer/model pairs. Such a check should reject maps that are shape-correct but semantically stale, moved special IDs, corrupted old rows or moments, a reset optimizer age, duplicate tied state, a resized factorized bridge, shard gaps and overlaps, stale packs, unsafe version pairs, missing rollback files and persisted IDs without a version. It proves the transformation on the toy values; it says nothing about tokenizer quality, loading in a production framework, collective ordering, quantized-kernel parity, downstream model quality or canary safety.

What the checkpoint records

The checkpoint records at least:

  • the tokenizer’s semantic and release hashes and the ordered vocabulary digest;
  • the embedding shape, dtype and factorization dimensions;
  • the PAD and control rows and the scale convention;
  • the weight-tying aliases, or the distributed replica topology;
  • the source/target sharing policy and the exact migration map;
  • the optimizer’s parameter identities, moment shapes, step and scheduler convention;
  • the sharding layout and the distributed-checkpoint format and version;
  • the quantization representation and calibration revision, if deployed;
  • the candidate version pair and the complete rollback version pair.

Some serialization formats do not preserve Python object aliases directly; load code may need to re-tie parameters after restoring values. Test the pointer identity of colocated ties, and the logical identity of replicas and updates for distributed ties, not only the equality of values.


0x06 Positional handoff: src_embed and tgt_embed are sequential

In the Harvard construction, the embedding module is wrapped with positional encoding:

src_embed = nn.Sequential(
    Embeddings(d_model, src_vocab),
    PositionalEncoding(d_model, dropout),
)

tgt_embed = nn.Sequential(
    Embeddings(d_model, tgt_vocab),
    PositionalEncoding(d_model, dropout),
)

So Embeddings(d_model, vocab)(x) and src_embed(x) are different operations: the first performs the content lookup and the scaling; the second performs the lookup, the scaling, the positional addition and the positional dropout.

Embedding module and positional encoding code path for turning token IDs into model-width vectors

This article covers the embedding half, input_ids -> learned rows -> [B,L,d_model]; M3.3 covers what comes next, the addition of position, layout or time information to those rows. The distinction matters because the shape does not change: it is [B,L,d_model] after the embedding and [B,L,d_model] after the positional encoding. A model can receive the correct rank while losing the position information, receiving it twice, or applying it at the wrong place.

Token IDs become token embeddings before positional encoding is added

This is why “the embedding output has shape [B,L,d_model]” is necessary but not sufficient: it says that the width is correct, and nothing about whether each row holds the right content row and position row, under the right mask, from the right source or target table.


0x07 Non-text features before a projector

The next three sections follow, for the shapes only, the second path of 0x01: inputs that are already vectors. X1.1 covers the choice of non-text units and their geometry; X1.2 covers encoders, projectors, resamplers and fusion; X1.3 covers multimodal packing, training and runtime state.

For non-text inputs, the path starts after a processor or an encoder has produced features specific to the modality, for example:

H_img:   [B, N_img,   d_vision]
H_doc:   [B, N_doc,   d_doc]
H_audio: [B, N_audio, d_audio]
H_video: [B, N_video, d_video]
H_event: [B, N_event, d_event]

These are already continuous features; no vocabulary assigns them an ID, so casting them to IDs is wrong:

bad_ids = image_features.long()
text_embedding(bad_ids)

This produces integer tensors, and it destroys the meaning of the visual features. The problem to solve is one of width:

vision encoder output width: d_vision
language model state width:  d_model

For example:

H_img: [B,N_img,1024]
LLM expects: [B,N,d_model=4096]

The projector bridge must convert:

[B,N_img,1024] -> [B,N_img,4096]

The projector does more than make the shape fit: it is the learned alignment between the feature space produced by one component and the state space consumed by another.


0x08 Projectors and adapters

The simplest count-preserving projector is a linear layer:

class MediaProjector(nn.Module):
    def __init__(self, d_media, d_model):
        super().__init__()
        self.proj = nn.Linear(d_media, d_model)

    def forward(self, h):
        return self.proj(h)

The shape trace is:

h:          [B,n_media,d_media]
proj.weight implementation storage: [d_model,d_media]
output:     [B,n_media,d_model]

Conceptually:

where:

and:

The count is preserved:

n_media in
n_media out

This covers the common “project visual features into language embedding width” interface. LLaVA-style systems use this kind of connector idea: visual features from a vision encoder are mapped into the language model’s embedding space so they can be consumed as language-compatible rows.

Count-changing adapters

Some adapters change both width and row count:

H_media: [B,n_media,d_media]
    -> adapter / resampler / query bottleneck
Z_media: [B,r,d_model]

Here:

r != n_media

That choice changes how many rows the later attention layers see. A query bottleneck can compress hundreds or thousands of visual patch features into a fixed number of learned-query outputs; BLIP-2’s Q-Former is an example of this kind of bridge between a frozen image encoder and a frozen language model.

For the shapes, four kinds of adapter matter: a linear projector preserves the row count and changes the width; an MLP projector does the same with more capacity; a pooling or resampling adapter changes both the row count and the width; a query bottleneck extracts r rows from a larger feature set.

The downstream risk is immediate. If an adapter changes:

[B,n,d] -> [B,r,d_model]

then masks, row metadata, labels, and geometry tensors must follow r, not the old n.


0x09 Assembling X0 from several sources

Once all branches have width d_model, they can be assembled along the sequence or unit axis:

X0 = torch.cat(
    [
        image_states,   # [B, N_img, d_model]
        text_states,    # [B, L_text, d_model]
        event_states,   # [B, N_event, d_model]
    ],
    dim=1,
)

The result is:

X0: [B, N_total, d_model]
N_total = N_img + L_text + N_event

The concatenation axis is the row axis. Concatenating along the feature axis would produce a different object:

wrong:
    [B,n,d_model] + [B,n,d_model] -> [B,n,2*d_model]

That may be useful in some architectures, but it is not the usual “append media rows before text rows” context construction.

Equal width is not enough for a state assembled from several sources. The row order matters because prompt templates and training data expect a particular order; the row type matters because image, text, event, PAD and tool rows may follow different conventions; the masks matter because ragged media and text batches need correct visibility and padding masks; the geometry metadata has to stay attached to its rows (X1 aligns layout and time metadata; M3.3 to M3.5 handle the language positions); and the labels matter because M3.9 decides which rows are supervised and which are ignored.

This section stops at width alignment and assembly. X1.1 covers non-text geometry, X1.2 the fusion of several sources, and X1.3 multimodal packing and runtime state; M3.9 covers training labels and masks, and M3.10 single-request inference.

The question to ask when debugging is whether row 17 still corresponds to the intended token, patch, span, event or PAD row. If it does not, [B,N_total,d_model] is only a convincing shape.


0x0A Weight tying: the algebra, the storage and the updates

Embedding lookup and the vocabulary classifier sit at the two ends of the model: at the input, token ID v selects the row E[v,:], a state of hidden width; at the output, a state of hidden width produces one score per vocabulary row. Their layouts in the framework can match:

token_embedding.weight: [V,H]
lm_head.weight:         [V,H]

but equal shape is only the first condition. Four independent questions follow, and their answers have to hold before and after the model is saved and loaded: whether row v names the same token in every role (semantic identity); whether each role consumes the same [V,H] orientation of the parameter (algebraic compatibility); whether there is one Parameter, or declared synchronized replicas (physical realization); and where all gradient contributions are combined, the optimizer state is stored and the authoritative update is applied (update ownership).

M3.8 covers the output head’s scores, the cross-entropy loss and decoding; M4 covers the cost of collectives; M8 covers quantization and packed kernels. This section keeps what is needed to show that the shared table remains one logical parameter.

What the papers claim

Weight tying entered language modeling through related but distinct arguments; “sharing saves parameters” is only one of them.

Press and Wolf treat the topmost classifier matrix as an output embedding, analyze its row updates, and set the input and output embeddings equal; they also study tying the decoder’s input and output, and a three-way tying for translation. Their update analysis distinguishes neural language models from skip-gram, and the translation variants require compatible source and target subword identities. The results are the paper’s measurements; they do not prove that tying always helps.

Inan, Khosravi, and Socher start from an augmented target distribution informed by word-vector similarity, show why the classifier and input-embedding subspaces approach one another under stated assumptions, then evaluate explicit embedding reuse. The theoretical section assumes equal input and hidden widths and removes the output bias for the derivation; the augmented loss and the hard parameter reuse are separable interventions.

Attention Is All You Need shares compatible encoder embedding, decoder embedding and pre-softmax weights, and multiplies the embedding-role outputs by . This is three-role reuse under the paper’s vocabulary setup; the role-specific input scale does not create another parameter copy.

ALBERT factors the vocabulary width away from the hidden width, then uses a hidden-to-embedding decoder path before the vocabulary classification. Direct [V,H] tying is impossible when the lexical rows are [V,D] with ; only the compatible lexical classifier factor can be shared.

Press and Wolf’s neural-language-model observation is especially useful for understanding the gradient: an input-only table updates rows selected by the current batch, whereas the ordinary output softmax gives every vocabulary row an update. Their tied row therefore evolves under both roles. The paper also warns, through its skip-gram analysis, that the same tying argument should not be transported into every embedding objective without re-derivation.

The original Transformer-era diagram is a compact intuition: one stored matrix is read by lookup and transposed by the output linear operation.

Input embedding and output projection sharing one transposed parameter matrix

The diagram shows only the idea; vocabulary identity, pointer identity, factorization compatibility and distributed synchronization are the rest of this section.

Deriving the two-path gradient from one shared parameter

Flatten all supervised output positions into rows. Let:

S: [M,V]       one-hot selector for M input positions
E: [V,H]       shared token table
G_X: [M,H]     gradient arriving at gathered input states
C: [N,H]       final contextual rows presented to the classifier
Y: [N,V]       target distributions, usually one-hot
b: [V]         optional untied output bias

The input and output uses are:

For row-wise cross entropy,

The log-softmax derivative gives the logit residual:

Now differentiate the classifier . Using :

Reordering each trace to place the differential last yields:

The backward section derived the transpose of lookup:

Because both graph edges terminate at the same parameter object, autograd must accumulate:

The row-level form shows exactly why tying destroys input-only sparsity:

The first sum is empty for vocabulary rows absent from the input. The second sum is generally nonzero for every row because softmax assigns probability to every finite candidate. An output bias remains a separate [V] parameter and does not become tied merely because the classifier weight does.

If the input role multiplies gathered rows by a scalar , as in the original Transformer’s convention, the input contribution becomes . The output contribution remains unless the output operation declares its own scale. One parameter can participate in differently scaled operations without becoming two parameters.

A two-position tensor trace

Use V=4, H=3, input IDs [1,3,1], and the following upstream input rows:

G_X = [[1,0,1],
       [0,2,1],
       [2,1,0]]

The input contribution is:

row 0: [0,0,0]
row 1: [3,1,1]
row 2: [0,0,0]
row 3: [0,2,1]

For two classifier rows, choose:

C = [[1,2,-1],
     [0,1, 2]]

D = P-Y
  = [[ 0.1,-0.4, 0.2, 0.1],
     [-0.2, 0.1,-0.3, 0.4]]

Each row of D sums to zero, as a softmax-cross-entropy residual should. The output contribution D.T @ C is:

row 0: [ 0.1, 0.0,-0.5]
row 1: [-0.4,-0.7, 0.6]
row 2: [ 0.2, 0.1,-0.8]
row 3: [ 0.1, 0.6, 0.7]

The tied total is therefore:

row 0: [0.1,0.0,-0.5]   # absent from input, still updated by output
row 1: [2.6,0.3, 1.6]
row 2: [0.2,0.1,-0.8]   # absent from input, still updated by output
row 3: [0.1,2.6, 1.7]

The trace also shows what the optimizer has to accept: a sparse-only update path cannot consume the complete tied gradient without densifying it, or without a mathematically equivalent classifier implementation that emits its gradient in a form the sparse path accepts.

Direct and factorized tying

For a direct table :

untied input plus output weights:  2*V*H
tied input/output weight:             V*H

The familiar saving is one matrix:

excluding optional output bias and optimizer state.

Now let the lexical width be , as in the factorized table of 0x05A:

An ordinary direct output matrix is [V,H] and cannot alias A. A compatible factorized classifier first maps contextual rows back to lexical width:

The lexical table then receives:

and the output bridge receives:

This is the shape pattern used by ALBERT’s masked-LM head: hidden states are mapped from hidden width to embedding width before the decoder whose [V,D] weight is tied to the lexical table. The input bridge and output bridge are separate learned matrices in that implementation. Requiring is another, stronger architecture constraint; it is not implied by lexical-table tying.

Ignoring biases, normalization and activations, the parameter counts are:

ArchitectureWeight parametersDirect alias legal?
direct input + direct output, untiedno alias declared
direct input/output tiedyes, same [V,H] table
factorized input + direct [V,H] outputlexical/output shapes differ
factorized lexical decoder tied, separate input/output bridgestie [V,D] lexical classifier only
factorized lexical decoder plus transposed shared bridgeonly under the additional bridge-sharing contract

For V=128,000, H=4096, and D=256:

direct untied:                         1,048,576,000
direct tied:                             524,288,000
factorized input + direct output:         558,104,576
factorized lexical-tied, two bridges:      34,865,152
factorized lexical + shared bridge:        33,816,576

The compute changes too. For M gathered input rows and N classifier rows:

direct output classifier:       N*V*H MACs
factorized input bridge:        M*D*H MACs
factorized output bridge:       N*H*D MACs
factorized output classifier:   N*V*D MACs

These are logical dense MACs. Fused losses, vocabulary parallelism, sampled or adaptive classifiers, and kernel packing change execution without changing the declared parameter graph.

Which tables may be tied

Whether two tables may be tied depends first on what their rows mean, then on their shapes:

  • decoder input and decoder output: the same ordered target vocabulary and a compatible stored width;
  • encoder input and decoder input: the same ordered joint vocabulary, and not merely an equal row count;
  • encoder input, decoder input and output: all three roles with the same row identity; Press and Wolf’s three-way tying used a union source/target vocabulary;
  • token table and type or position table: invalid, because the rows belong to different address spaces even when the widths match;
  • hashed bucket table and vocabulary output: invalid as a direct alias when many tokens share a bucket and the classifier still needs one logit row per token; a decomposed classifier would be another architecture;
  • imported frozen table and trainable output: tying would also freeze, or jointly train, the classifier, and that change of training policy has to be explicit;
  • factorized [V,D] input and direct [V,H] output: invalid for ; insert a compatible output bridge, or keep the head untied.

Equal V_src and V_tgt do not prove row compatibility. A permutation of the target vocabulary preserves every shape and makes three-way tying semantically wrong.

Colocated implementation: one object, one gradient, one optimizer state

A minimal direct tie assigns the Parameter reference, preferably before constructing the optimizer:

class DirectTiedModel(nn.Module):
    def __init__(self, vocab_size, hidden_size):
        super().__init__()
        self.token_embedding = nn.Embedding(vocab_size, hidden_size)
        self.lm_head = nn.Linear(hidden_size, vocab_size, bias=False)
        self.lm_head.weight = self.token_embedding.weight

    def embed(self, input_ids):
        return self.token_embedding(input_ids)

    def project(self, hidden):
        return F.linear(hidden, self.token_embedding.weight)

After construction, the test checks that both names refer to one object and one storage; equal values are not enough:

left = model.token_embedding.weight
right = model.lm_head.weight

assert left is right
assert left.untyped_storage().data_ptr() == \
       right.untyped_storage().data_ptr()
assert left.storage_offset() == right.storage_offset()
assert left.shape == right.shape
assert left.stride() == right.stride()

data.copy_(...), equal tensor hashes, and two Parameters that happen to share initial values all fail the colocated tying contract. They can acquire separate gradients, separate optimizer states, and separate updates.

The optimizer is constructed after the aliases are in place, and it registers the shared parameter once:

params = list(model.parameters())
assert len({id(p) for p in params}) == len(params)

optimizer = AdamW(params, ...)
assert optimizer_registers_once(model.token_embedding.weight, optimizer)

Replacing lm_head.weight after optimizer construction can leave the optimizer holding the old Parameter. A valid restore order is:

  1. construct the architecture and the alias map;
  2. load or assign the checkpoint values;
  3. re-establish the requested aliases;
  4. verify object and storage identity;
  5. construct the optimizer and restore one logical optimizer state;
  6. run one two-path gradient and update as a probe.

Restoring the alias after loading

PyTorch documents that Module.state_dict() is a shallow mapping containing references to module parameters and buffers. torch.save() preserves tensor storage sharing in the serialized Python object. Those facts do not mean that load_state_dict() will redesign an independently constructed module into a tied one: the usual load path copies checkpoint values into the Parameter objects already registered by the model.

The checkpoint therefore needs both the data and the topology: one canonical logical tensor (token_table.weight); an alias map (lm_head.weight -> token_table.weight); what the alias presupposes (the ordered vocabulary hash, the shape, the dtype, the factorization, the shard map); and, after loading, the observation that the alias or storage identity holds, or that the declared synchronized replicas exist.

If a checkpoint exposes both names, validate their values before choosing one canonical tensor. Two present alias keys with different values are not a minor serialization detail; they describe an untied or corrupted state and need an explicit conversion policy.

The current Transformers source makes the topology model-aware through a {target: source} tied-key mapping gated by tie_word_embeddings. Its load path can use the present side when the other key is absent, checks equality when both are present, and assigns the target attribute to the source Parameter. The exact behavior is version-scoped; the invariant here is the explicit mapping plus post-load identity verification.

Safetensors deliberately does not encode arbitrary PyTorch shared-storage graphs. Its official save_model/load_model helpers are model-aware, can drop duplicate names, and document that saved metadata is not sufficient to recover an arbitrary shared structure by itself. A plain tensor-name loader therefore cannot be the sole owner of alias restoration.

def restore_tied_checkpoint(model, tensors, alias_map):
    validate_vocab_shapes_and_shards(model, tensors)
    reject_divergent_present_alias_values(tensors, alias_map)
    model.load_state_dict(tensors, strict=False)
    apply_alias_map(model, alias_map)
    verify_alias_graph(model, alias_map)
    return model

PyTorch’s load_state_dict(assign=True) changes which tensor properties are preserved and, as documented, requires the optimizer to be constructed after loading. Treat it as a separate restore mode and run the same alias check after it; assign=True does not repair an alias that was never declared.

Conversion is an architecture migration

Each change of tying mode has its own procedure:

  • from tied to untied: clone the canonical tensor into a new output Parameter, create separate optimizer state, and record that future updates may diverge;
  • from untied to tied: choose a canonical value or a merge rule deliberately and validate the change in quality; equality at one instant does not justify discarding one trained matrix silently;
  • from direct tied to factorized tied: define the lexical width, the input and output bridges, and a conversion or retraining procedure; in general a reshape cannot preserve the original classifier exactly;
  • from one vocabulary to a joint three-way vocabulary: build an explicit row mapping, initialize the new rows, migrate the output bias and the optimizer state, and update the tokenizer and checkpoint identity together;
  • from a native tie to separately quantized input and output packs: keep one logical source tensor and record the packs derived for each role, or declare that the runtime unties them; two independent scales are not one mutable training parameter.

0x05D covers vocabulary migration and release in full; the point here is that a change of tying mode cannot hide inside an ordinary checkpoint load.

Tensor-parallel output ownership

With vocabulary-row tensor parallelism, rank r owns:

The masked-local input lookup from section 0x04A reconstructs hidden rows from the owner of each token. The same local shard can produce local classifier scores:

The system may all-gather the Z_r blocks for full logits, or use a vocabulary-parallel cross entropy that computes global normalization and target terms without materializing [N,V] on every rank. M3.8 covers the scores and the loss. For tying, the requirement is narrower: the input row interval on rank r equals the output row interval on rank r; when colocated, the local input and output roles reference one local shard; the output bias uses the same vocabulary partition; and the checkpoint’s row order reconstructs the same global table.

If input and output partitions differ, equal global values are insufficient; the runtime needs a declared reshard/remapping step and the checkpoint cannot label the local storages as direct aliases.

Pipeline-parallel tying with synchronized replicas

The first pipeline stage performs the input lookup while the last stage performs the output projection. Different processes cannot share one Python Parameter pointer. A valid logical tie keeps two physical replicas per tensor-parallel row shard, E_r^(in) on the first stage and E_r^(out) on the last. They start equal; their gradients are reconciled, g_r = g_r^(input) + g_r^(output); and both replicas apply the same update from equal optimizer state, or one authority steps and broadcasts the new value.

The pinned Megatron-Core implementation makes this exception explicit. With pipeline parallelism it creates a last-stage copy, initializes first/last-stage values through an embedding-group all-reduce, marks the copies as shared, and requires their gradients to be reduced before the update. Its sharded state dictionary maps the last-stage output copy to the first-stage embedding’s logical checkpoint key with a replica identifier.

For each row shard, the reconciliation equation is:

If every replica begins with the same value and optimizer state and consumes the same reconciled gradient, deterministic identical updates preserve equality. A mere periodic value copy is weaker: independent optimizer moments can make replicas diverge again at the next step.

The two realizations are verified differently. A colocated tie holds when the two roles reference the same Parameter object and the same storage. A cross-stage logical tie holds when both replicas carry the same logical parameter ID and the same tensor-parallel row interval, and the replica group, the gradient reconciliation and the optimizer authority are all declared. Calling both “equal tensors” erases the distinction.

Weight tying contract showing two-path gradient accumulation, direct and factorized classifier variants, colocated storage aliases, checkpoint restoration, and synchronized pipeline replicas

Checking the tying rules on toy tensors

A check of these rules on toy tensors confirms four things: that the two-path gradient satisfies dE_tied == dE_input + dE_output; that the direct and factorized parameter and MAC formulas give consistent numbers; that in a colocated restore equal copies fail the identity test while one object and storage alias passes; and that in a distributed restore the tensor-parallel shards reconstruct the logical table, and the pipeline replicas stay equal only after the gradients and the optimizer state are reconciled.

The same check compares direct untied, direct tied, factorized untied-output, factorized lexical-tied, target-only seq2seq tying and compatible three-way tying, and rejects row-order mismatches, shape-only ties, divergent duplicate keys, missing alias maps, duplicated optimizer registration, stale optimizer references, incompatible factorization, shard gaps and overlaps, input/output partition mismatches, unsynchronized pipeline gradients, divergent replica optimizer state, and tied claims over independently quantized mutable copies. It proves the algebra and the declared ownership on toy values; it says nothing about framework autograd, NCCL ordering, production checkpoint conversion, or model quality after the architecture changes.

0x0A1 Memory, compute and placement of the table

For a dense trainable table with V rows, width H, and b_w bytes per stored weight:

Mixed-precision Adam training may additionally hold a master weight and two optimizer moments. A rough count:

forward weight, bf16:       2 * V * H bytes
master weight, fp32:        4 * V * H bytes
first moment, fp32:         4 * V * H bytes
second moment, fp32:        4 * V * H bytes
gradient, implementation:   dense or sparse policy-dependent

This can make a “simple lookup table” expensive during training. At inference, the logical arithmetic per selected row is tiny, but memory access is irregular and table residency matters. Repeated IDs may benefit from cache locality; large distributed vocabularies require ownership and communication.

Rare rows create an optimization problem. If row v occurs c_v times in the training corpus, its input-side gradient evidence is proportional to those occurrences, while an untied output head still sees vocabulary-wide softmax gradients. Undertrained-token audits inspect frequency, row norms, output probability pathologies, and tokenization neighborhoods rather than assuming every allocated row learned equally well.

Padding and regularization interaction

padding_idx suppresses ordinary embedding-gradient updates for the PAD row, but global optimizer or regularization logic can still matter. Decoupled weight decay applied blindly to all dense parameters may move a supposedly fixed row. Models that require a zero PAD row can enforce it after the optimizer step, or exclude the row or the parameter from decay, as their implementation requires.

@torch.no_grad()
def enforce_padding_row(embedding, pad_id):
    if pad_id is not None:
        embedding.weight[pad_id].zero_()

Do not add this hook to a checkpoint that intentionally learned a nonzero PAD row. The invariant comes from the model definition.

Parameter counts, arithmetic and placement

For a text table E: [V,d_model]:

Lookup returns rows, so its logical output contains elements. It is a gather, not the dense multiplication by a materialized one-hot matrix used in the conceptual proof. At V=32,000 and d_model=4096, the table has 131,072,000 parameters and occupies 250 MiB at two bytes per parameter.

For a linear media projector from d_media to d_model:

With B=1, n_media=576, d_media=1024, and d_model=4096:

projector parameters: 4,194,304 = 8 MiB at 2 bytes/parameter
projector MACs:       2,415,919,104
projected states:     2,359,296 elements = 4.5 MiB at 2 bytes/element

A two-layer projector replaces the parameter term with d_media*d_hidden + d_hidden*d_model and materializes an intermediate [B,n_media,d_hidden]. Count-changing resamplers add a separate row-reduction contract; width matching alone does not explain their cost or information loss.

Placement matters because these are boundary tensors. A vocabulary-sharded embedding must map global token IDs to the owning shard and combine the lookup result according to its sharding scheme. One implementation may mask non-local IDs, perform local lookup, and all-reduce hidden outputs; another may route IDs to owners. It does not necessarily gather full table rows. A vision encoder and language model on different devices must transfer [B,n_media,d_media] or the projected [B,n_media,d_model], depending on where the projector is placed. Moving the projector changes the transfer width and the compute placement without changing the final shape. A device/dtype conversion that silently moves the tensor through host memory can dominate a small projector even though every shape is correct.


0x0B Shape reference

Use this as the debugging table for the whole article.

ObjectShapeSource or note
text token IDs[B,L_text]M2.1 output / M2.2 input
source IDs[B,S]data path / encoder input
target IDs[B,T]data path / decoder input
embedding table E[V,d_model]M2.2
source embedding table[V_src,d_model]may differ from target
target embedding table[V_tgt,d_model]decoder input table
PAD row[d_model]row at pad_id if valid
text embeddings[B,L_text,d_model]E[input_ids]
source content embeddings[B,S,d_model]before PE if only Embeddings
target content embeddings[B,T,d_model]before PE if only Embeddings
full src_embed(src)[B,S,d_model]embedding plus PE in Harvard code
full tgt_embed(tgt)[B,T,d_model]embedding plus PE in Harvard code
PE buffer[1,max_len,d_model]M3.3 handoff
media features H_media[B,n_media,d_media]X1 encoder output
image features H_img[B,N_img,d_vision]vision encoder output
audio features H_audio[B,N_audio,d_audio]audio encoder output
document features H_doc[B,N_doc,d_doc]document processor output
projector conceptual weight W_p[d_media,d_model]framework may store transpose
projected media states Z_media[B,n_media,d_model]projector output, X1
count-changing adapter output[B,r,d_model]row count changed
row-type metadata[B,N_total] or side metadatamust align to rows
mixed state sequence X0[B,N_total,d_model]assembled input, X1
output head weight[V,d_model]0x0A and M3.8
logits / log-probs[B,L,V]M3.8 and M3.10

The pattern through the whole table: a correct last dimension is necessary, and so is a correct row identity. Many bugs preserve the first and break the second.


0x0C Tests for the embedding layer

Small tests can prove the algebra independently of a full training run.

Lookup equals one-hot multiplication

def test_lookup_matches_one_hot():
    torch.manual_seed(0)
    V, H = 11, 5
    ids = torch.tensor([[2, 7, 2], [0, 10, 4]])
    weight = torch.randn(V, H)

    gathered = F.embedding(ids, weight)
    selected = F.one_hot(ids, num_classes=V).to(weight.dtype) @ weight

    torch.testing.assert_close(gathered, selected)

This proves the forward equivalence on the test case; 0x04 explains why the one-hot tensor is still not materialized in production.

Repeated IDs accumulate gradients

def test_repeated_ids_scatter_add():
    embedding = nn.Embedding(8, 3)
    ids = torch.tensor([4, 2, 4])
    weights = torch.tensor([1.0, 1.0, 2.0]).unsqueeze(-1)

    loss = (embedding(ids) * weights).sum()
    loss.backward()

    torch.testing.assert_close(
        embedding.weight.grad[4],
        torch.full((3,), 3.0),
    )
    torch.testing.assert_close(
        embedding.weight.grad[2],
        torch.full((3,), 1.0),
    )

Padding, bounds, dtype, and tying

def assert_initial_state_contract(model, tokenizer, batch):
    ids = batch["input_ids"]
    assert ids.dtype in (torch.int32, torch.int64)
    assert ids.min().item() >= 0
    assert ids.max().item() < model.token_embedding.num_embeddings
    assert tokenizer.fingerprint == model.config.tokenizer_hash

    x = model.token_embedding(ids)
    assert x.shape == (*ids.shape, model.config.embedding_dim)
    assert torch.isfinite(x).all()

    if model.config.padding_idx is not None:
        pad = model.config.padding_idx
        pad_positions = ids == pad
        if pad_positions.any() and model.config.zero_pad_row:
            torch.testing.assert_close(
                x[pad_positions],
                torch.zeros_like(x[pad_positions]),
            )

    if model.config.tie_word_embeddings:
        assert model.token_embedding.weight.data_ptr() == \
               model.lm_head.weight.data_ptr()

Scale and factorization checks

def test_harvard_scaling(wrapper):
    ids = torch.tensor([[1, 3]])
    raw = wrapper.lut(ids)
    scaled = wrapper(ids)
    torch.testing.assert_close(scaled, raw * math.sqrt(wrapper.d_model))


def test_factorized_shape(module):
    ids = torch.tensor([[1, 2, 3], [4, 5, 6]])
    lexical = module.lookup(ids)
    hidden = module(ids)
    assert lexical.shape == (2, 3, module.lookup.embedding_dim)
    assert hidden.shape == (2, 3, module.bridge.out_features)

Checkpoint tests should also verify the vocabulary row count, the tokenizer hash, the table dtype, the sharding metadata, the PAD policy, the factorization dimensions and the actual aliasing of tied parameters. Each of these belongs in a test that runs before a release rather than in a code comment.

0x0D Failure lab

These are practical bugs in which the tensor rank survives while the meaning, identity or update path of the rows breaks. Each bold line names one failure; the sentences under it say what goes wrong and, where there is one, the check that catches it.

Release and table-identity bugs

One release hash used as every kind of identity.

Resharding changes the saved files without necessarily changing the logical tensor; changing the row order can preserve the shape while changing the meaning. Keep the identities of the address space, the logical table, the checkpoint and the saved files separate.

Equal vocabulary size taken as address compatibility.

Two tokenizers can have the same V and different ID-to-piece assignments. Store the tokenizer’s semantic hash and ordered vocabulary digest with the table and check them at load time.

Tied weights accepted from equal values.

Two independent tensors can compare equal at load time and diverge on the next update. Verify shared storage after materialization.

Shard map accepted from local shapes alone.

Overlapping intervals duplicate owners; gaps make rows unreachable. Require an exact, non-overlapping cover of [0,V).

ID and embedding bugs

Token IDs treated as numeric magnitudes.
ID 9000 is not semantically larger than ID 42. Both are table addresses.

Strings passed into nn.Embedding.
The layer expects integer indices, not token strings.

One-hot vectors passed into nn.Embedding.
One-hot is a conceptual explanation for one_hot @ E. The implementation expects IDs.

Already embedded floats passed into nn.Embedding.
The shape may look sequence-like, but embedding lookup is row indexing. It is not a generic projection layer.

Media features cast to IDs.
Converting [B,n,d_media] floats to integers and using a text embedding table destroys continuous feature meaning.

Vocabulary and table bugs

Tokenizer vocabulary and embedding row count mismatch.
The tokenizer emits IDs outside [0,V-1], or the model has rows the tokenizer never emits.

Tokenizer/model mismatch.
An ID is in range but addresses a row trained for a different token.

Source and target embedding tables swapped.
Both tensors may be [B,L]; the address space is wrong.

Shared embedding assumed when the implementation uses separate tables.
Parameter tying and checkpoint loading can silently become invalid assumptions.

Target Generator initialized with V_src.
This works only when source and target vocabularies are actually compatible.

A reordered vocabulary is called append-only.

Every tensor shape is valid, but old ID v now names a different token. Check that the complete old ordered vocabulary is an exact prefix and that the special roles keep their IDs.

An approximate initializer is recorded as an exact row copy.

A decomposition average or a semantic neighbor can be useful, but it does not preserve one trained row’s meaning. Keep the exact-map edges separate from the record of how each new row was initialized.

Old raw logits are preserved, so old probabilities are assumed preserved.

New output rows add A to the softmax denominator and scale every old probability by Z/(Z+A). Measure new-token mass and the resulting KL term.

The embedding grows but the untied output head or bias does not.

The model can read the new ID but cannot score it, or the classifier has a misaligned vocabulary axis. Migrate every tensor that has a vocabulary axis.

Adam moments are resized but the step is reset.

The new shape loads, but old rows use a different bias-correction convention. Preserve parameter age or declare a custom row-age design; do not reset the whole table to make only the new rows young.

Only the sparse lookup gradient is masked to freeze old tied rows.

Dense output gradients, existing moments, or decoupled weight decay still move the rows. Freeze the combined update path, not one gradient producer.

Physical shards are edited independently without a canonical reconstruction.

Local files can all pass shape checks while the row order, the moments or the tied intervals diverge. Convert the logical state first, then check the shard cover and the reconstruction, or check an equivalent streaming transformation.

Quantized bytes are appended without regenerating group metadata.

Group boundaries, scales, padding, packing or alignment can become stale. Migrate the canonical state and regenerate the packed files, unless the conversion of the packed state is checked on its own.

T1/M0 is accepted because most IDs are still in range.

One new or semantically changed ID is enough to corrupt the lookup and the output meaning. Route the tokenizer and the model together, as one approved version pair.

Rollback restores M0 while retaining T1 IDs or candidate cache state.

The process is live but conditions on foreign addresses or K/V rows. Restore the complete old tuple and reconstruct state from compatible source data.

PAD bugs

PAD ID, padding_idx, attention mask, and label mask disagree.
Lookup runs, but PAD rows may be updated, attended to, or supervised incorrectly.

pad_id=-1 passed into embedding lookup.
-1 may be tokenizer metadata, but ordinary embedding lookup expects valid nonnegative row IDs.

PAD row updates unexpectedly.
If padding_idx is not set or the wrong ID is used, PAD can train like content.

PAD row frozen when intended as content.
The reverse bug: padding_idx can freeze a row that another component treats as a real token.

Backward and distributed bugs

Duplicate IDs overwrite instead of accumulate.

Assignment to dE[id] retains only one occurrence. The backward operation is scatter-add, or an equivalent sorted/segmented reduction.

Frequency scaling uses an undeclared count scope.

Rank-local counts, global effective-batch counts, and accumulation-window counts produce different updates. Record the scope and reduction convention.

Sparse layout is confused with sparse values.

A mostly-zero dense tensor is not a sparse-layout gradient, and an uncoalesced sparse tensor can contain duplicate row indices. The optimizer check has to look at the layout and at whether the tensor is coalesced.

An optimizer’s name is taken as proof that sparse gradients work.

The device, weight decay, momentum or fused options, clipping and the gradient layout can all break an optimizer that is listed as supported.

Local clipping is called global clipping.

Each owner clips with its local norm, so the global sharded gradient exceeds the declared threshold. Reduce the norm statistic across owners before scaling.

Tied output gradient is dropped to preserve input sparsity.

The lookup path can be sparse while the vocabulary-wide output path is dense. The shared parameter must receive both contributions under one agreed gradient layout.

Data-parallel AVG and loss averaging divide twice.

The gradient is scaled by an unintended extra world-size factor. Freeze loss, microbatch, accumulation, and collective conventions together.

Row-shard intervals contain a gap or overlap.

A valid global ID has no owner or two owners. Validate exact coverage of [0,V) before forward.

Global IDs index a local shard directly.

The lookup is in bounds for some IDs but addresses the wrong row. Subtract the owner’s shard start only after checking that this rank owns the row.

Origin-position metadata is lost during routing.

Correct rows return in expert/owner order rather than sequence order. Preserve origin rank and flattened position through both collectives.

A non-owner rank steps a row shard.

Forward reconstruction can be correct while the optimizer state diverges. The configuration has to say which rank owns each row shard and which rank owns its optimizer state.

Column-wise weight placement is mistaken for a full activation schedule.

The next operator requires a full hidden row, but no concatenate/all-gather or compatible sharded layout is declared.

Tensor-parallel and data-parallel groups are conflated.

The row shard is correctly unique across tensor-parallel ranks but its replicas are never reduced across the data-parallel group, or the reverse.

Weight-tying and checkpoint bugs

Equal values are mistaken for one parameter.

embed.weight and lm_head.weight have equal hashes after initialization but are distinct Parameter objects. They receive separate gradients and optimizer state and can diverge on the first update. Verify object and storage identity for a colocated tie.

A checkpoint stores values but loses the alias graph.

The loader copies two keys into two independently constructed Parameters and never reapplies lm_head.weight -> token_embedding.weight. Serialize a canonical logical tensor plus an alias map, restore the topology explicitly, and verify it after loading.

Two declared alias keys contain different values.

Silently selecting one tensor discards trained state and hides an untied or corrupt checkpoint. Reject the load unless an explicit untied-to-tied migration policy chooses or merges the canonical value and validates the quality change.

The optimizer is built before an alias is restored.

The optimizer retains the replaced output Parameter while forward uses the embedding Parameter. Re-establish and verify aliases before constructing the optimizer, or rebuild optimizer parameter groups and restore one logical state.

One tied Parameter is registered twice with the optimizer.

The same logical weight can be stepped twice or carry duplicate state. Deduplicate by object identity and assert exactly one optimizer registration per colocated logical parameter.

A factorized lexical table is tied directly to a hidden-width head.

[V,D] and [V,H] have different coordinate spaces when . A reshape or copied prefix is not a classifier derivation. Insert a separate hidden-to-lexical bridge and tie only the compatible [V,D] decoder factor, or keep the head untied.

Source and target tables are tied from equal row counts.

Equal V and shape do not imply equal row meaning. Require the same ordered vocabulary identity, including special-token assignments, or an explicit joint vocabulary migration.

Tensor-parallel input and output shards use different row intervals.

Each local shape can be valid while lookup row v and classifier logit v refer to different global rows. Require identical input/output partitions or a declared reshard and remapping operation.

Pipeline replicas reduce values but not the two gradient paths.

The first stage steps only the input contribution and the last stage steps only the output contribution. Reconcile the logical sum before update, then apply one authoritative update or identical updates from equal optimizer state.

Pipeline replica values match while optimizer moments differ.

A periodic parameter broadcast makes one checkpoint look correct, but the next local optimizer step diverges again. Synchronize or centralize optimizer state as part of the logical tie.

The reconciled pipeline gradient is reduced twice.

Both a tied-embedding group and a wider data-parallel collective sum the same contribution without a declared normalization convention. Decide the group membership and the reduction order once, then check the result against one logical gradient.

Input and output roles create independent quantized packs and call them tied.

Different scales, calibration state, or mutable packed values are two physical representations. Keep one logical source tensor with role-specific derived packs and a regeneration policy, or explicitly declare runtime untying.

Harvard reproduction bugs

Missing sqrt(d_model).
Shapes match, but the source-compatible scale is wrong.

Applying sqrt(d_model) twice.
This happens when both the embedding wrapper and caller scale.

Treating sqrt(d_model) as a law independent of the initializer.

The output variance is d_model * sigma^2, not automatically one. Record the actual initializer, any re-initialization pass that runs after it, and where the scale is applied.

Calling the rectangular Xavier variance 1/d_model.

For a PyTorch [V,d_model] tensor with gain one, the Xavier variance is 2/(V+d_model). The square-matrix approximation is not the exact value for the Harvard table.

Fresh initialization confused with checkpoint loading.

A missing checkpoint key leaves random constructor rows behind. An exact load must fail rather than silently convert missing trained state into fresh state.

Vocabulary growth overwrites old rows.

Resize code reinitializes the full table rather than only appended/remapped rows. Compare the old prefix exactly and update optimizer state, output rows, biases, configuration, tokenizer identity, and tied aliases.

Assuming padding_idx forces a permanent zero row.

The constructor zeros a fresh PAD row, but supplied weights bypass that reset; global initialization, checkpoint load, tying, and regularization can define or change a nonzero row. The lookup-gradient rule is narrower than a zero-row invariant.

Ignoring max_norm as a forward mutation.

Selected rows can change during lookup even under inference and without an optimizer step. Hashing, autograd regularizers, checkpoint comparisons, and concurrent readers must account for that state change.

Equating autocast with converted parameters or fp32 master weights.

Autocast is operator-specific. Parameter storage, gathered output, gradient, optimizer moments, loss scaling, and an optional master copy need separate observed fields.

Calling only Embeddings when code expects Embeddings + PositionalEncoding.
The output is [B,L,d_model], but rows lack the positional component expected by the Harvard stack.

Calling src_embed when only raw content embeddings were intended.
Position encoding can be applied too early or twice.

Projector bugs

Mistaking d_media for d_model.
A vision encoder may output [B,N,1024]; the language model may expect [B,N,4096].

Projector maps to the correct width but wrong semantic space.
Z_media: [B,N,d_model] is shape-compatible but not aligned if the projector was not trained for this encoder and language model.

Projector trained for one encoder is used with another encoder.
The same d_media can hide incompatible feature distributions.

Projector frozen or trained contrary to the setup.
Both choices can be correct in different systems. The bug is making the wrong choice for the interface being reproduced.

Embedding-object bugs

Treating lookup rows as contextual states.

The same token ID selects the same input row before the Transformer stack; context-dependent meaning is produced later.

Using arbitrary hidden-state cosine as a calibrated retrieval score.

Vector width and cosine computability do not show that a downstream readout, normalization rule, or representation objective trained the space for retrieval. M3.11 covers that check.

Calling projected patch rows a single image embedding.

[B,N,d_model] model-consumable rows and a pooled [B,d_retrieval] task vector have different row counts, consumers, and objectives.

Treating equal-width downstream representations as interchangeable.

Vectors from different layers, pooling heads, checkpoints, or objectives can share a dimension without sharing a coordinate system. This article records only the handoff; M3.11 covers their comparison and when one may replace another.

Count-changing adapter bugs

Adapter changes n but masks still use old n.
[B,n,d] -> [B,r,d_model] succeeds while masks, row metadata, or labels still assume n.

Adapter reorders rows without metadata update.
The output rows have the correct width but no longer correspond to the original patches, spans, or events.

Query bottleneck collapses needed evidence.
The adapter produces valid [B,r,d_model] rows, but small OCR, visual, or audio evidence is compressed away.

Mixed-origin X0 bugs

Text and media concatenated along the feature axis.
The usual mixed-context path concatenates rows along dim=1, not features along dim=-1.

Rows have correct shape but wrong order.
Training may expect image rows before the question. Inference may append them elsewhere.

Row-type metadata lost.
The model or wrapper may no longer distinguish image rows, text rows, event rows, and PAD rows in the way training expected.

Geometry metadata dropped at concat.
Rows have width d_model, but layout, time, or order metadata no longer aligns for X1 and M3.3.

Ragged media batches padded without media masks.
Padded media rows become evidence rows.

Output-head and weight-tying bugs

Output head and input embedding vocabulary dimensions disagree.
Input lookup works; logits have the wrong vocabulary dimension.

Assuming tied weights when the implementation does not tie.
Checkpoint loading, parameter counting, and output behavior can be wrong.

Tying incompatible source, target, and output tables.
Weight sharing is not a free operation across different vocabularies.

Using transposed weight layout incorrectly.
Conceptually hidden @ W_out.T; framework storage for nn.Linear(d_model,V) has its own layout. Custom implementations must respect it.

The lab covers the input state this article builds. The tensor and gradient errors in it are caught by the toy checks of 0x03C, 0x04A, 0x04B and 0x0A and by the tests of 0x0C; the errors of identity, provenance and responsibility between modules are caught by the records a release keeps. Failures of contextual pooling, contrastive objectives, retrieval indexes and representation runtimes belong to M3.11 and to the retrieval and deployment articles after it, and are not repeated here.


0x0E What comes next: M3 and X1

This article ends with text rows of model width, X_text: [B,L_text,d_model]. That solves the width problem and leaves the geometry problem: the model still needs the order of the text, the visibility and score algebra of attention, position IDs or an attention bias, RoPE and context extension, and the residual, normalization and block execution.

M3.1 starts with the attention algebra; M3.3 to M3.5 cover positional geometry. The parallel route continues in X1.1 with non-text units and geometry, then in X1.2 with encoders, projectors, resampling and fusion.

Once M3.1 to M3.7 have produced contextual rows, M3.11 covers the separate route from those rows to pooled representations, task heads, typed scores and retrieval readout.


0xFF Reference

Primary Papers And Official Technical Sources

Contextual Surveys And Engineering Explanations

These sources preserve useful explanatory context. The article does not rely on them alone for a mechanism, implementation, or measurement claim.

Local Corpus And Downstream Owners