Manuscript Offprint
arXiv:2610.117164-Tensor Attention Model for Semantic Physical Reality
Abstract
We describe a 4-tensor attention model that predicts the next semantic state of a scene, for video generation and robot planning. A window of states has positions and two fibers, a semantic fiber and a temporal-context fiber, and one softmax normalizes attention jointly over the window. Frames and an agent's situation are written as those states; the encoder, the renderer, and the planner remain outside the update. To test the update on its own, we train on ROCStories, where each window poses the same next-sentence task at the semantic layer. On the validation split, with one seed per setting, the last-sentence cross-entropy on the three matched settings is lower for the 4-tensor model than for a free-running one-dimensional transformer by 5.3% at , , by 2.6% at , , and by 2.4% at , . At , the parameter counts are nearly the same, 172.5M and 175.9M. On the same two GPUs that 4-tensor run finished in 2.4 hours and the baseline run in 45.2 hours; the baseline is trained by free-running decoding, one sequential forward pass per target token.
Code is available at https://github.com/indigowave511/semantic-world.
Keywords: 4-tensor attention, semantic representation
Contents
1 Introduction 4
1.1 Implementation Scheme 4
1.2 Scope of This Paper 4
1.3 The Semantic State Sequence 5
1.4 Rank-4 Representation 5
1.5 Score Tensor and Joint Softmax 6
1.6 Attention Output 6
1.7 Prediction Targets and the Learning Objective 7
1.8 Autoregressive Inference 7
2 4-Tensor Transformer Design 8
2.1 Overview of the Tensor Pipeline 8
2.2 Stage-by-Stage Logic 8
2.3 Joint-Phase Temporal Embedding 9
2.4 Final Assembly of the Input Tensor 10
3 Forward Pass and Pipeline Overview 10
3.1 Pipeline Overview 10
3.2 Residual After Attention 11
3.3 Event Position MLP Block 11
3.4 Residual After MLP and Readout-Boundary Normalization 11
3.5 Vocabulary Readout and Structured Factorization 12
3.5.1 Sequence-Independent Matrix Pre-computation 12
3.6 Structural Constraints Imposed by the Loss Objective 13
3.7 Mapping to the Vocabulary Simplex 13
3.8 From Embedding-Level Loss to Cross-Entropy Loss 13
4 Enabling Construction of the Forward Pipeline 14
4.1 Index convention and storage 14
4.2 Parameters, buffers, and initialization 15
4.3 Step 1: construction of the input tensor 15
4.4 Steps 2–5: one attention head 16
4.5 Multi-head sum and the Pre-LN layer 17
4.6 Readout and the training loss 18
4.7 End-to-end training procedure 19
4.8 Faithfulness checks 20
5 Reference Implementation 20
5.1 Input construction 21
5.2 Rank-4 attention head 21
5.3 Multi-head sum, Pre-LN, and the MLP 22
5.4 Tied readout, shifted loss, and the model step 22
6 4-Tensor Attention Backward Pass and Weight Update Rules 23
6.1 Joint Softmax Jacobian and Score Tensor Gradient 23
6.2 Gradients with Respect to Q, K, and V 24
6.3 Chain Rule to the Projection Weights 25
6.4 Gradient-Descent Update Rule 25
7 Comparative Baseline: Standard 1-Dimensional Autoregressive Attention 25
7.1 1-D Sequence Packing and Standard QKV Architecture 26
7.2 Informational Parity via Free-Running Autoregressive Decoding 27
7.3 Architectural Alignment and Capacity Matching 27
7.4 Baseline design pipeline 28
7.5 Code for the fair comparison 30
8 Experimental Setup 30
8.1 Corpus and windows 31
8.2 Optimization and checkpoint rule 31
9 Experiment Data 31
10 Discussion 33
Modeling temporally coherent entities and environments is a central problem both for video generation [1, 12] and for world models used in planning and control [2, 3]. Most current systems operate on continuous sensory representations, in pixel or latent space, and can struggle to keep scenes consistent over long horizons. Part of the difficulty is that semantically relevant state and perceptual detail are mixed in the same dense representation. Latent predictive architectures [4, 5] and discrete visual tokenization with language models [6, 7] separate the two more explicitly. When such tokens are flattened into a single autoregressive sequence, however, spatially simultaneous content is given an order it does not have, and temporal structure must be recovered from one-dimensional position alone. Video transformers avoid a single raster order by attending jointly over all spatiotemporal tokens, or by factorizing attention into spatial and temporal stages [9]; each token, however, still carries a single feature vector in which content and temporal context are entangled.
Our approach compresses the content of a scene at a fixed time t into a one-dimensional semantic representation and keeps time as a separate axis. Describing a video as a temporal sequence of sentences has precedent in paragraph captioning [11], where the state of earlier sentences conditions the next; there the sentences describe frames that have been observed, whereas here the next semantic state is predicted before it is observed. Each state carries two fibers: a semantic fiber of width and a temporal-context fiber of width . A window of states is then a rank-4 tensor, and the update, which we call 4-tensor attention, acts on that tensor directly rather than on a flattened sequence.
1.1 Implementation Scheme
In the intended pipeline, semantic states are extracted from video frames at fixed intervals by an image-to-text model. The resulting sequence of textual states is processed by 4-tensor attention to predict future states, and the predicted states are rendered back into frames by a text-to-image model (fig. 1). The prediction step is where temporal consistency is decided; the encoder and the renderer determine only how faithfully a state is read from and written back to the visual domain.
1.2 Scope of This Paper
This paper tests one component of that program: whether the 4-tensor update predicts the next semantic state better than a flattened sequence model when both read the same window (sections 7 and 9). The image-to-text encoder, the text-to-image renderer, and any planner are outside this test. To isolate the update from visual encoding and decoding, the experiments operate directly at the semantic layer, on narrative windows from ROCStories, where each window poses the same next-sentence task.

Figure 1: The intended generative pipeline. Frames are compressed into semantic states, the 4-tensor attention update predicts the next states, and the predicted states are rendered back into frames. This paper implements and evaluates only the 4-tensor attention block (teal).
The separation of the two fibers may matter beyond sensory world models, as a representation in which transition rules could be learned apart from the objects they apply to. We return to this question in section 10.
1.3 The Semantic State Sequence
Let an observation be represented as a sequence of semantic states extracted at regular intervals. To give every state the same length N, shorter states are padded with a null token 0. For an agent waiting for an elevator, with N = 8:
S(t=0): [I, am, in, front, of, the, elevator, 0]
S(t=1): [I, am, looking, at, the, floor, indicator, 0]
S(t=2): [The, elevator, arrives, at, my, floor, 0, 0]
A window of length T collects the most recent T states. For T = 3,
The running example in this section uses T = 3 and N = 8. The experiments use T = 4 and N = 16 (section 8.1).
1.4 Rank-4 Representation
The window is a rank-4 tensor
with the states arranged along the temporal axis. Compared with standard scaled dot-product attention, every index is doubled. A sequence position becomes a pair , where is the token position within a state and is the temporal slice. The feature dimension becomes a pair of fibers: the semantic -fiber and the temporal-context -fiber. Input fiber indices are written and output fiber indices , with on the -fiber and on the -fiber.
The query, key, and value tensors are joint bilinear contractions over both input fibers,
with .
The two fibers enter as distinct tensor factors: each token is embedded as an outer product of a semantic vector and a temporal-context vector (section 2), and the readout ties the semantic fiber to the vocabulary (section 3). The projection , however, is a general bilinear map on the joint space and admits arbitrary interaction between the fibers. The architecture therefore does not force transition rules to separate from content. It keeps a representation in which such a separation can be learned and tested.
1.5 Score Tensor and Joint Softmax
The score between a query at and a key at contracts both fibers. To avoid a clash with the state sequence , the unnormalized score tensor is written E:
The factor is the standard variance correction for an inner product over coordinates.
The softmax normalizes jointly over the full grid of key positions , so that a query may draw on any token of any state in the window:
Apart from padding keys, which are masked (section 4.4), no mask is applied. In particular there is no temporal causal mask: every query attends to every slice of the window.
1.6 Attention Output
The attention output is the A-weighted sum of values over the key grid,
and has the same shape as the input .
1.7 Prediction Targets and the Learning Objective
In the full model the attention block is followed by a residual connection, a position-wise MLP, and a final LayerNorm, and the result is read out to vocabulary logits at every position (sections 3 and 4). Write F for this map from the window to the logits. The readout at slice t is a prediction of the next state,
An input window therefore yields predictions , and the training targets are the window shifted by one slice:
S(t=1): [I, am, looking, at, the, floor, indicator, 0]
S(t=2): [The, elevator, arrives, at, my, floor, 0, 0]
S(t=3): [The, elevator, doors, open, in, front, of, me]
Training minimizes the cross-entropy of all T predicted states against their targets, with padding positions ignored.
Because the joint softmax carries no temporal causal mask, for the target of slice is present in input slice . The terms of the training loss therefore read sentences already in the input. Prediction of a sentence absent from the input is measured only at the last slice:
In the running example this is , and in the experiments . All tokens of are predicted in one parallel forward pass, and the tokens of enter only as targets.
1.8 Autoregressive Inference
The generative task is to continue the sequence beyond the window:
S(t=3): [The, elevator, doors, open, in, front, of, me]
S(t=4): [I, step, inside, the, elevator, 0, 0, 0]
S(t=5): [The, doors, close, behind, me, 0, 0, 0]
S(t=6): [I, press, the, button, for, my, floor, 0]
The predicted state is first converted to tokens, , or by sampling. The window then slides by one state,
where the three states again occupy slices and are embedded by the same input construction. The same weights are applied, and the next state is read from the last slice:
Repeating the step with gives , and so on. Ground-truth states from onward never enter the window; each step conditions on the model's own earlier predictions. The window can thus be advanced repeatedly with fixed weights. This paper reports single-step results only; multi-step rollout is left to future work.
2 4-Tensor Transformer Design
2.1 Overview of the Tensor Pipeline
The 4-Tensor Transformer takes as its base unit the state tensor at a given temporal slice t, defined as:
The rank-4 input tensor is constructed via a sequential pipeline rather than a simultaneous summation. Each stage injects a single piece of information into a specific fiber:
Here, is a spatial position embedding from into the semantic -fiber, and is a temporal position embedding added from into the temporal -fiber. This ordering ensures that the spatial token position and temporal sequence position remain analytically separable within the unified rank-4 object.
2.2 Stage-by-Stage Logic
Stage A: Initialization by Dual-Dictionary Token Embedding
Traditionally, a token is embedded via a single dictionary lookup into a semantic vector space. However, because the temporal-context -fiber operates as a first-class axis in our rank-4 formulation, the token's initial embedding must explicitly bifurcate into two independent dictionaries:
The token embedding is rank-1 across the two fibers: the base state at position is the outer product of the two dictionary vectors. For each discrete temporal slot , a token at spatial position is embedded via two separate dictionaries:
Thus, is rank-3 from the outset, intrinsically carrying content along both the semantic -fiber and the temporal-context -fiber prior to any positional injection.
Stage B: Spatial Position Injection
The spatial position embedding is added independently per temporal slice:
Because spatial placement governs static semantic identity, resides entirely within the -fiber. It broadcasts identically across the -fiber , preserving the rank-3 structure.
Stage C: Temporal Stacking
The T sentence tensors are stacked along a newly initialized temporal axis:
This operation maps the sequence into the rank-4 configuration . Because operates independently per sentence and broadcasts over , the operations of adding and stacking over are mathematically commutative.
Stage D: Temporal-Order Injection
Finally, the temporal-order embedding is added, broadcasting strictly over the semantic -fiber :
While Stage A establishes the token-level context, Stage D establishes the rigorous positional trajectory across the causal surface.
2.3 Joint-Phase Temporal Embedding
Crucially, the temporal embedding must depend on both the temporal slice t and the spatial column x. A naive parameterization would assign the identical temporal signal to every spatial token within a given slice t. In scenarios where the same entity appears at different times (e.g., the token [I] appearing at t = 0 and t = 4 in our physical elevator progression), a column-independent signal fails to distinguish the token's shifting causal roles.
To resolve this, we formulate as a joint-phase embedding:
This formulation satisfies two properties of the phase :
-
Column Independence: For a fixed , whenever . The same phase gives . Positions that share a value of are distinguished once is added to the spatial embedding .
-
Offset Consistency: For a fixed shift , the phase increment depends only on and the frequency index , and a linear map on the -fiber, independent of , carries to . The implemented slide does not use . Each new window is written again onto positions , and is recomputed from those positions.
2.4 Final Assembly of the Input Tensor
The complete rank-4 input tensor is thus formalized through the direct superposition of these structured stages:
yielding the exact causal dimensionality required:
This boxed formulation is the input to the 4-Tensor Attention block. The sum is one tensor; the two fibers stay distinct factors, and may mix them.
3 Forward Pass and Pipeline Overview
Following the construction of the completed rank-4 input tensor , this section covers the remainder of a single-layer, single-head forward pass through to the training loss. Indices are zero-based, and , as in section 4.1. The pipeline encompasses the attention operation, residual connections with dropout, the position-wise MLP block, readout-boundary LayerNorm, vocabulary readout, and the final cross-entropy loss, including the t-index shift that connects the attention update to the prediction targets.
3.1 Pipeline Overview
The full transformation from the input tensor to the scalar loss is strictly sequentially ordered:
Where the intermediate variables are defined as follows:
• : The raw rank-4 output of the attention mechanism.
• : The intermediate state following the first residual connection and dropout.
• : The unflattened output of the position-wise MLP block.
-
: The completed rank-4 representation for the layer following the second residual connection and dropout.
-
: The state after applying LayerNorm over the semantic and temporal-context fibers , preparing the tensor for vocabulary readout.
The construction of (including the QKV generation, score tensor computation, and joint softmax) initiates the stage. The subsequent sections detail the pipeline beginning directly from the first residual connection.
3.2 Residual After Attention
Following the attention mechanism, the first residual connection is applied:
The indices align directly: the attention output resides in the exact same space as the input . This dimensional consistency is guaranteed because the query, key, and value tensors were all constructed by contracting the identical fibers via the weight matrices . Dropout is applied exclusively to the residual branch to preserve the main identity pathway.
3.3 Event Position MLP Block
The feed-forward network operates independently across each event position on the causal surface. Because the semantic and temporal-context fibers represent distinct algebraic spaces, we impose no separability assumption between them at this stage. Instead, the slice at each fixed is jointly flattened into a single feature vector of dimension before applying the non-linear transformations:
where flatten : maps the matrix slice into a vector, and unflatten restores the original rank-4 structure.
The projection weights are defined as and , with denoting the GELU activation function. To maintain the standard transformer capacity scaling relative to the joint input dimension, the hidden layer width is explicitly set to the standard expansion ratio: .
3.4 Residual After MLP and Readout-Boundary Normalization
Following the MLP block, the second residual connection is applied to produce the completed layer output:
The residual stream itself remains the raw sum of the block input and the dropped branch outputs. In the reduced-to-practice stack of section 4, each branch input is LayerNorm'd before attention and before the MLP; those normalizations are not placed after the residual add. The residual stream can therefore still grow across layers. If left unscaled at the readout, that magnitude saturates the vocabulary softmax and collapses the cross-entropy gradient. The readout-boundary LayerNorm below is retained in addition to the per-branch normalizations.
To stabilize the output logits without interfering with the internal attention dynamics, we introduce a Layer Normalization strictly at the readout boundary of the final layer. Consistent with the MLP block, this normalization operates over the jointly flattened semantic and temporal-context fibers, imposing no separability assumption. For the final layer's output , the normalized tensor is computed as:
The normalization is applied independently at each spatial-temporal position over the dimensional space, incorporating standard learnable affine parameters . By operating locally at each coordinate, the normalization strictly preserves the independence of causal slots and prevents any temporal information leakage.
3.5 Vocabulary Readout and Structured Factorization
To project the normalized state into the vocabulary, the general linear map is a dense tensor . The readout used here factorizes each vocabulary column as a rank-1 tensor on .
The semantic factor is the token embedding , tied to Stage A, and it contributes no new parameters. The temporal-context factor is a learned matrix . Each vocabulary item is therefore one rank-1 pair , the same boundary described as a rank-1 readout functional in section 10.
The factorization is:
where v indexes the vocabulary. Substituting this into the logit computation over the flattened slice yields:
3.5.1 Sequence-Independent Matrix Pre-computation
To evaluate this logit efficiently and avoid materializing a prohibitively large sequence-dependent intermediate tensor of size , we define an optimal evaluation order. We pre-compute a strictly sequence-independent projection matrix :
where is the identical joint-flattening bijection used in the MLP block. The final vocabulary logits are then computed via a direct matrix multiplication between the jointly flattened representation and the factorized matrix :
By decoupling the lexical projection from the sequence length, this factorized construction strictly preserves both the structural meaning of the distinct fibers and the computational tractability of the forward pass.
3.6 Structural Constraints Imposed by the Loss Objective
The mathematical structure of the vocabulary readout is not arbitrary; it is strictly dictated by the terminal loss function. Because the final training objective evaluates the predicted semantic states against the ground truth pointwise across both the sequence position x and the temporal step t, these two indices must be explicitly preserved. Conversely, the semantic and temporal-context fibers represent internal latent coordinates that do not exist in the discrete target space. Consequently, they must be contracted away.
This deterministic survival of indices—preserving while eliminating —requires a mapping from the normalized latent state to the vocabulary logits . The most general linear transformation is a joint bilinear contraction over the plane:
where the readout tensor is defined as .
That dense contraction is the general linear map. The implemented readout replaces it by the rank-1 factorization , one rank-1 pair for each vocabulary item.
3.7 Mapping to the Vocabulary Simplex
The raw logits derived from the readout projection are mapped onto the vocabulary simplex via a standard softmax operation over the vocabulary axis v:
This transformation is computed independently at each spatial-temporal coordinate , yielding a discrete probability distribution over the vocabulary space. This tensor represents the model's predicted likelihood for each discrete semantic token at position and time step .
While the explicit materialization of is strictly required for inference algorithms (e.g., autoregressive sampling or argmax decoding), during training, this probability mapping is analytically absorbed directly into the cross-entropy objective to guarantee numerical stability.
3.8 From Embedding-Level Loss to Cross-Entropy Loss
While traditional continuous generative architectures often formulate training objectives as direct regression losses at the embedding level (e.g., minimizing ), our discrete semantic framework evaluates predictions directly over the vocabulary simplex.
Transitioning from continuous vector space interpolation to discrete semantic evolution, the training objective is formulated as the cross-entropy loss over the predicted vocabulary distribution:
Table 1: Storage layout of the reduced-to-practice pipeline. The batch axis is present on every public tensor, including the case .
| Object | Shape | Index order |
|---|---|---|
| token_ids, | ||
| pad_mask | , true on a PAD key | |
| scores, attention weights | ||
| logits |
where and the logit slice is the distribution for sentence . Here is the target distribution at that position, and is the softmax of the readout logits. This formulation bridges the continuous hidden representations of the causal surface with the discrete semantic vocabulary space, completing the end-to-end differentiable training pipeline.
4 Enabling Construction of the Forward Pipeline
This section specifies the forward pipeline that was reduced to practice. The algebraic maps of the preceding sections are unchanged. What is fixed here is the order of operations, the in-memory axis order, the numerical guards, and which tensors are parameters. An implementation that preserves every shape in table 1 can still compute a different function if any check in section 4.8 is omitted. Storage indices below are zero-based.
4.1 Index convention and storage
Theory indices remain and . The stored activation places the position axes adjacent and the fibers last, so that the flattening
is a reshape with no permutation. The same is used for the attention contraction, the MLP, the readout-boundary LayerNorm, and the vocabulary matrix . A tensor whose last two axes are has the same product and would pass a product check while applying the wrong . Fiber checks therefore compare the ordered pair .
The weight tensor is the view of a matrix,
so is the linear map with no copy. Logits are stored and targets are stored . The bridge is the permutation . When that permutation preserves the shape. A missing permutation is therefore caught by checking that the target has shape before the permutation is applied.
A stored example supplied to training has shape , the sentences . The forward input is the prefix , of shape . An array of rank 2 and shape is rejected. The caller inserts the batch axis.
4.2 Parameters, buffers, and initialization
The learned parameters are the following.
-
and , with the row at the padding index held at zero and excluded from the gradient.
-
For each layer and each head, three maps , each stored as above. Xavier uniform initialization is applied to the flat matrix and then viewed into . Initializing the four-dimensional array directly mis-estimates the fan-in.
-
For each layer, two LayerNorm affine pairs of width (one before attention, one before the MLP), and one MLP of width .
• One further LayerNorm of width after the last layer.
- The readout factor , Xavier-uniform initialized.
The spatial table and the joint-phase table are fixed sinusoids, recomputed or registered as non-learned buffers. Dropout probability p is a hyperparameter, set to 0.1 in the reported runs. Evaluation disables dropout.
4.3 Step 1: construction of the input tensor
The input X is assembled in four stages. Each stage writes one signal into one fiber.
Stage A, content. For a token identifier ,
The slice at a padding identifier is the zero tensor, because both embedding rows are zero. No position has been added.
Stage B, spatial position. depends only on the column . With ,
If is odd, the last coordinate remains 0. is added at every batch index, every sentence index, and every :
Adding P before or after the stack over t is the same map, because P carries no t index.
Stage C, stack. The T sentences are already arranged along the sentence axis of the stored tensor . Stacking performs no arithmetic.
Stage D, joint-phase temporal embedding. depends on the sum of the column and the sentence index. With ,
and the last coordinate remains 0 when is odd. It is added at every batch index and every semantic coordinate n:
The phase makes the signal differ across columns of one sentence, and a shift of the sentence index is a linear map on the q-fiber. When the window slides, the positions are reused and is rebuilt on them. The maps apply to that re-indexed window.
On the stored layout the broadcasts are expanded in the sentence and slots, and expanded in the slot. The completed tensor has shape .
A padding slot is not the zero tensor after Step 1. Stages B and D add P and regardless of the token:
The keys and values built from that slot are nonzero. Which slots are padding is read from the integer token identifiers, not from the norm of X.
4.4 Steps 2–5: one attention head
One head owns three full-fiber maps. The contraction, written on storage indices, is
and likewise for and with and . Each of , , has shape . In the reduced-to-practice layer this contraction receives , as specified in section 4.5, rather than the raw residual.
The score is the scaled Frobenius product over the slice, jointly over the key grid :
With adjacent to , the reshape followed by a batched matrix product realizes this sum. The score tensor has shape .
The padding mask is built once per forward call:
which is the permutation of a boolean tensor. It is reused at every depth of that call, because later layers rewrite values of X and do not rewrite which slot held which identifier. It is rebuilt on the next call. A generation step that writes a token into a former padding slot must observe the new mask.
The mask is applied on the key axes only, by writing the smallest finite value of the score dtype into whenever is true. Query axes are left unchanged: a padding query is removed from the loss by the ignore index, and the MLP has no path from one slot to another. The fill value is the finite minimum, not . If every key of a query is padding, a fill of makes the softmax maximum undefined. The finite minimum leaves a finite maximum, and the softmax returns the uniform distribution on the NT keys.
Joint softmax then normalizes the last two axes together. In exact arithmetic,
The implementation subtracts the maximum over before the exponential, which is the stabilization inside a softmax on the flattened key axis of length NT. Dropout is not applied to A.
The head output contracts A with V and returns to the fiber layout:
The result has shape , identical to the residual stream.
4.5 Multi-head sum and the Pre-LN layer
A head count instantiates independent copies of Steps 2–5. Each copy keeps fibers of size and . The copies are summed, with no factor :
The case is exactly one head. The argument U is a normalized copy of the residual, not the residual itself.
Let denote LayerNorm over a last axis of length , with and learned affine scale and shift, applied independently at each :
The flatten and unflatten use . One layer then executes
LN and LN are distinct modules. The residual additions use the unnormalized stream X and . The two dropout calls share the rate p and draw independent masks. They are the only dropout sites: embeddings, the pre-layer norms, the joint softmax, the final norm, and the readout are undropped.
The MLP acts at each on the flattened fiber :
with , , , and
The linear maps use the reference implementation’s default initialization (Kaiming uniform on the weights, uniform biases of bound ). The hidden width is the ordinary expansion of a model dimension .
L such layers are applied in sequence to the same X, each consuming the shared pad_mask of the call. After the last layer, one further , denoted final_norm, produces . This norm is required in addition to the per-branch norms, because the residual stream that reaches it is the raw sum.
4.6 Readout and the training loss
The readout does not allocate a parameter tensor of shape . It ties the semantic fiber to the same used in Stage A and learns only . The sequence-independent matrix
is formed first. The logits are then one product,
viewed back to . Because , the padding column of is identically zero, and the padding logit is zero. A padding argmax on the generation path is reported as a warning. The logits are left unchanged, and no permanent mask is written onto the vocabulary axis.
Softmax over v is a diagnostic map used for sampling or inspection. The training loss does not materialize it and does not materialize a one-hot target. Given the full window token_ids_full of shape ,
so is the token of and Y has shape . The loss is the mean token cross-entropy of the integer targets after the axis bridge,
with ignore index equal to padding_idx. The log-softmax sits inside that reduction. Ignore-index removal drops padding targets from L. It does not replace the key mask
Table 2: Fiber role through one reduced-to-practice forward pass. The pair is eliminated at the readout and does not appear in .
| Stage | Tensor | Storage shape |
|---|---|---|
| Step 1 | X | |
| Steps 2–5, summed over heads | Attn | |
| After both residual adds | ||
| Readout-boundary norm | ||
| Tied readout | logits | |
| Shifted targets | Y |
of section 4.4, and the zero padding row of does not replace it either: that row only stops a padding identifier from contributing an embedding gradient.
The recorded last-slice score uses the final sentence axis of the same logits, , against 's last sentence, again ignoring padding. For the reported windows, , so this slice is .
Gradient descent accumulates into along both the Stage A path and the tied readout. receives a gradient only from the readout.
4.7 End-to-end training procedure
One training example of shape is processed as follows.
-
Reject the example unless its shape is with .
-
Split it into the input prefix token_ids of shape and the shifted target of shape .
-
Build pad_mask from token_ids by the permutation in section 4.4.
-
Build by eq. (39).
-
For each of the layers, replace by from section 4.5, reusing pad_mask.
-
Apply final_norm on .
-
Form from and , then the logits .
-
Permute from to and evaluate the ignore-index cross-entropy against the logits.
Teacher forcing uses ground-truth sentences on the input side for every term of . A predicted sentence is substituted for a ground-truth sentence only in the diagnostic multi-step rollout, which does not propagate a gradient. At evaluation time the same forward procedure is used with dropout disabled.
4.8 Faithfulness checks
The following conditions are part of the embodiment. Each one is a case in which a tensor can have a plausible shape and still implement a different map.
-
The activation layout is . The layout coincides with it whenever .
-
is shared by the weight view, the MLP, final_norm, and M. A swapped fiber has the same product.
-
P broadcasts over t and q. broadcasts over n. The two broadcasts are not interchangeable.
-
pad_mask is computed from token identifiers. is nonzero, so a mask inferred from selects the wrong slots.
-
Key scores of padding slots are filled with the smallest finite value of the score dtype. Query slots are unmasked. The MLP receives no mask.
-
pad_mask is local to one forward call and is shared by the layers of that call.
-
Each head uses a full fiber. Heads are summed, with no factor .
-
LayerNorm is applied to each branch input and, once more, to the final residual. The residual addends are the unnormalized stream.
-
Dropout with a single rate p is applied to the attention branch and to the MLP branch only.
-
M is materialized from and before multiplication by X. The alternative intermediate of shape is the same function at much larger activation cost and is not the implemented order.
-
The loss permutes Y from to and drops padding targets by the ignore index. The key mask remains in force on the forward pass.
-
Training compares logits to integer targets. The vocabulary softmax and the one-hot target are available as diagnostics and are not called by the training step.
5 Reference Implementation
The listings below are the design operations of four_tensor_model.py, in pipeline order. Shape and range checks, the optimizer wrapper, and diagnostic warnings are omitted. Every arithmetic line is the source statement. Comments are shortened to ASCII.
5.1 Input construction
def _sinusoidal_pe(positions, dim): # even 2i -> sin(pos / 10000^2i/dim); odd 2i+1 -> cos; leftover slot stays 0 half = dim // 2 i = torch.arange(half, device=positions.device, dtype=positions.dtype) div = 10000.0 ** (2 * i / dim) angle = positions.unsqueeze(-1) / div pe = positions.new_zeros(*positions.shape, dim) pe[..., 0:2 * half:2] = torch.sin(angle) pe[..., 1:2 * half:2] = torch.cos(angle) return pe
Stage A dictionaries. padding_idx row is zero and receives no gradient.
self.E_sem = nn.Embedding(vocab_size, d_x, padding_idx=padding_idx) self.E_temp = nn.Embedding(vocab_size, d_t, padding_idx=padding_idx)
Stage B: P_xn, phase = x. Stage D: Temb, phase = x + t.
x_idx = torch.arange(N, dtype=torch.float32) self.register_buffer("P", _sinusoidal_pe(x_idx, d_x), persistent=False) tau_idx = torch.arange(T, dtype=torch.float32) phase = x_idx[:, None] + tau_idx[None, :] # (N, T) self.register_buffer("Temb", _sinusoidal_pe(phase, d_t), persistent=False)
def build_token_tensor(self, token_ids): # token_ids (B, T, N) -> S (B, N, T, d_x, d_t) e_n = self.E_sem(token_ids) # (B, T, N, d_x) e_q = self.E_temp(token_ids) # (B, T, N, d_t) S = e_n.unsqueeze(-1) * e_q.unsqueeze(-2) # outer product (n, q) return S.permute(0, 2, 1, 3, 4).contiguous() # (B, N, T, d_x, d_t)
def build_input_tensor(self, token_ids): S = self.build_token_tensor(token_ids) S_tilde = S + self.P[None, :, None, :, None] # broadcast over (t, q) return S_tilde + self.Temb[None, :, :, None, :] # broadcast over n
5.2 Rank-4 attention head
def rank4_weight(d_x_out, d_x_in, d_t_out, d_t_in): # Xavier on the flat (m p, n q) matrix, then view to (m, p, n, q). mat = torch.empty(d_x_out * d_t_out, d_x_in * d_t_in) nn.init.xavier_uniform(mat) return nn.Parameter(mat.view(d_x_out, d_t_out, d_x_in, d_t_in).contiguous())
self.scale = 1.0 / math.sqrt(d_x_out * d_t_out) self.W_Q = _rank4_weight(d_x_out, d_x, d_t_out, d_t) self.W_K = _rank4_weight(d_x_out, d_x, d_t_out, d_t) self.W_V = _rank4_weight(d_x_out, d_x, d_t_out, d_t)
def contract(self, X, W): # Y[b, x, t, m, p] = sum{n, q} W[m, p, n, q] * X[b, x, t, n, q] B, N, T, d_x_in, d_t_in = X.shape d_x_out, d_t_out, _, _ = W.shape X_flat = X.reshape(B * N * T, d_x_in * d_t_in) W_flat = W.view(d_x_out * d_t_out, d_x_in * d_t_in) return F.linear(X_flat, W_flat).view(B, N, T, d_x_out, d_t_out)
def compute_scores(self, Q, K): # Scores (B, N, T, N, T), joint over the key grid (x', t'). B, N, T, d_x_out, d_t_out = Q.shape Qf = Q.reshape(B, N * T, d_x_out * d_t_out) Kf = K.reshape(B, N * T, d_x_out * d_t_out) scores = self.scale * torch.bmm(Qf, Kf.transpose(1, 2)) return scores.view(B, N, T, N, T)
def joint_softmax(Scores, pad_mask=None): # Key axes only. info.min, so an all-PAD key row stays finite and uniform. B, N, T, _, _ = Scores.shape if pad_mask is not None: neg = torch.finfo(Scores.dtype).min Scores = Scores.masked_fill(pad_mask[:, None, None, :, :], neg) return F.softmax(Scores.reshape(B, N, T, N * T), dim=-1).view(B, N, T, N, T)
def attention_output(self, A, V): B, N, T, d_x_out, d_t_out = V.shape Attn_flat = torch.bmm(A.reshape(B, N * T, N * T), V.reshape(B, N * T, d_x_out * d_t_out)) return Attn_flat.view(B, N, T, d_x_out, d_t_out)
def forward(self, X, pad_mask): Q, K, V = self.build_qkv(X) # three_contract calls A = self.joint_softmax(self.compute_scores(Q, K), pad_mask) return self.attention_output(A, V)
5.3 Multi-head sum, Pre-LN, and the MLP
def forward(self, X, pad_mask): # Each head keeps a full (d_x, d_t) fiber. No 1/sqrt(H) factor. Attn = self.heads[0](X, pad_mask) for head in self.heads[1]: Attn = Attn + head(X, pad_mask) return Attn
def compute_dff(d_x, d_t): return 4 * d_x * d_t
d_in = d_x * d_t; W1 (d_ff, d_in), W2 (d_in, d_ff)
self.fc1 = nn.Linear(d_in, d_ff) self.fc2 = nn.Linear(d_ff, d_in) self.ln = nn.LayerNorm(d_in) # MLP branch, distinct from ln_attn self.dropout = nn.Dropout(dropout)
def residual_after_attention(self, X, Attn): return X + self.dropout(Attn)
def mlp_block(self, X_out_attn): B, N, T, d_x, d_t = X_out_attn.shape v = self.ln(X_out_attn.reshape(B, N, T, d_x * d_t)).reshape(B * N * T, d_x * d_t) out = self.fc2(F.gelu(self.fc1(v))) return out.view(B, N, T, d_x, d_t)
def residual_after_mlp(self, X_out_attn, Z): return X_out_attn + self.dropout(Z)
def _norm_attn(self, X): B, N, T, d_x, d_t = X.shape return self.ln_attn(X.reshape(B, N, T, d_x * d_t)).reshape(B, N, T, d_x, d_t)
def forward(self, X, pad_mask): # Pre-LN on the attention branch; the MLP pre-norm is inside mlp_block. Attn = self.attention(self._norm_attn(X), pad_mask) return self.mlp(X, Attn)
5.4 Tied readout, shifted loss, and the model step
self.W_prime = nn.Parameter(torch.empty(d_t, vocab_size)) nn.init.xavier_uniform_(self.W_prime) self.final_norm = nn.LayerNorm(d_x * d_t)
def readout_logits_tied(self, X_output, E_sem): # M[n * d_t + q, v] = E_sem[v, n] * W_prime[q, v], then L = X_flat @ M. B, N, T, d_x, d_t = X_output.shape d = d_x * d_t X_flat = X_output.reshape(B * N * T, d)
M = torch.einsum("vn,qv->nqv", E_sem, self.W_prime).reshape(d, self.vocab_size) return (X_flat @ M).view(B, N, T, self.vocab_size)
def build_pad_mask(self, token_ids): # token_ids (B, T, N) -> mask (B, N, T), True where the id is padding. return (token_ids == self.padding_idx).permute(0, 2, 1)
def forward(self, token_ids): pad_mask = self.build_pad_mask(token_ids) X = self.input_construction(token_ids) for layer in self.layers: X = layer(X, pad_mask) B, N, T, d_x, d_t = X.shape X_norm = self.final_norm(X.reshape(B, N, T, d_x * d_t)).reshape(B, N, T, d_x, d_t) return self.readout(X_norm, self.input_construction.E_sem.weight)
def build_targets(token_ids_full): # (B, T+1, N) -> Y (B, T, N) = S(1), ..., S(T) return token_ids_full[:, 1:, :].contiguous()
def cross_entropy_loss(logits, Y, pad_id): # logits (B, N, T, |V|), Y (B, T, N). The permute is the axis bridge. tgt = Y.permute(0, 2, 1).reshape(-1) return F.cross_entropy(logits.reshape(-1, logits.size(-1)), tgt, ignore_index=pad_id)
def last_slice_token_stats(logits, token_ids_full, pad_id): # Reported score: non-padding tokens of S(T) only. last = logits[:, :, -1, :] gold = token_ids_full[:, -1, :] mask = gold != pad_id ce_sum = F.cross_entropy(last.reshape(-1, last.size(-1)), gold.reshape(-1), ignore_index=pad_id, reduction="sum") n_correct = ((last.argmax(dim=-1) == gold) & mask).sum() n_tok = mask.sum() return ce_sum, n_correct, n_tok
def training_step(self, token_ids_full): token_ids = token_ids_full[:, :-1, :] logits = self.forward(token_ids) Y = build_targets(token_ids_full) loss = cross_entropy_loss(logits, Y, pad_id=self.padding_idx) return loss, logits
6 4-Tensor Attention Backward Pass and Weight Update Rules
The derivation of the backward pass through the rank-4 attention mechanism requires rigorous tracking of the 4-dimensional index contractions. Because the token-position axes and the temporal-slice axes interact across multiple nested summations, we compute the exact analytical gradients traversing backward from the raw attention output through the joint softmax to the primary weight tensors. The temporal-context fiber is the index q.
6.1 Joint Softmax Jacobian and Score Tensor Gradient
Let denote the joint softmax probabilities computed over the score tensor . The Jacobian of this transformation with respect to the pre-softmax scores evaluates to:
The Kronecker deltas dictate that A depends on E exclusively through the row , sharing the identical query index . The joint-softmax rows remain entirely algebraically independent.
Applying the chain rule, we substitute this Jacobian to find the gradient of the loss with respect to the score tensor, denoted . The deltas collapse the outer summation over , yielding the exact row-wise softmax-gradient identity:
For each query , the gradient subtracts the A-weighted average of the incoming gradient across the entire key/value grid, subsequently scaled by the local probability .
6.2 Gradients with Respect to Q, K, and V
Recall the forward definition of the score tensor: . Differentiating with respect to the query tensor yields:
Collapsing the deltas, we express the gradients for Q and K in slice-matrix notation, where each spatial-temporal position acts as a matrix:
This explicitly reveals the index asymmetry: sums over its second index pair with the first pair fixed, whereas sums over its first index pair with the second fixed. This structural asymmetry directly mirrors their respective roles as row and column determinants of the score matrix.
Because the value tensor V bypasses the score computation and enters exclusively at the final attention contraction , its gradient relies directly on the incoming upstream gradient :
This operation is the exact transpose of the forward attention contraction: the backward pass distributes into using A as weights over the query sequence for each key/value position .
6.3 Chain Rule to the Projection Weights
The upstream gradient arrives at the attention block via the network's backward pass through the vocabulary readout, LayerNorm, MLP block, and sequential residual connections. Treating as the explicitly derived downstream targets, we backpropagate into the learned weight tensors .
Q, K, and V are formed from . The forward projection (e.g., ) is a strict rank-4 bilinear contraction. Differentiating this contraction strips out U, yielding the analytical gradients for the network weights:
Each formulation is a tensor outer product between the upstream gradient (in the m, p space) and U (in the n, q space), summed over positions . The gradient continues from U to the residual X through the LayerNorm.
6.4 Gradient-Descent Update Rule
The display is plain gradient descent, for exposition; training uses AdamW (section 8.2). Given a learning rate and the cross-entropy , the joint parameter updates are:
7 Comparative Baseline: Standard 1-Dimensional Autoregressive Attention
To rigorously evaluate the efficacy of the rank-4 structural decomposition, we establish a standard autoregressive (AR) transformer baseline tasked with the identical generative objective: predicting the future semantic state exclusively from the historical context window.
For an observation window of T = 3, the baseline model receives the exact same sequence of contextual states and must generate the subsequent state . Crucially, to maintain a fair comparison and prevent causal leakage, the ground truth target is strictly isolated from the input, mirroring the exact forward-prediction constraints imposed on the 4-tensor framework.
While the 4-tensor architecture explicitly decomposes the causal surface into independent token-position , temporal , semantic , and contextual axes, a standard AR transformer fundamentally lacks this geometric capacity. Instead, it must concatenate the discrete semantic states into a single, flattened 1-D token sequence. The standard self-attention mechanism operates globally over this unidimensional string, relying entirely on 1-D positional encodings to implicitly approximate temporal boundaries.
Consequently, this baseline serves not as an ablation of the 4-tensor mechanism, but as a definitive test of representation: it isolates the structural limits of applying standard flat-sequence attention to a problem domain that inherently demands spatial-temporal and semantic-contextual decomposition.
7.1 1-D Sequence Packing and Standard QKV Architecture
To process the structured context through a standard transformer, the distinct semantic states must be collapsed into a contiguous 1-D token sequence. We eliminate internal padding tokens and concatenate the discrete sentences in temporal reading order. Because standard vocabularies natively encode punctuation, explicit separator tokens between states are unnecessary.
To illustrate this structural flattening, consider a simplified contextual sequence:
Context X(2): [BOS] tom went to the store . he bought milk . then he walked home . [EOS]
Target S(3): [BOS] tom drank the milk . [EOS]
The baseline architecture operates entirely over this flattened 1-D string. The input representations are constructed by summing the shared lexical embeddings with standard 1-D absolute positional encodings:
where represents the token ID at sequence position i. The temporal progression is processed via the standard causal self-attention mechanism:
The baseline follows the same structural policy as the 4-tensor model: projection weights , MLP width 4d, and dropout on both residual branches. LayerNorm is applied to the residual stream before attention and before the MLP, and again on the flattened fiber immediately before the tied vocabulary projection .
During inference, the model is seeded solely with the flattened context sequence . It must then autoregressively emit the predicted sequence step-by-step, appending its own generated tokens until an token is produced. Consequently, the baseline processes as a structurally undifferentiated context, relying entirely on the 1-D causal mask and positional encodings to implicitly approximate the explicit spatial-temporal and semantic-contextual boundaries geometrically enforced by the 4-tensor model.
7.2 Informational Parity via Free-Running Autoregressive Decoding
To ensure a rigorous evaluation, the baseline must operate under the exact same informational premise as the 4-tensor framework: the model is conditioned exclusively on the historical context , with zero exposure to the ground truth tokens of the target state during inference.
In the 4-tensor architecture, the future state is decoded in a single, parallel forward pass across all spatial positions x:
By contrast, the standard 1-D baseline approximates the target state sequentially. To maintain strict informational parity, this generation must be executed in a free-running autoregressive mode. Let denote the flattened context sequence comprising and the explicit [BOS] token that initiates the target state. The baseline generates the target sequence step-by-step by continuously appending its own previous predictions:
where denotes 1-D sequence concatenation.
Because the prior predictions are deterministically generated from C and the model parameters, they contain no external information regarding the ground truth target. If the model makes an erroneous prediction at step 2, it is strictly forced to condition on that error at step 3. This constraint precisely isolates the fundamental architectural distinction—single-shot parallel structural projection versus 1-D sequential compounding factorization—without confounding the evaluation through asymmetric access to the target sequence.
7.3 Architectural Alignment and Capacity Matching
The baseline width is mapped from the 4-tensor fibers. Its model dimension is the joint product , and the feed-forward width is . The two models use differently. The 4-tensor model adds full-size heads; the baseline splits across its heads. The runs in section 9 use . Among them, and is the closest match in total parameter count.
With , raising from 2 to 4 adds parameters per layer to the 4-tensor model and none to the baseline, which is why the baseline count is the same in the first two rows of table 5. At , the totals are close, but they are spent differently: the 4-tensor model puts 100.7M into attention and 4.7M into its token table, the baseline 33.6M and 75.2M.
The embedding tables differ in shape. The baseline instantiates one table . The 4-tensor model factorizes that boundary into and .
Table 3: How a head count enters the parameter count. . Biases and LayerNorm are omitted. The baseline attention count is the reported case , three maps of size plus . The 4-tensor count is three full-fiber maps on each of heads and no output projection. The 4-tensor token term is , , and the readout factor .
| 4-tensor | Baseline | |
|---|---|---|
| Width of each head | full fiber, | |
| Head merge | sum, no output projection | concatenation, then |
| Attention parameters per layer | ||
| MLP parameters per layer | ||
| Token table and readout | , tied |
Finally, because the standard baseline lacks the explicit spatial-grid bounding inherently provided by the 4-tensor's position index , its vocabulary must be artificially expanded to include explicit [BOS] and [EOS] tokens. These boundary tokens are strictly required to control the start and termination of the 1-D sequence generation, a mechanism entirely obviated by the exact geometric decoding of the 4-tensor architecture.
7.4 Baseline design pipeline
The comparison model is a decoder-only causal transformer on one flattened token string. It receives the same stored window as the 4-tensor model and is asked for the same last sentence. It does not build a rank-4 tensor, a joint softmax, or a pair of fibers. Width, depth, dropout, and the optimizer are the copies stated in section 8.2: , , layers, residual dropout on both branches, AdamW at learning rate and weight decay 0.01.
Packing. Padding identifiers are deleted inside each sentence and the remaining tokens are concatenated in reading order. No separator is inserted; sentence boundaries remain only as whatever punctuation the tokenizer already emitted. Two identifiers are appended after the content vocabulary, and , and the padding index is left unused by them. For a window whose context is and whose target sentence is ,
Each row is then right-padded with the padding index to the longest row in the batch, and the true lengths and are retained. The gold span is a target. It is not written into the prefix.
Token representation. One table embeds every identifier, with the padding row held at zero. Position is a single integer along the packed string, encoded by the same sinusoid as section 4.3 with phase and width :
There is no column index x and no sentence index inside the position code.
Causal block. A key at position is blocked when , and every padding key is blocked. The blocked entries of the score are filled with the smallest finite value of the score dtype, the same guard as the 4-tensor key mask. Heads partition . With the maps have no output projection and the score scale is . With , must divide , each head has width , the scale is , and a learned map recombines the concatenated heads. The reported runs use , so they include . One layer is Pre-LN on both branches, with distinct LayerNorms of width and GELU in the MLP:
The residual stream is the raw sum. After the last layer, one further produces . Attention still runs on the full packed prefix; only the inputs of attention and of the MLP are normalized.
Readout at the last live position. The vocabulary projection is tied, . In the free-running loop only the logit at the last content position of each row is consumed. Because the tied map has no cross-position term,
The implementation therefore normalizes the full sequence, slices that one vector, and multiplies by . The earlier positions remain available as keys and values on the next step. The slice changes the activation size, not the function.
Free-running objective. Training and the reported comparison use the same loop. Start from the packed prefix. At step , read the logit of the last live position, add the cross-entropy against the gold token at that step, then append argmax of that logit. The appended identifier is detached, so the gradient stops at the logit that chose it and does not pass through the discrete token. If the argmax differs from the gold token, the next step conditions on that own token. Rows that have already exhausted their gold span are left inactive. Two reductions are accumulated. The selection loss averages every gold token, including [EOS]. The quantity placed beside the 4-tensor last-slice score averages only the content tokens of , dropping [EOS], on the same non-padding denominator. Evaluation decodes greedily from the prefix alone, stops at [EOS] or after N content tokens, and aligns that string to the gold content for the token accuracy in table 5.
Teacher-forced training, which would place gold on the input side of later steps, is a different premise. It is not the path implemented in the comparison model, and its cross-entropy is not the number in table 5.
The 4-tensor model receives a loss on all T target sentences of a window, of which only is absent from the input; the baseline receives a loss only on the tokens of .
7.5 Code for the fair comparison
Ordinary causal self-attention, Pre-LN, and the position-wise MLP are omitted. The statements below are the parts of baseline_ar_attention_model.py that fix the comparison: the same window, a premise that excludes gold , a tied readout that is algebraically unchanged by the last-position slice, and a content-token denominator aligned with the 4-tensor last slice.
def compute_d(d_x, d_t): return d_x * d_t # one width, d_ff = 4*d elsewhere
def bos_eos_ids(content_vocab_size): # Appended after the pool vocabulary. The padding index is not reused. return content_vocab_size, content_vocab_size + 1
def strip_pad(row, pad_id): return row[row != pad_id]
token_ids_full (B, T+1, N). No separator token.
parts = [strip_pad(token_ids_full[b, t], padding_idx) for t in range(T + 1)] prefix = torch.cat([bos, *parts[:T]]) # [BOS] + S(0) .. S(T-1) gold = torch.cat([parts[T], eos]) # S(T) + [EOS], target only
def forward_last(self, ids, lengths=None): # Full causal stack, then one vector into the tied table. # forward(ids)[b, i] == forward_last(ids, lengths)[b] at i = lengths[b]-1. H = self._encode(ids) if lengths is None: H_last = H[:, -1, :] else: idx = (lengths - 1).clamp(min=0, max=H.shape[1] - 1) H_last = H[torch.arange(H.shape[0], device=ids.device), idx] return F.linear(H_last, self.E.weight)
One free-running step. Gold is the target; the next input is the model's argmax.
last = self.forward_last(ids[:, :L_now], lengths) tgt = packed.gold[:, step] loss_sum = loss_sum + F.cross_entropy(last[active], tgt[active], reduction="sum") is_content = active & (tgt != self.eos_id) # drop EOS: same slots as 4-tensor S(T) content_sum = content_sum + F.cross_entropy( last[is_content], tgt[is_content], reduction="sum") hat = last.argmax(dim=-1).detach() ids[active, write_at[active]] = hat[active]
def training_step(self, token_ids_full): return self.training_step_fair(token_ids_full)
Eval string is (B, N): store content, skip EOS, stop after N tokens.
emit = live & (nxt != self.eos_id) & (n_content < self.N) hat[rows, n_content[rows]] = nxt[rows] g = packed.gold[b, : int(packed.gold_len[b])] if g.numel() > 0 and int(g[-1]) == self.eos_id: g = g[: -1] # accuracy gold is S(T) without EOS out[b, :n] = g[:n]
8 Experimental Setup
The runs below train the Pre-LN 4-tensor model and the free-running 1-D baseline on the same semantic windows. Both place LayerNorm on the residual stream before attention and before the MLP, apply dropout on both residual branches, and apply one further LayerNorm on the fiber immediately before the tied readout. The number reported across the two models is the mean cross-entropy on the non-padding tokens of the last sentence.
8.1 Corpus and windows
The corpus is the ROCStories pool of spring 2016, winter 2017, and the accompanying cloze files: 101,671 stories in total. Each stored window has shape . The model conditions on . and the recorded score is the cross-entropy of . Sentences are padded to with padding index 0; the pad fraction over the pool is 0.3876, and 2,457 sentences were truncated because they exceeded tokens. The vocabulary contains the 36,711 tokens of frequency at least one. The vocabulary is built over the full pool, including the validation split. The baseline adds [BOS] and [EOS], giving vocabulary size 36,713.
Of these windows, 97,929 are the training split and 3,742 are the validation split. Early stopping and checkpoint selection use the validation split, and the tables below report that split. The validation denominator for is 32,173 non-padding tokens. A uniform distribution over the 36,711-word vocabulary has cross-entropy .
8.2 Optimization and checkpoint rule
Both models use and . The baseline therefore has width and feed-forward width . Dropout is 0.1. The optimizer is AdamW with learning rate and weight decay 0.01. Each GPU receives a batch of 32; on two RTX 3080 GPUs the effective batch is 64. Seeds are fixed and deterministic algorithms are enabled. The head count, layer count, and seed of each run are those of table 5.
Training stops when at least five epochs have passed since the minimum validation loss and the current loss is above 1.01 times that minimum, or when the epoch budget is exhausted. The reported checkpoint is the epoch of that minimum. For the 4-tensor model the selection loss is the teacher-forced window cross-entropy on , with padding ignored. For the baseline the selection loss is the free-running cross-entropy of its own tokens, including [EOS]. The column placed beside both models is a different quantity: the token-weighted mean cross-entropy of the non-padding content tokens of . On the 4-tensor side this is one parallel forward pass, and the gold tokens of are targets only. On the baseline side the same tokens are scored by free-running decoding from [BOS] plus the flattened context, with [EOS] removed from the denominator. Token accuracy is the argmax match rate on those same 32,173 positions. For every reported 4-tensor setting, the epoch of minimum validation window loss coincides with the epoch of minimum .
9 Experiment Data
Table 5 lists the matched Pre-LN settings at the checkpoint selected by the rule in section 8.2. Each entry is written as 4-tensor / baseline. The epoch column is the selected epoch followed by the last logged epoch. The difference is
A positive means the 4-tensor cross-entropy is lower. Perplexity is and is omitted from the tables.
Table 4: Shared setup of the runs.
| Item | Value |
|---|---|
| Corpus | ROCStories, window 5 × 16, condition on four sentences |
| Split | 97,929 train / 3,742 validation |
| Vocabulary | 36,711; baseline 36,713 with [BOS], [EOS] |
| Width | , ; baseline , |
| Dropout | 0.1 on both residual branches |
| Optimizer | AdamW, learning rate , weight decay 0.01 |
| Batch | 32 per GPU, effective batch 64, two RTX 3080 |
| Selection | minimum validation loss; stop once five epochs have passed and the loss exceeds that minimum |
Table 5: Matched settings at the selected checkpoint. Each entry is 4-tensor / baseline. Epoch is selected/last. is the mean cross-entropy on the 32,173 non-padding tokens of the last sentence, and accuracy is the argmax match rate on the same tokens. is defined in the text.
| H | L | seed | parameters | epoch | acc. (%) | Δ | |
|---|---|---|---|---|---|---|---|
| 2 | 2 | 43 | 122.2M / 175.9M | 4/9 / 30/39 | 5.562 / 5.873 | 16.8 / 7.3 | 0.311 |
| 4 | 2 | 43 | 172.5M / 175.9M | 6/11 / 45/50 | 5.554 / 5.701 | 16.0 / 10.5 | 0.147 |
| 4 | 3 | 42 | 256.4M / 226.2M | 6/11 / 29/35 | 5.531 / 5.667 | 15.4 / 11.1 | 0.136 |
At the selected checkpoints, the mean cross-entropy on , recovered from the logged window loss and using the validation token counts, is 0.10–0.12, against 5.53–5.56 on .
Figure 2 shows at every logged epoch. On each panel the 4-tensor curve stays below the baseline curve once the baseline has entered the plotted range, including at the lowest baseline point on that trajectory. On each 4-tensor curve the marked epoch is the minimum, and the curve is higher afterward; the stopping rule in section 8.2 ends the run on that rise. Over all logged epochs, the lowest baseline is 5.845, 5.694, and 5.667, above the 4-tensor minima 5.562, 5.554, and 5.531. The gaps on that comparison are 0.283, 0.140, and 0.136. Figure 3 is the loss the optimizer steps on, drawn apart from because the two are not on the same scale. On the 4-tensor runs it falls from 2.180, 2.178, and 2.521 at epoch 1 to 1.479, 1.435, and 1.446 at the marked checkpoints. staying near 5.5 is the term on , the only sentence of absent from the input ; the training loss averages with , , and . Figure 4 evaluates that same pair of windows on the validation split, input and target . Its marked points are the minima used for checkpoint selection: 1.305, 1.305, and 1.314 for the 4-tensor runs, and 5.481, 5.310, and 5.297 for the baseline. On each 4-tensor curve the validation loss is higher after the marked epoch.
On the three matched pairs the last-slice cross-entropy is lower for the 4-tensor model: 5.562 against 5.873 at , , 5.554 against 5.701 at , , and 5.531 against 5.667 at , . The , pair is the closest parameter match, 172.5M against 175.9M, and corresponds to perplexities 258 and 299. On the same two RTX 3080 GPUs the 4-tensor run finished in 2.4 hours and the baseline run in 45.2

Figure 2: Validation cross-entropy of the non-padding tokens of . This is the sentence absent from the input: the model reads , and is not in that window. The solid curve is the 4-tensor model and the dashed curve is the free-running baseline. Open circles are the checkpoints in table 5. Epoch 1 of each baseline lies above the plotted range (12.9–15.0). The horizontal axis is the epoch index, not wall-clock time: at , those runs took 2.4 and 45.2 hours.
hours. The , pair trains a smaller 4-tensor model, 122.2M against 175.9M, with perplexities 260 and 355. The , pair trains a larger 4-tensor model, 256.4M against 226.2M, with perplexities 252 and 289. That baseline stopped at epoch 35 of a 100-epoch budget under the rule in section 8.2, and the selected checkpoint is epoch 29. Each cell is a single seed, and the checkpoint was chosen on the validation split reported here.
10 Discussion
The rank-4 factorization forces the model to distinguish semantic content from temporal context, keeping the - and -fibers as distinct tensor factors. The separation is imposed only at the boundaries, through rank-1 input embeddings and rank-1 readout functionals, while the internal weight remains a general bilinear map that admits arbitrary cross-fiber interaction. Coupling two representation subspaces through a bilinear weight tensor was used in deep tensor neural networks for speech recognition [10]; here the same kind of coupling parameterizes the query, key, and value maps of an attention mechanism over a window indexed jointly by position and time. The architecture does not, however, force transition rules to be abstracted from the objects they apply to; it preserves a representation in which such abstraction can emerge and be tested.
Future directions. This representation makes a further question testable: whether a learner of coupled agent–environment dynamics can acquire, without structural annotation or recursion-specific modules, an operation whose output fills its own argument slot. Nested containment is a minimal setting for this question, and with identical containers the iterated operation takes the form of Zermelo’s successor construction,

Figure 3: Training cross-entropy on separate axes. The upper row is the 4-tensor model trained in these experiments. On a training window the input is , and the loss is the mean cross-entropy of the shifted window . The lower row is the baseline, whose loss is the free-running loss on , including [EOS]. Open circles are the checkpoints in table 5. Epoch 1 of each baseline lies above the plotted range (29.1–32.6). The horizontal axis is the epoch index, not wall-clock time.
We develop this program, including criteria under which it would be refuted, in a separate document.
A multi-step rollout, with parameters held fixed, would score sentences from onward under free-running inputs. For an evaluation horizon ,
where indexes the sentence , and conditions on earlier predictions rather than on the ground-truth sentence. No value of this metric is reported. Denoising may be performed on interpolations between generated images.
Patent Notice The methods described in this paper are the subject of a pending Korean patent application (Application No. 10-2026-0191535, filed October 6, 2026) by IndigoWave Inc. Researchers interested in using these methods are welcome to contact the authors.

Figure 4: Validation cross-entropy on separate axes. The upper row is the 4-tensor model on the validation split, with the same windows as fig. 3: the input is , and the loss is the mean cross-entropy of . The lower row is the baseline selection loss on , including [EOS]. Open circles are the checkpoints in table 5, which are the minima of these curves. Every logged epoch lies inside the plotted range. The horizontal axis is the epoch index, not wall-clock time.
References
[1] Brooks, T., Peebles, W., et al. (2024). Video generation models as world simulators. OpenAI.
[2] Hafner, D., Pasukonis, J., Ba, J., & Lillicrap, T. (2023). Mastering diverse domains through world models. arXiv preprint arXiv:2301.04104. (DreamerV3)
[3] Brohan, A., Brown, N., Carbajal, J., et al. (2023). RT-2: Vision-language-action models transfer web knowledge to robotic control. In Conference on Robot Learning (CoRL).
[4] LeCun, Y. (2022). A path towards autonomous machine intelligence version 0.9.2. OpenReview. (JEPA Proposal)
[5] Bardes, A., Garrido, Q., Ponce, J., Chen, X., Rabbat, M., LeCun, Y., et al. (2024). Revisiting feature prediction for learning visual representations from video. arXiv preprint arXiv:2404.08471. (V-JEPA)
[6] Yu, L., Lezama, J., et al. (2023). Language Model Beats Diffusion – Tokenizer is Key to Visual Generation. In International Conference on Learning Representations (ICLR). (MAGVIT-v2)
[7] Kondratyuk, D., Yu, L., Gu, X., et al. (2023). VideoPoet: A large language model for zero-shot video generation. arXiv preprint arXiv:2312.14125.
[8] Zermelo, E. (1908). Untersuchungen über die Grundlagen der Mengenlehre I. Mathematische Annalen, 65, 261–281.
[9] Arnab, A., Dehghani, M., Heigold, G., Sun, C., Lučić, M., & Schmid, C. (2021). ViViT: A video vision transformer. In Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV), 6836–6846. (ViViT)
[10] Yu, D., Deng, L., & Seide, F. (2013). The deep tensor neural network with applications to large vocabulary speech recognition. IEEE Transactions on Audio, Speech, and Language Processing, 21(2), 388–396. (DTNN)
[11] Yu, H., Wang, J., Huang, Z., Yang, Y., & Xu, W. (2016). Video paragraph captioning using hierarchical recurrent neural networks. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 4584–4593.
[12] Ho, J., Chan, W., Saharia, C., Whang, J., Gao, R., Gritsenko, A., et al. (2022). Imagen Video: High definition video generation with diffusion models. arXiv preprint arXiv:2210.02303. (Imagen Video)