DenseFormer: Enhancing Information Flow in Transformers via Depth Weighted Averaging
Paper · 2024 · Matteo Pagliardini, Amirkeivan Mohtashami, François Fleuret et al.
Summary
Every block in a standard Transformer receives a representation that has passed through the block immediately before it. As the stack grows deeper, useful information from early blocks must travel through more transformations before later blocks can use it. DenseFormer gives those later blocks a shorter route to earlier outputs. The authors ask whether making those outputs directly available can improve next-token prediction without paying for a substantially larger network or exposing it to more training data.
DenseFormer inserts a depth-weighted average, or DWA, between Transformer blocks. A DWA combines the current block’s output, earlier block outputs, and, where the connection pattern allows it, the original token embeddings. Each connection has a learned scalar coefficient. That coefficient is shared across token positions and stays fixed during inference. The added coefficients account for little of the total parameter count, but applying them involves operations on sizable arrays. The authors therefore test two ways to cut the work. Dilation makes each DWA read a regularly spaced subset of earlier outputs. Periodicity determines how frequently a DWA is applied in the stack.
On OpenWebText2, the authors compare systems with matched depth, inference throughput, predictive quality, or training time. A 48-block DenseFormer with dilation 4 and period 5 reaches similar final perplexity to a 72-block standard Transformer and runs 1.4× as fast at inference in the reported comparison. Perplexity measures how much probability a predictor assigns to the observed next tokens, with lower values indicating better predictions. The shallower DenseFormer also has a smaller parameter count and memory footprint in the comparison with the deeper baseline. At equal training time, the same DenseFormer variant reaches lower validation perplexity than a standard Transformer of its own depth, even though the baseline is given more training steps. Experiments on PG-19 and with longer training sequences show gains in those settings as well.
The learned coefficients show a recurring pattern across depths and training runs. Mixers give substantial weight to nearby outputs, draw strongly on the input embeddings, and combine a group of block outputs near the end of the stack. The embeddings tend to receive positive coefficients early and negative coefficients late. The authors relate that shift to a possible transition from processing the current token to predicting its successor. Controlled comparisons also show that learned gains on ordinary residual connections and a single mixture at the end recover less of the perplexity improvement. The experiments support distributing access to earlier representations through the stack, while the proposed explanation of what the network does with that access remains a hypothesis.
Deep dive: DenseFormer: Enhancing Information Flow in Transformers via Depth Weighted Averaging
DenseFormer lets Transformer blocks reuse earlier representations, improving next-token prediction and reducing inference cost at similar perplexity. · about 35 minutes to read
The problem and its context
What has to travel through a deep stack
A Transformer block can transform the representation at each token position using information from other positions. Its output then becomes the input to the next block. The resulting sequence of computations gives a deep network many opportunities to refine a representation. It also determines which versions of that representation a later block can see directly. A late block sees the result of the preceding block, which already reflects many earlier transformations. An early output can influence that result, but the late block has no separate input through which to retrieve the early output itself.
This distinction between influence and access motivates DenseFormer. An early block might produce a feature that remains useful much later, even as intermediate blocks concentrate on other features. In the ordinary stack, information about that early feature has to survive the intermediate computations in some form. A direct route would let a later stage draw on the earlier representation alongside the current one. The authors hypothesize that such a route reduces the pressure to preserve early information in every intervening state. The architecture gives a concrete way to test the value of that route by changing how blocks exchange representations while retaining the usual operations inside them.
The paper frames this as a problem of language modeling and pretraining. In the task it studies, the predictor uses the tokens available so far to assign probabilities to the next token. Each position has an input representation associated with the token already seen. The final representation at that position must support a prediction about what follows. The authors suggest that this creates competing demands on the representation as it evolves through the stack. Early computations can benefit from keeping the identity and features of the current token available. Later computations must produce a representation suited to scoring possible successors. Direct access to selected earlier states could give the stack more flexibility over when and where to preserve the original information.
Why depth and training data matter together
The authors situate this architectural question in a practical scaling problem. They describe a progression from systems with millions of parameters to systems with billions, accompanied by greater computing and memory demands. Adding blocks is a way to increase the amount of computation available for prediction. It also increases how much computation is required to produce each prediction and how many parameters must be kept available. The paper cites prior observations of diminishing returns from increasing depth. Those observations make a change in connectivity worth testing at depths where adding more blocks already carries meaningful costs.
Training a smaller network for more steps addresses a different part of the cost. The authors discuss this strategy in connection with Llama. A smaller network can be attractive at inference, and longer training can help it take advantage of more examples. The strategy adds to the training requirement, and the authors point to earlier work on the potential scarcity of enough data at large scales. An architectural change that improves prediction under a fixed exposure to examples would address that concern more directly. It could also offer an alternative to added depth when deployment cost matters.
These concerns give rise to several separate questions. At a fixed depth and training schedule, the useful measure is the improvement in prediction. At comparable inference throughput, the useful measure is the predictive quality that can be delivered at that rate. At comparable perplexity, the useful measures include depth, parameter count, and speed. The paper also asks what happens when the standard architecture can spend the same training time processing more batches. Each comparison answers a different version of the question of whether the new connections are worth their cost.
Earlier ways to carry forward information
The paper draws an analogy with deep convolutional networks in computer vision. Residual connections and Highway Networks supplied routes that helped information move through many transformations and supported training of deeper stacks. DenseNets took the access idea further by allowing a layer to make direct use of outputs from earlier layers throughout the network. DenseFormer takes its broad motivation from that work. Its particular design is a scalar-weighted combination of representations at the boundaries between Transformer blocks.
Residual connections already provide a shortcut within the ordinary Transformer architecture. In the paper’s comparison, a residual route carries a value around a transformation and adds it to the transformed value. This makes it easier to retain and update a representation. After that addition, the next computation receives the combined state. DenseFormer adds access to block outputs saved at several depths, so a later computation can receive a fresh combination of states that had previously gone their separate ways through the stack.
The paper identifies Depth-wise Attention as a closer relative. That method combines representations of a token from different depths with an attention-like operation before the final projection. Depth in this setting means position in the stack. The candidates are different representations of the same token, so the operation runs along a different axis from ordinary self-attention over token positions. Depth-wise Attention uses dot products to compute the mixture weights. DenseFormer learns scalar weights directly and uses mixtures at multiple depths, giving intermediate blocks opportunities to transform the combinations they receive.
CotFormer connects earlier and current representations through another arrangement. As described by the authors, it interleaves representations so that a current position can attend to previous versions of itself and of earlier tokens. DenseFormer takes a narrower route. Its DWA directly mixes matching positions across depths, using coefficients that stay the same across inputs after training. The standard self-attention inside its blocks continues to provide interactions among positions. This division is central to the cost argument: the new route can use information already computed by attention without performing another attention calculation to determine how to read it.
The authors also distinguish the proposal from work on the operations inside a block. They discuss variations in normalization, activation functions, and the arrangement of attention and feed-forward computation, as well as efforts to approximate attention more cheaply or to remove redundant operations. DenseFormer changes what moves between blocks, which leads the authors to expect that it could be combined with such changes. They also discuss hardware-aware attention implementations as examples of the importance of moving data efficiently. That concern applies to DWA because a small coefficient array can still require repeated reads of large representations.
The method, step by step
Following one token position through the stack
Begin with a sequence of input tokens. An embedding operation turns each token into a vector, a list of numerical features that can be processed by the network. A block receives a whole sequence of these vectors. In the paper’s setup, the block applies self-attention and then a multilayer perceptron, a feed-forward transformation with a hidden layer. Self-attention lets the representation at a position draw on information from other positions available to it. The resulting sequence of vectors is the block’s output.
In a standard stack, that output is passed directly to the next block. In DenseFormer, the raw output is first saved. A DWA can then combine it with other saved outputs and pass the resulting mixture on. The distinction between raw and mixed states is important. The next block works on a mixture, but the saved history consists of outputs taken before their respective mixtures. This gives a later DWA access to what an earlier block produced as well as to what the present block has computed after receiving earlier mixtures.
At the first block, the full DWA has access to the embedding and the raw output of that block. At the second, it can use the embedding and both raw block outputs. The second raw output already reflects processing of the first mixture. It can now be combined with the first raw output again, with a coefficient learned specifically for this destination. The same earlier representation can therefore serve several stages, and its contribution can differ from one stage to the next.
Consider the vector at a particular token position. The DWA multiplies the vector from each eligible depth by that depth’s coefficient for the current mixer. It adds those scaled vectors component by component. The procedure applies across the sequence, using the same set of coefficients at each position. The early vectors being combined can already contain information about other tokens, since they were produced by blocks with self-attention. The direct operation performed by DWA, however, combines the vector at the chosen position with earlier versions at that same position.
How DenseFormer passes representations between blocks
The steps in order.
The standard recurrence
The paper uses a depth index to describe the ordinary stack and the modified one. Both begin with the same embedding operation.
X₀ := Embedding(X)
The symbol X denotes the input sequence of tokens. Embedding is the operation that converts it into token vectors, and X₀ denotes the resulting array. The subscript ₀ identifies the point before any block has acted. The symbol := defines the quantity on its left.
Xᵢ := Bᵢ(Xᵢ₋₁), i = 1, …, d
Here i is the current block index, d is the total number of blocks, and Bᵢ is the transformation carried out by block i. The notation Xᵢ denotes that block’s output, and Xᵢ₋₁ denotes the representation entering it from the immediately preceding depth. At the first block that entering representation is X₀. The range after the comma says to apply this definition at every block through depth d, with the ellipsis standing for the intervening indices.
Transformer(X) := X_d
Transformer is the standard stack viewed as a function of the input sequence X. The underscore marks d as the subscript in X_d, the raw output of the last block. This is the representation produced by the stack. The language-prediction implementation then uses the final state to produce scores for tokens.
The recurrence with a mixture at each depth
DenseFormer adds a second sequence of states, denoted by Y. The initial state is shared by the two sequences.
Y₀ := X₀
Y₀ is the state passed to the first block. X₀ is the embedded input defined above. Both symbols refer to the same starting representation because there is no post-block mixture before the first block.
Xᵢ := Bᵢ(Yᵢ₋₁), i = 1, …, d
The raw output Xᵢ is still the result of applying block Bᵢ. The input to that transformation is now Yᵢ₋₁, the state passed forward from the preceding depth. The indices i and d again designate the current block and the depth of the stack. This equation is what lets an earlier mixture affect later computations. Once a block has transformed its incoming mixture, its own raw output enters the history available for subsequent use.
Yᵢ := Σⱼ₌₀ⁱ αᵢ,ⱼ · Xⱼ
Yᵢ is the mixture made after block i. The summation sign Σ adds one term for each source index j from 0 through i. Xⱼ is the embedded input when j is 0 and the raw output of block j at positive indices. The coefficient αᵢ,ⱼ is the learned scalar for the connection from source j to the mixer at destination i. The dot denotes multiplication of every component of Xⱼ by that scalar. All the terms have the same representation shape, so their sum also has that shape.
DenseFormer(X) := Y_d
DenseFormer denotes the modified stack as a function of input tokens X. The output Y_d is the state leaving the final block boundary, with d again denoting the number of blocks. In the full architecture that output includes the final DWA. The implementation in the paper follows the stack with final normalization and a linear prediction head that produces token scores.
The authors call the operation an average. Its definition is a learned linear combination. The coefficients can be signed, and the equation contains no normalization that forces them to sum to a specified value. A positive coefficient adds a scaled copy of an earlier representation. A negative coefficient subtracts a scaled copy. This freedom matters in the analysis because the authors find both signs on connections from the embedding.
A useful way to read the coefficients is as a triangular array. Each row belongs to a destination depth. The columns in that row identify the raw representations that can feed that destination, starting from the input embedding. The diagonal entry is the coefficient on the current block output. Earlier columns in the row provide direct connections from earlier depths. The triangle arises from the direction of the computation: a mixer can read outputs that have been computed by the time it runs.
Initialization and parameter count
DenseFormer begins with the ordinary flow through the stack. For each mixer the authors set the coefficient on the current block output to 1 and every other coefficient to 0. Accordingly, the mixture initially returns its current raw input unchanged. The coefficients are trainable, so learning can rescale that current input and bring in other states. Identity initialization gives the architecture familiar behavior at the starting point while still allowing the training objective to change the routing.
The additional parameter count comes entirely from the scalar coefficients. A row at depth i has i + 1 entries because it includes the input embedding and the raw output of every block through the current one.
Σⱼ₌₁ᵈ (j + 1) = d(d + 3) / 2
The summation sign Σ counts the coefficients over mixer depths j from 1 through d. Here j indexes a destination row, while d is the depth of the full DenseFormer. The term j + 1 counts the source states at that row. On the right, juxtaposition indicates multiplication, the parentheses group d + 3, and the slash denotes division. The equality gives the total scalar count for the full set of connections. For the typical depths discussed by the authors, under 100 blocks, they put the added count on the order of 10³ parameters.
Parameter count measures little of the work required to apply those parameters. A coefficient scales an entire activation tensor, the array with axes for batch items, token positions, and hidden features. Multiplying and adding many such arrays requires reading their values and writing the resulting mixture. Even when only a few scalar parameters are added to a row, each of their associated vectors or arrays can be large. The architecture thus separates the question of how many parameters it introduces from the question of how much time it takes to use them.
Choosing which depths can connect
Dilation reduces the number of sources read by each mixer. Starting from the current depth, a DWA with dilation k steps backward by k blocks at a time. The allowed source indices share a remainder with the destination index when divided by k. The current output always qualifies. The embedding qualifies in rows whose destination index is divisible by k, because the embedding occupies index 0.
Yᵢ := DWAᵈⁱˡᵃᵗᵉᵈᵢ({Xⱼ | j ≤ i, j ≡ i (mod k)})
Yᵢ is the state passed forward from depth i. The DWA symbol with the dilated label and subscript i denotes the scalar-weighted mixer for that destination, operating on the collection inside braces. Xⱼ denotes a raw state of index j, including the embedding at index 0. The vertical bar introduces the conditions on j. The symbol ≤ restricts the sources to the current depth or an earlier one, and ≡ together with mod k requires matching remainders under division by the positive dilation factor k. Each retained state is scaled by its coefficient for that destination and added to the mixture.
The sparsity is relative to the current depth. As the destination moves, the eligible class of sources can change. With dilation 4, the example in the paper has the mixer after block 4 use X₀ and X₄, and the mixer after block 8 use X₀, X₄, and X₈. A raw output outside the selected class can still affect a future mixture indirectly by being processed through intervening blocks. Dilation removes certain direct reads while preserving the ordinary path of computation through the stack.
Periodicity controls which destination depths have mixers. A period of p places DWA after blocks whose index is divisible by p. At all other depths, the raw block output is passed forward. The authors use the notation k×p to state the dilation and period in that order. Full DenseFormer has dilation and period 1, so it uses the entire available history at every block boundary.
Yᵢ := ⎧ DWAᵈⁱˡᵃᵗᵉᵈᵢ({Xⱼ | j ≤ i, j ≡ i (mod k)}) if p ∣ i
⎩ Xᵢ if p ∤ i
The brace on the right indicates two cases for the outgoing state Yᵢ at depth i. The symbol p stands for the DWA period. The relation p ∣ i means that p divides i, so the destination uses the dilated DWA and the set of eligible raw states specified by j, i, and k as above. The relation p ∤ i means that p does not divide i, so the outgoing state is Xᵢ, the raw result of block Bᵢ. The embedding, the calculation of raw block outputs, and the definition of the final outgoing state follow the same recurrence used for the full version.
1 / (kp)
This is the paper’s estimate of the fraction of full DWA computational overhead retained with both sparsity controls. The numeral 1 denotes the full reference amount, k is the dilation factor, p is the period, and kp is their product. The slash denotes division. The corresponding fractions for dilation or periodicity on its own are 1/k and 1/p. These expressions refer to the additional averaging work. The stack still runs all its Transformer blocks, and the exact amount of mixing work depends on which rows and sources are available at the finite depths of the architecture.
The two controls also determine how quickly a mixture can be reused. In the paper’s example with k = 4 and p = 4, Y₄ enters block 5 and affects its output X₅. The mixer after block 8 reads the states at depths 0, 4, and 8. It can receive the effects of Y₄ through X₈, after they have passed through blocks 5, 6, 7, and 8. The raw output X₅ sits outside that mixer’s dilation pattern. With k = 4 and p = 5, the next mixer has a direct connection to the raw state produced by the block immediately after the preceding mixer. The output of that block already reflects the preceding mixture. This example explains why two choices of period can differ in the routes they create as well as in how frequently they mix.
How the authors implement and train it
The paper gives a straightforward PyTorch implementation that keeps a list of the raw states and loops over the eligible entries to produce each mixture. A second implementation allocates storage in advance and collects the states into tensors, grouping depths for dilated access. This makes it possible to contract the coefficient vector against the history along the depth axis with a tensor operation. With that arrangement a forward pass can fill the history as blocks finish, then read the relevant portion for a mixer.
Writing into preallocated storage during a computation presents a bookkeeping issue for automatic differentiation. The backward calculation needs to associate a gradient with each state that contributed to a mixture. The authors provide a custom differentiation operation for the update. It exposes the newly filled portion of the accumulator and, during the backward pass, routes gradients to the last assigned value and the earlier portion as appropriate. The accompanying denseformer Python package contains the module that manages these operations between blocks. For a 48-block 4×5-DenseFormer, the appendix reports 674 ms per training iteration for the loop-based implementation and 657 ms for the optimized one.
The authors argue that retaining the history has modest memory implications because training already saves block activations for back-propagation. They also discuss reuse of stored information during autoregressive decoding, where a cache supports generation across successive tokens. The specific history required by the DWA equations is the set of raw block outputs used by the mixers. Its storage and movement are separate from the storage of the scalar parameters, and the implementation addresses them by accumulating representations as the forward pass proceeds.
The main training runs use OpenWebText2, an expanded version of OpenWebTextCorpus with around 17B tokens. Each batch has 400 sequences, each of length 256, and the main fixed-data comparisons run for 40k steps. The blocks use 8 attention heads with 64 dimensions per head and use rotary positional encoding to incorporate position. The optimizer is AdamW, with β₁ set to 0.9 and β₂ set to 0.95 for its moving estimates and a weight decay factor of 0.1. The authors use a learning rate of 0.001, a cosine learning-rate schedule, and a warmup during the opening 5% of steps. The DWA coefficients are learned during training together with the rest of the network, starting from the identity setting. A separate experiment changes when this learning is allowed to begin.
Experiments and results
What the comparisons hold fixed
The main experiments use perplexity to evaluate next-token prediction. It summarizes the probability assigned to the tokens that actually occur. Lower perplexity means the observed tokens received higher probability in aggregate. Depth and parameter count describe the size of the network doing that prediction, while training time and inference throughput describe different parts of its operating cost. A result about one of these quantities is easiest to interpret when the comparison specifies which other quantity has been matched.
The most direct architectural comparison is at the same depth. The baseline and DenseFormer have similar parameter counts because the additional weights in DenseFormer are scalars. With the same batches, sequence length, and number of training steps in the main OpenWebText2 runs, the comparison asks what adding the history connections achieves under similar parameter and data budgets. The extra DWA computation creates a difference in processing time even when depth is held fixed.
A second comparison matches inference throughput. The standard architecture can use more blocks within roughly the same time because it avoids the cost of DWA. This gives the baseline greater depth and capacity and asks which use of the inference budget produces lower perplexity. The complementary comparison matches perplexity. It asks how much depth and execution cost the standard stack requires to reach predictive quality similar to that of a shallower DenseFormer. Together these comparisons show why throughput at a fixed depth gives only one view of the tradeoff.
The training-time comparison instead gives the baseline more iterations. A standard stack can process training batches more quickly at the same depth, so the authors let it use that speed to see more examples in approximately equal time. The final baseline is an architectural control called Skips with Gains. It learns a scaling factor on each ordinary skip path before that path is summed with a transformation’s output. This gives the standard stack more control over the strength of its residual paths while preserving their local connectivity.
For the main OpenWebText2 results, inference speed is reported as batches processed per second, using batches of size 64. A higher rate means the system processed more of those fixed batches in the measured time. This batch size describes the inference measurement, while the main training batches contain 400 sequences. The main comparison reports means across three training runs with different seeds and supplies standard errors. These conditions matter when interpreting both close perplexity values and the operational meaning of the throughput ratios.
OpenWebText2 at similar inference throughput
The paper reports lower final perplexity for DenseFormer at the same depth as the standard architecture. The conclusion also holds in a comparison that lets the baseline spend the DWA overhead on more blocks. A 48-block DenseFormer without dilation and a 64-block standard Transformer have the same inference speed in this comparison. The DenseFormer reaches final OpenWebText2 perplexity of 17.84, and the standard Transformer reaches 17.94.
Final OpenWebText2 perplexity at matched inference speed
The shallower DenseFormer reaches lower perplexity than the deeper standard Transformer.
The numbers
| System or setting | Perplexity |
|---|---|
| 64-block standard Transformer | 17.94 |
| 48-block DenseFormer without dilation (this paper) | 17.84 |
This result answers a specific resource question. With the measured inference rate held fixed, the deeper baseline can perform more successive block transformations. The shallower system can spend part of its time combining earlier representations. The lower perplexity favors the second use of that budget in the comparison. The authors also find that sparse DWA configurations shift the tradeoff further by lowering the mixing cost while preserving much of the gain in perplexity.
The same-depth comparison makes the direction of the tradeoff clear. Among the 48-block systems in the efficiency figure, the standard Transformer provides the highest inference throughput and the highest perplexity. The full 1×1-DenseFormer provides the lowest perplexity and pays more in throughput. Intermediate choices of dilation and period offer operating points between these extremes. The relevant result for deployment is how much predictive quality can be retained as the added computation is reduced, alongside how each point compares with a standard stack of another depth.
OpenWebText2 at similar perplexity
A 48-block DenseFormer reaches roughly the final perplexity of a 72-block standard Transformer in the main experiments. The paper highlights the 48-block 4×5-DenseFormer as the practical comparison. It reaches similar perplexity to the 72-block baseline while running 1.4× as fast in the reported inference measurement. The authors also report that the 72-block baseline has a parameter count and memory footprint 45% larger than those of the 48-block DenseFormer in the comparison.
The parameter and speed comparisons answer related questions. Replacing some depth with a set of scalar-weighted routes leaves fewer Transformer blocks to store and run each time. Applying the routes still takes time, which is why the choice of dilation and period matters. The reported speed advantage is for the sparse variant compared with the deeper standard stack at similar predictive quality. In the same-depth figure, the ordinary stack retains a throughput advantage over the full DenseFormer. Both observations follow from the cost of a DWA and from the amount of depth required to reach the chosen perplexity.
The authors describe this as a better frontier of speed and perplexity. A frontier comparison considers whether another tested setting can improve one metric while maintaining the other. Dilation 4 with period 1 or 5 yields a more favorable set of operating points than using the full set of connections at every depth. Period 5 is the compromise emphasized for the main experiments. A reader choosing among the points would still need to decide whether the target is the best perplexity within a fixed depth, a particular throughput, or the least costly route to a given perplexity.
What changes when training time is held fixed
The main runs use 40k steps at a common batch size and sequence length. This keeps the amount of data processed comparable across the principal architectures. A natural follow-up is whether the standard Transformer can use the time saved by omitting DWA to train for longer and close the gap. To test that, the authors compare a 48-block 4×5-DenseFormer against a 48-block standard Transformer under approximately equal training time.
The DenseFormer trains for 40k steps, and the standard Transformer trains for 41.5k. Both use 2000 warmup steps in this comparison. The authors choose the baseline’s number of steps so that its training time is at least as long as DenseFormer’s, and the standard architecture sees more training batches as a result. For the training trajectory, the authors estimate perplexity on a small validation subset to limit the time spent evaluating it. The DenseFormer’s perplexity falls faster as a function of elapsed training time.
The final comparison evaluates perplexity on the full validation set. It favors DenseFormer in spite of the extra iterations given to the baseline. This gives the training claim a firmer basis than the trajectory alone. The subset makes it possible to follow progress during training, and the full validation set checks the final ordering. The comparison establishes a time-budget advantage for the particular depths, configurations, and schedule tested. The fixed-step runs separately show that the architecture can gain under equal exposure to training data.
A different corpus, longer sequences, and smaller batches
The authors repeat the comparison on PG-19, a collection of full-length Project Gutenberg books. They train both architectures for 48k steps with a batch size of 128, retaining the other stated OpenWebText2 training parameters. DenseFormer again has lower perplexity than the standard Transformer. This tests the generality of the architectural advantage across a different kind of text. The use of books as source material and the sequence length supplied to the network are distinct features of the experiment. The PG-19 comparison changes the corpus while keeping the other stated training settings, apart from the step and batch changes.
A separate experiment increases sequence length to 512 tokens and uses batches of 128 sequences. The 48-block standard Transformer reaches final perplexity of 18.28 ± 0.03. DenseFormer reaches 17.73 ± 0.02 in the paired comparison. This result shows that the observed gap persists in the longer-sequence run. The paper describes these as a limited set of experiments because of computation constraints. The result supports the comparison at the stated sequence length and batch size.
The appendix also revisits the OpenWebText2 comparisons with training batches of 128 instead of 400. Under the smaller-batch setup, the comparison highlights a 48-block 4×1-DenseFormer whose perplexity is comparable to that of a 90-block standard Transformer. In that pairing the 48-block system runs 1.6× as fast at inference. The authors find a larger perplexity gap between the architectures in the smaller-batch setting. They suggest that this could reflect greater robustness to gradient noise, the variation in the training update associated with the batch sampled at each step.
The smaller-batch comparison uses period 1 for the highlighted dilated DenseFormer. The authors expect a variant using period 5 to improve the tradeoff further. The demonstrated result is the speed and perplexity comparison with period 1. That distinction matters because period alters the actual connectivity of the stack, and its effects depend on the combination of period, dilation, and depth.
What the ablations show
Scaling a skip connection explains only part of the change
A full DWA has a learnable coefficient on the current block output as well as coefficients on earlier states. A benefit might therefore come from giving the network more freedom to rescale signals along the ordinary path. The Skips with Gains baseline tests this explanation by putting a learned gain into each ordinary skip connection. In the 48-block comparison, these gains give little improvement over the standard architecture. The corresponding DenseFormer improves perplexity more clearly.
The control distinguishes two changes that happen together in the proposed architecture. Rescaling a skip stream changes the relative contribution of a local residual path. Adding DWA also changes which previously computed representations a destination can read. The weak result with gains alone points toward the availability of earlier outputs as an important part of the improvement. The test leaves open which particular routes are most valuable, a question the authors address with several connection patterns and a pruning experiment.
The arrangement of sparse connections matters
The full coefficient array gives every mixer many possible sources. One way to reduce it is to keep only recent outputs and the embedding. The authors call this pattern Last K. They were motivated by the strong coefficients on nearby states and on the embedding in the full system. The experiment asks whether those visibly prominent routes account for most of the advantage when the network is trained with only that restricted set of direct inputs.
Another control, Connect to Last, uses one DWA after the final block. That mixer can combine outputs from across the stack just before prediction. This supplies depth-wide information at the end, but the preceding block computations follow the regular sequential route. In the distributed architecture, mixtures also become inputs to further Transformer blocks. A feature recovered from an early output can therefore be transformed again and enter later mixtures. The two arrangements differ in when that opportunity becomes available.
In the 48-block comparisons, both Last K and Connect to Last achieve smaller perplexity improvements than the favored sparse DenseFormer variants. The paper reports that 12×1-DenseFormer and 4×5-DenseFormer outperform the alternative patterns at sparsities of 92% and 95%, respectively. Here sparsity describes how much of the full DWA connection array is absent. These variants preserve selected longer routes throughout the stack even as they omit many of the possible reads. The appendix reproduces the alternative-pattern comparison with training batches of 128 and draws a similar conclusion.
The comparison supports a role for where direct links are placed. Last K concentrates them near the destination, and Connect to Last concentrates them at a single destination. Dilated or periodic DenseFormer distributes selected links among depths. A strong result from a highly sparse configuration shows that access along some of those distributed routes can suffice for much of the observed benefit. It also makes the coefficient map of the full network an incomplete guide to the best architecture to train. A sparse architecture learns all its representations with the chosen routes in place.
Dilation and periodicity trade off access against work
The authors vary dilation while keeping period equal to 1 for a 48-block setup. In the range of small dilation factors, up to 4 in the discussion of the main experiments, perplexity changes little, and throughput improves. At larger values, perplexity deteriorates more visibly and the speed gain starts to level off. In the appendix comparison, the 12-dilated configuration still outperforms the standard Transformer in perplexity. The speed plateau is reported near k = 4 for the 48-block comparison, with speed gains extending to larger dilation factors at greater depths.
Reducing the averaging work has more room to help when the undilated mixers have many sources to read. Once that work has been reduced, the block computations account for more of the total processing time. This is consistent with a plateau in end-to-end speed even though the connection pattern can be made sparser. The experiment also shows that the predictive cost of fewer links can become clearer at the same point where the returns in speed are diminishing.
A complementary comparison fixes dilation at 4 and varies the period in 48-block systems. The paper describes little effect on perplexity for p ≤ 5 in the main set of comparisons. It also reports a non-monotonic pattern, meaning that increasing the period can hurt or help perplexity depending on the particular value. The period determines where mixtures are inserted, and dilation determines which states those mixtures can see. Together they determine whether a state processed just after one mixer can enter another mixer directly. A period sweep thus changes the structure of information routes along with the frequency of averaging.
Even 4×20-DenseFormer remains ahead of the standard Transformer in perplexity in the appendix comparison. The result shows that some benefit survives infrequent mixing in that setting. The authors favor 4×5 as a compromise across speed and perplexity in the main tests. The non-monotonic sweep and the dependence of the speed plateau on depth both make the choice specific to the setup being examined.
Small learned coefficients can have a joint effect
Many coefficients in a trained full DenseFormer are small in magnitude. This suggests a different way to create sparsity: train the full network, then remove the weakest connections by absolute coefficient value before inference. The authors test this by progressively zeroing a portion of the smallest learned weights. Perplexity increases substantially beyond pruning 15% of the weights in the reported experiment.
That result concerns a network whose computations developed with the dense set of routes available. Removing many weak terms together can change the mixture enough to affect downstream states and predictions. The study measures the consequence of deleting groups of connections ranked by weight magnitude. It leaves the individual importance of each connection unresolved. In particular, the scalar magnitude by itself says little about the direction of the associated vector or how the subsequent blocks will respond when a set of contributions disappears.
The outcome fits with the success of architectures trained with greater prescribed sparsity. A network trained with dilation and periodicity has always computed under those restrictions. Its remaining coefficients and block transformations can adapt to that arrangement. A network pruned after training experiences a change in the signals reaching the blocks at inference. The paper uses these two comparisons to separate what can be learned with a restricted connection pattern from how much of a trained full system can be removed by a simple magnitude rule.
Recurring patterns in the learned weights
To study what the mixers learn, the authors draw the coefficient array as a heat map. A row corresponds to a destination mixer and a column to a possible source. A bright or dark band can therefore identify a group of routes that repeatedly receives coefficients of substantial magnitude. The full 48-block and 72-block systems yield similar patterns. The figures average over three seeds, and the authors report that the patterns are also consistent across individual runs.
The strongest recurring feature is the diagonal, the path from a block’s raw output to its own mixer. The nearest preceding blocks also receive substantial weight. These patterns preserve a prominent role for the current and recent states as the representations move through the stack. Direct access to distant states is added to a computation in which the sequential path continues to carry much of the signal.
The embedding column shows a different pattern. Earlier mixers give the embedded input substantial positive weight, while later mixers assign it negative weight. The embedding is special because it is the state produced before any of the blocks have transformed the sequence. Those coefficients show that the network learns to treat the original token representation differently across depths. Near the end of the stack, the authors also observe a group of late blocks whose mixers draw strongly on earlier outputs within that same group. This produces a triangular region near the lower end of the diagonal in the coefficient visualization.
Related structures appear when some of the connections are fixed to zero. The paper visualizes a 48-block system with dilation 4 and shows versions with periods 3, 4, and 5. The coarse outlines of the full pattern remain visible at the positions the sparse system is allowed to use. Comparisons with smaller training batches also recover similar patterns. Agreement across these conditions makes it less plausible that the broad shapes are idiosyncrasies of one training run. The visualization describes learned routing preferences, and the sparsity controls test what happens when the available routes are changed.
The connection to the input embedding
The authors examine cosine similarity between the vector leaving each mixer and that token’s input embedding. Cosine similarity compares vector directions, with greater similarity corresponding to closer alignment. This diagnostic looks at the resulting state after the terms in a DWA are added. It complements the coefficients, which describe how the states were combined but do not by themselves specify the direction of the sum.
In the full 48-block DenseFormer, the average similarity to the input embedding stays high in the early layers and declines substantially near the end. The 72-block analysis shows a similar trajectory. In the ordinary Transformer the similarity drops much earlier and stays low over the remaining layers. This gives the authors evidence that the DenseFormer stack retains a stronger directional relationship to the original embedding through more of its depth.
The authors interpret the late decline as a possible shift from working with the current token to preparing to predict its successor. A negative coefficient on the input embedding could reduce the embedding’s influence as part of that shift. The experiment measures similarity to the input, so the observed decline directly supports a claim about the relation to the current token’s original vector. The proposed function of the late states remains an interpretation. A vector can move away from the embedding for several reasons, and the diagnostic does not identify what information enables the next prediction.
When the mixing weights start to learn
The appendix tracks the heat map through training. In a 48-block DenseFormer, the coefficients already resemble their eventual pattern after 5000 iterations. At initialization, only the path from each current output is active. The emerging pattern shows that the extra routes begin to acquire a structure early in training, while the other block parameters are also learning how to process the mixtures.
A controlled comparison delays the point at which the coefficients become trainable. The authors hold them at their initial values for N iterations and then allow the whole system to learn through the remainder of the 40k-step run. The rest of the training schedule stays fixed. Increasing N reduces the benefit of the architecture. In that setup, learning the mixers alongside the blocks from the beginning is more effective than enabling the additional routes later.
The authors suggest that early updates may commit the rest of the network to a region of the training objective where the new routes are harder to exploit. They also suggest that a different learning-rate schedule could help. The fixed-schedule experiment establishes the disadvantage of delaying the coefficients under its own conditions. It leaves open whether changing the subsequent training procedure could enable a stronger conversion from an already trained standard Transformer.
What the parameter matrices show
The appendix compares the ranked singular values of several learned parameter matrices. Singular values describe how strongly a matrix can act along different directions and provide information about its effective use of dimensions. The analysis looks at the attention matrices, the feed-forward projections, and the embedding matrix. For the 48-block comparison the authors average across blocks where applicable, and the results are averaged over 3 seeds.
According to the authors, that analysis found no significant difference between the ranks of the two architectures. This narrows one potential explanation of the gain. The study finds lower perplexity and a different pattern of access to earlier activations, while the matrix spectra examined show similar behavior. Because the analysis concerns individual parameter matrices and averages across blocks, its scope is the measured spectra. The routing and representation comparisons address different properties of the computation.
Limitations
Limits the authors identify
The authors describe computation as a constraint on the breadth of the experiments. The longer-sequence test uses 512-token sequences and batches of 128 and covers a limited set of runs. They also identify efficient distributed training as future work, particularly finding a way to divide the DWA computation across multiple nodes. Each mixer may need a set of earlier activations, so partitioning the stack creates a question about where those activations are held and how a later stage reads them. The experiments establish the tradeoffs of the implementation they test, while the distributed version remains an open engineering problem.
The conclusion also leaves better sparsity patterns and implementations for further study. Dilation and periodicity are simple to specify, and the tested combinations offer favorable choices. The learned coefficient maps suggest that there may be other ways to preserve useful connections while spending less on averaging. The experiments with Last K, Connect to Last, and magnitude pruning cover concrete alternatives. They establish that some plausible restrictions sacrifice more perplexity than the favored patterns and leave the broader search space open.
The authors are explicit that their interpretation of the embedding analysis is a hypothesis. The observed mix of positive and negative coefficients and the depth profile of cosine similarity show how closely the states track the original input representation. The experiment does not trace the content of those states into particular correct predictions. Likewise, the delayed-training result motivates a hypothesis about the trajectory of optimization, and the authors leave the effect of a revised schedule to future work.
Limits visible in the evaluation
The predictive evidence centers on perplexity. This makes the central comparison precise because every system is evaluated on how much probability it assigns to observed next tokens. It provides only indirect evidence about qualities a reader might care about in generated text or about success on downstream tasks. The tests on OpenWebText2 and PG-19 show persistence across those corpora. The book corpus broadens the type of text represented in the evaluation, while the sequence-length experiment determines the longest explicitly tested training input in the reported comparison. Performance on much longer sequences remains open.
The numerical argument about parameter overhead is broader than the experiments because the count follows directly from the architecture. The count shows how many learned scalars a stack of a given depth would add. The empirical advantages in throughput, memory, and perplexity come from particular tested stacks. Extrapolating those advantages to far larger deployments would require measuring how tensor movement, storage, and distributed execution scale. A small coefficient array alone is insufficient to answer those questions.
The inference measure is throughput for batches of size 64. This supports a comparison for a workload that can make use of such batches. It leaves individual-request latency, behavior at other batch sizes, and speed in other decoding arrangements to be measured separately. The 1.4× and 1.6× figures belong to the specific comparisons against deeper standard Transformers at similar OpenWebText2 perplexity. The same-depth results make clear that DWA still imposes work. Operational results therefore depend on the depth and sparsity that are needed to hit a given perplexity target.
Memory also has several components. The reduced footprint reported against a deeper baseline is consistent with using fewer Transformer blocks to achieve similar quality. The paper’s argument about a negligible DWA memory overhead relies on access to activations being inexpensive in the implementation. The equations require raw block outputs at the depths a mixer reads. A claim about inference cache reuse depends on what representations a runtime actually retains and can expose to DWA. The availability of a cache and the availability of the particular raw tensors required by a mixer are separate questions for implementation.
Finally, the controls establish that connectivity matters in the tested configurations more clearly than they establish a single causal mechanism. Learned skip gains, recent-only connections, and final-only mixing recover less of the gain. Coefficient patterns recur, and pruning by magnitude damages prediction once enough terms are removed. Those findings support the role of distributed access to earlier outputs. They leave open how much of the benefit comes from preserving particular features, improving the way gradients move during training, or enabling computations that the ordinary stack learns less efficiently.
What came after
The follow-on record is open. The paper closes by proposing further work on sparsity patterns, faster implementations, and distributing DWA across nodes. It also raises the question of whether a different learning-rate schedule could help an already trained Transformer adapt to newly enabled depth connections. These directions carry forward two distinct questions raised by DenseFormer: how to make earlier representations cheap to access, and how to train the block transformations to take advantage of that access.
Cite
Cite as Matteo Pagliardini, Amirkeivan Mohtashami, François Fleuret and Martin Jaggi. 2024. DenseFormer: Enhancing Information Flow in Transformers via Depth Weighted Averaging. neural information processing systems.
@inproceedings{pagliardini2024denseformer,
title = {{DenseFormer: Enhancing Information Flow in Transformers via Depth Weighted Averaging}},
author = {Matteo Pagliardini, Amirkeivan Mohtashami, François Fleuret and Martin Jaggi},
booktitle = {neural information processing systems},
year = {2024},
doi = {10.52202/079017-4336},
eprint = {2402.02622},
archivePrefix = {arXiv},
url = {https://doi.org/10.52202/079017-4336}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/pagliardini-2024-denseformer-enhancing-information-flow-transformers/
References
- Brown, T. B., Mann, B., Ryder, N., Subbiah, M., Kaplan, J., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G., Askell, A., Agarwal, S., Herbert-Voss, A., Krueger, G., Henighan, T., Child, R., Ramesh, A., Ziegler, D. M., Wu, J., Winter, C., Hesse, C., Chen, M., Sigler, E., Litwin, M., Gray, S., Chess, B., Clark, J., Berner, C., McCandlish, S., Radford, A., Sutskever, I., and Amodei, D. Language Models are Few-Shot Learners, July 2020. URL http://arxiv.org/abs/2005.14165. arXiv:2005.14165 [cs]. our card
- Dao, T. Flashattention-2: Faster attention with better parallelism and work partitioning. CoRR, abs/2307.08691, 2023. our card
- Dao, T., Fu, D. Y., Ermon, S., Rudra, A., and Ré, C. Flashattention: Fast and memory-efficient exact attention with io-awareness. In NeurIPS, 2022. OpenAlex ↗ · Scholar ↗
- Devlin, J., Chang, M.-W., Lee, K., and Toutanova, K. Bert: Pre-training of deep bidirectional transformers for language understanding, 2019. our card
- ElNokrashy, M., AlKhamissi, B., and Diab, M. Depth-wise attention (dwatt): A layer fusion method for data-efficient classification. arXiv preprint arXiv:2209.15168, 2022. OpenAlex ↗ · Scholar ↗
- Fedus, W., Zoph, B., and Shazeer, N. Switch transformers: Scaling to trillion parameter models with simple and efficient sparsity. Journal of Machine Learning Research, 230 (120):0 1–39, 2022. OpenAlex ↗ · Scholar ↗
- Gao, L., Biderman, S., Black, S., Golding, L., Hoppe, T., Foster, C., Phang, J., He, H., Thite, A., Nabeshima, N., Presser, S., and Leahy, C. OpenWebText2 dataset, as part of `the Pile: An 800gb dataset of diverse text for language modeling`. arXiv preprint arXiv:2101.00027, 2020. our card
- Gokaslan, A. and Cohen, V. Openwebtext corpus. http://Skylion007.github.io/OpenWebTextCorpus, 2019. OpenAlex ↗ · Scholar ↗
- He, B. and Hofmann, T. Simplifying transformer blocks. CoRR, abs/2311.01906, 2023. OpenAlex ↗ · Scholar ↗
- He, K. and Sun, J. Convolutional neural networks at constrained time cost. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 5353–5360, 2015. OpenAlex ↗ · Scholar ↗
- He, K., Zhang, X., Ren, S., and Sun, J. Deep residual learning for image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 770–778, 2016. our card
- Huang, G., Liu, Z., van der Maaten, L., and Weinberger, K. Q. Densely connected convolutional networks. In CVPR, pp. 2261–2269. IEEE Computer Society, 2017. OpenAlex ↗ · Scholar ↗
- Katharopoulos, A., Vyas, A., Pappas, N., and Fleuret, F. Transformers are RNNs: Fast autoregressive transformers with linear attention. In Proceedings of the International Conference on Machine Learning (ICML), pp. 5294–5303, 2020. URL https://fleuret.org/papers/katharopoulos-et-al-icml2020.pdf. OpenAlex ↗ · Scholar ↗
- Kitaev, N., Kaiser, L., and Levskaya, A. Reformer: The efficient transformer. In ICLR. OpenReview.net, 2020. our card
- Liang, T., He, Z., Jiao, W., Wang, X., Wang, Y., Wang, R., Yang, Y., Tu, Z., and Shi, S. Encouraging divergent thinking in large language models through multi-agent debate. arXiv preprint arXiv:2305.19118, 2023. our card
- Loshchilov, I. and Hutter, F. Decoupled weight decay regularization. arXiv preprint arXiv:1711.05101, 2017. our card
- Madaan, A., Tandon, N., Gupta, P., Hallinan, S., Gao, L., Wiegreffe, S., Alon, U., Dziri, N., Prabhumoye, S., Yang, Y., et al. Self-refine: Iterative refinement with self-feedback. arXiv preprint arXiv:2303.17651, 2023. our card
- Mohtashami, A., Pagliardini, M., and Jaggi, M. Cotformer: More tokens with attention make up for less depth. In Workshop on Advancing Neural Network Training: Computational Efficiency, Scalability, and Resource Optimization (WANT@ NeurIPS 2023), 2023. OpenAlex ↗ · Scholar ↗
- OpenAI. GPT-4 Technical Report, March 2023. URL http://arxiv.org/abs/2303.08774. arXiv:2303.08774 [cs]. our card
- Paszke, A., Gross, S., Chintala, S., Chanan, G., Yang, E., DeVito, Z., Lin, Z., Desmaison, A., Antiga, L., and Lerer, A. Automatic differentiation in pytorch. 2017. OpenAlex ↗ · Scholar ↗
- Penedo, G., Malartic, Q., Hesslow, D., Cojocaru, R., Cappelli, A., Alobeidli, H., Pannier, B., Almazrouei, E., and Launay, J. The refinedweb dataset for falcon LLM: outperforming curated corpora with web data, and web data only. CoRR, abs/2306.01116, 2023. OpenAlex ↗ · Scholar ↗
- Petty, J., van Steenkiste, S., Dasgupta, I., Sha, F., Garrette, D., and Linzen, T. The impact of depth and width on transformer language model generalization. CoRR, abs/2310.19956, 2023a. OpenAlex ↗ · Scholar ↗
- Petty, J., van Steenkiste, S., Dasgupta, I., Sha, F., Garrette, D., and Linzen, T. The impact of depth and width on transformer language model generalization. arXiv preprint arXiv:2310.19956, 2023b. OpenAlex ↗ · Scholar ↗
- Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., and Sutskever, I. Language models are unsupervised multitask learners, 2019. OpenAlex ↗ · Scholar ↗
- Rae, J. W., Potapenko, A., Jayakumar, S. M., Hillier, C., and Lillicrap, T. P. Compressive transformers for long-range sequence modelling. In ICLR. OpenReview.net, 2020. our card
- Shazeer, N. Fast transformer decoding: One write-head is all you need. CoRR, abs/1911.02150, 2019. OpenAlex ↗ · Scholar ↗
- Shazeer, N. GLU variants improve transformer. CoRR, abs/2002.05202, 2020. OpenAlex ↗ · Scholar ↗
- Srivastava, R. K., Greff, K., and Schmidhuber, J. Highway networks. arXiv preprint arXiv:1505.00387, 2015. OpenAlex ↗ · Scholar ↗
- Su, J., Lu, Y., Pan, S., Wen, B., and Liu, Y. Roformer: Enhanced transformer with rotary position embedding. CoRR, abs/2104.09864, 2021. our card
- Touvron, H., Lavril, T., Izacard, G., Martinet, X., Lachaux, M.-A., Lacroix, T., Rozière, B., Goyal, N., Hambro, E., Azhar, F., Rodriguez, A., Joulin, A., Grave, E., and Lample, G. Llama: Open and efficient foundation language models, 2023a. our card
- Touvron, H., Martin, L., Stone, K., Albert, P., Almahairi, A., Babaei, Y., Bashlykov, N., Batra, S., Bhargava, P., Bhosale, S., Bikel, D., Blecher, L., Ferrer, C. C., Chen, M., Cucurull, G., Esiobu, D., Fernandes, J., Fu, J., Fu, W., Fuller, B., Gao, C., Goswami, V., Goyal, N., Hartshorn, A., Hosseini, S., Hou, R., Inan, H., Kardas, M., Kerkez, V., Khabsa, M., Kloumann, I., Korenev, A., Koura, P. S., Lachaux, M.-A., Lavril, T., Lee, J., Liskovich, D., Lu, Y., Mao, Y., Martinet, X., Mihaylov, T., Mishra, P., Molybog, I., Nie, Y., Poulton, A., Reizenstein, J., Rungta, R., Saladi, K., Schelten, A., Silva, R., Smith, E. M., Subramanian, R., Tan, X. E., Tang, B., Taylor, R., Williams, A., Kuan, J. X., Xu, P., Yan, Z., Zarov, I., Zhang, Y., Fan, A., Kambadur, M., Narang, S., Rodriguez, A., Stojnic, R., Edunov, S., and Scialom, T. Llama 2: Open foundation and fine-tuned chat models, 2023b. our card
- Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., and Polosukhin, I. Attention is all you need. CoRR, abs/1706.03762, 2017. URL http://arxiv.org/abs/1706.03762. our card
- Villalobos, P., Sevilla, J., Heim, L., Besiroglu, T., Hobbhahn, M., and Ho, A. Will we run out of data? an analysis of the limits of scaling datasets in machine learning. arXiv preprint arXiv:2211.04325, 2022. OpenAlex ↗ · Scholar ↗
- Wang, B. and Komatsuzaki, A. GPT-J-6B: A 6 Billion Parameter Autoregressive Language Model. https://github.com/kingoflolz/mesh-transformer-jax, May 2021. OpenAlex ↗ · Scholar ↗
- Wang, S., Li, B. Z., Khabsa, M., Fang, H., and Ma, H. Linformer: Self-attention with linear complexity. CoRR, abs/2006.04768, 2020. OpenAlex ↗ · Scholar ↗