Token Efficiency: Optimizer Tradeoffs and Long-Context Practices

    This article explains how to define and measure token efficiency, what optimizer changes cost in memory and communication, and how to choose attention schemes for long contexts. It also provides implementation notes and validation checks for putting these ideas into practice.

    With limited high-quality data available, model quality increasingly depends on how well each token is utilized. This article focuses on three areas: how to define and calculate token efficiency, what tradeoffs optimizer changes introduce, and what validation checks apply to long-context attention and reward design.

    1. Define Token Efficiency Clearly

    Token efficiency refers to the amount of data a system saves relative to a baseline while achieving the same result. Let $D{base}$ be the number of baseline training tokens needed to reach a target loss $L^*$, and let $D{new}$ be the number of tokens needed to reach the same loss with a new method. Then

    $\eta = \frac{D{base}}{D{new}}$

    When $\eta = 2$, the new method reaches the same loss with half the data. If the total amount of available high-quality data is $D{max}$, the efficiency gain is roughly equivalent to expanding the effective data volume to about $\eta \cdot D{max}$.

    This conversion holds only within a certain range. Repeated training on the same data leads to overfitting, and the benefit diminishes as $\eta$ increases. In addition, $\eta$ usually needs to be measured on the same data distribution and the same evaluation set; conclusions may change with a different dataset. To determine whether a method truly improves token efficiency, record three things together: the loss curves of the baseline and the new method at the same number of steps, the number of tokens required to reach the same loss, and downstream task metrics.

    The total amount of available high-quality data should not be estimated by intuition alone. A 2022 study by Epoch AI (Villalobos et al.) estimated that the stock of high-quality text is about 4.6 trillion to 17 trillion tokens, depending on the specific corpus and filtering criteria. When planning training, use actual statistics from your own corpus.

    2. Optimizers: Tradeoffs Between Gains, Memory, and Communication

    Most large models still use first-order adaptive optimizers such as AdamW, which maintains two states per parameter: the first moment and the second moment. In recent years, a class of matrix-aware optimizers has attracted attention, represented by methods that approximately orthogonalize momentum. They approximately project the update matrix of each two-dimensional weight onto an orthogonal matrix so that update magnitudes are more uniform across directions. Strictly speaking, these methods use matrix-level preconditioning and do not use full second-derivative information, so calling them “second-order” is not accurate.

    The table below compares typical differences between the two.

    Dimension AdamW (first-order adaptive) Approximate orthogonalization optimizer (matrix-aware)
    Extra state per parameter Two states (first moment, second moment) Usually one momentum, plus a temporary matrix during iteration
    Scope All parameters Usually only two-dimensional weights; biases and normalization parameters still use AdamW
    Communication Gradient all-reduce under data parallelism Also requires gradient synchronization; if states are sharded, parameters must also be broadcast
    Convergence Mature empirical behavior; hyperparameters can often be reused Some reports show fewer steps, but results depend on implementation, learning rate, and iteration count
    Main risk Stable baseline Learning rate needs separate search; loss spikes may appear early in training
    Suitable scenarios General purpose, suitable for quick starts Training dominated by large weight matrices, with enough budget for tuning

    Below is an illustrative sharded implementation. The momentum for each parameter is stored on only one rank. After that rank updates the parameter, it broadcasts the full parameter to the other ranks. This reduces momentum memory to about $1/N$ of the original ($N$ is the number of ranks), at the cost of broadcasting the full parameter every step.

    1. import torch
    2. import torch.distributed as dist
    3. class ShardedOrthogonalOptimizer:
    4. """Illustrative code: each parameter keeps momentum on only one rank, then broadcasts after update."""
    5. def __init__(self, params, lr=1e-3, momentum=0.95, ns_steps=5):
    6. self.params = list(params)
    7. self.lr = lr
    8. self.momentum = momentum
    9. self.ns_steps = ns_steps
    10. self.rank = dist.get_rank()
    11. self.world_size = dist.get_world_size()
    12. # Assign parameters to ranks in round-robin order; all ranks must use the same parameter order.
    13. self.owner = [i % self.world_size for i in range(len(self.params))]
    14. # Store momentum only for parameters owned by this rank.
    15. self.buffers = {
    16. i: torch.zeros_like(p)
    17. for i, p in enumerate(self.params)
    18. if self.owner[i] == self.rank
    19. }
    20. def _orthogonalize(self, m):
    21. if m.dim() != 2:
    22. # Simplified handling for illustration; in practice, one-dimensional parameters should use AdamW.
    23. return m / (m.norm() + 1e-8)
    24. # Normalize first so the spectral norm does not exceed 1, allowing Newton-Schulz iteration to converge.
    25. x = m / (m.norm() + 1e-8)
    26. for _ in range(self.ns_steps):
    27. x = 1.5 * x - 0.5 * x @ x.t() @ x
    28. return x
    29. @torch.no_grad()
    30. def step(self):
    31. for i, p in enumerate(self.params):
    32. owner = self.owner[i]
    33. if self.rank == owner and p.grad is not None:
    34. buf = self.buffers[i]
    35. buf.mul_(self.momentum).add_(p.grad)
    36. p.add_(self._orthogonalize(buf), alpha=-self.lr)
    37. # All ranks must call this in the same order; otherwise broadcast will deadlock.
    38. dist.broadcast(p, src=owner)

    Prerequisites for running the code:

    • dist.init_process_group has already been called. In a GPU environment, use the NCCL backend and launch with something like torchrun --nproc_per_node=8 train.py.
    • All ranks start with identical parameters, either by using the same random seed or by broadcasting from rank 0.
    • Before calling step(), gradients have been averaged across data-parallel ranks. DDP does this automatically; for manual training, use dist.all_reduce(p.grad, op=dist.ReduceOp.AVG).
    • All ranks iterate over parameters in the same order.

    This example is simplified. Before production use, two improvements are needed. First, parameters are assigned in round-robin order without considering the difference in element count between large matrices and small parameters; assignment should instead be greedy by element count. Second, each parameter is broadcast separately, resulting in many communication calls; parameters should be combined into buckets before broadcasting.

    3. Long Context: Choose Attention Schemes by Complexity

    For million-token contexts, the main bottleneck is usually not attention computation but KV cache memory. Consider a model with 32 layers, 8 KV heads, 128 dimensions per head, and fp16. The KV cache per token is $2 \times 32 \times 8 \times 128 \times 2 = 131072$ bytes, or about 128 KB. For one million input tokens, the KV cache alone requires about 131 GB, before accounting for model weights.

    The table below compares four common approaches.

    Approach Computation time Extra memory Accuracy
    Standard attention $O(N^2 d)$ Materializes an $N \times N$ score matrix, $O(N^2)$ Exact
    Blockwise computation with online softmax (FlashAttention-style) Still $O(N^2 d)$ Does not materialize the score matrix; extra memory about $O(N)$ Exact, with error within floating-point range
    Sliding-window attention (window size $w$) $O(N w d)$ About $O(N w)$ Approximate; information outside the window is lost
    Linear attention $O(N d^2)$ Fixed-size state, $O(d^2)$ Approximate; long-range retrieval often becomes weaker

    FlashAttention saves memory and memory traffic; it does not reduce the number of floating-point operations. Describing it as “reducing space complexity to $O(N)$” may lead readers to mistakenly believe that computation also scales linearly, which is incorrect.

    When choosing an approach, use the following order. If the task requires exact results and the sequence length is within hundreds of thousands of tokens, prefer blockwise exact attention. Beyond that length, consider approximate approaches such as sliding windows plus a small number of global layers, and validate effectiveness with retrieval tests.

    Before deploying an approximate approach, at a minimum run retrieval tests at multiple lengths such as 4K, 32K, and 128K and measure accuracy.