Every PyTorch training loop ends with the same three lines: loss.backward(), clip_grad_norm_, optimizer.step(). Almost all performance work goes into the first one and the forward pass before it. I wanted to know what the other two cost. On an Apple M5 Pro, with the model compiled and the optimizer already fused, replacing them cut training time by 23.55% to 34.07%, and the weights came out bit for bit the same in every controlled check.
The project is called Cotangent[1]. It took six studies and 499 training runs to get here, and four of the six failed. This post is about the one idea that survived: you can batch the work that happens after backward, but only if you keep every floating-point addition in the order the framework already used. The whole method comes down to one reshape.
The gap in the step#
Start with a number. I trained a 3.35M-parameter byte-level transformer on PyTorch's Metal backend[2], compiled with torch.compile, with fused AdamW. One step took 12.93 ms. Then I changed nothing about the model, the forward pass or the backward pass. I only changed how the finished gradients were handled. The step took 9.88 ms.
Three milliseconds does not sound like much. It is 23.55% of the step. On the larger models in Figure 1 the removed part is 9.20 ms and 15.96 ms. All of that time went to computing one number and then using it.
The number is the global gradient norm. Gradient clipping[3] rescales the whole gradient when its length exceeds a threshold , which keeps one bad batch from throwing the weights across the room. Write for the gradient of parameter tensor , and for the number of tensors. PyTorch computes
and then multiplies every gradient by . In words: take the length of each tensor's gradient separately, take the length of that list of lengths, and shrink everything if the result is above . In my runs and . After that, AdamW[4] updates its two moment buffers and the weights.
This is the code path, simplified from torch.nn.utils.clip_grad_norm_[5]:
norms = [torch.linalg.vector_norm(g, 2.0) for g in grads] # one GPU launch per tensor
total = torch.linalg.vector_norm(torch.stack(norms), 2.0)
coef = torch.clamp(max_norm / (total + 1e-6), max=1.0)
for g in grads:
g.mul_(coef) # one more launch per tensor
optimizer.step()
The first line is the problem. My small transformer has 37 parameter tensors: two embeddings, four blocks of eight tensors each, a final norm and an output head. So the first line launches 37 separate reductions on the GPU to produce 37 scalars, which exist only to be combined into one scalar.
On CUDA, PyTorch has a multi-tensor path for this. On Metal it does not. The documentation says that for devices without foreach support, clipping will "silently fall back to the slow implementation"[5]. Forcing foreach=True on MPS raised an error on my pinned build, and that failed run is still in the repository.1I also called the private torch._foreach_norm directly. It runs on MPS. In a 120-step pilot it trained in 1.654 s against 1.683 s for the loop, mean of two seeds after 20 warmup steps. Under 2%. Fused AdamW does exist on MPS[6], and I used it in every baseline. Fusing the optimizer does not touch the 37 norms.
Counting launches#
Each of those norms is cheap arithmetic. A LayerNorm weight has 256 elements. What costs time is the launch itself: Python calls into the dispatcher, the dispatcher encodes a compute command, the command goes onto the Metal queue, a thread group spins up, reduces 256 numbers, and writes one float. Then the next one starts. The work is tiny and the ceremony is constant.
Now look at the lengths. Of the 37 tensors, 18 have 256 elements, 7 have 65,536, 4 have 196,608 and 8 have 262,144. Four distinct lengths. A transformer is the same block repeated, so its gradients come in a handful of sizes no matter how deep it is. If equal-length gradients could share a launch, 37 launches would become 4.
The counts in Figure 2 are read off the source, not a profiler. Natively the small model issues 80 device operations after backward: 37 norms, a stack, a final norm, three scalar operations for the coefficient, 37 in-place multiplies and one fused optimizer call over 37 tensors. Cotangent issues 16, and the optimizer sees one tensor.
So batch it. This is where I lost two studies.
Equal in math, different in bits#
The obvious batching is to concatenate all the gradients into one long vector and take one norm. Mathematically nothing changes:
The squared length of the long vector is the sum of the squared lengths of its pieces. One launch, same number. That was my second study. Training got faster and the study still failed its combined time and quality decision.
The identity above is true for real numbers. A GPU does not add real numbers. It adds 32-bit floats, and float addition is not associative[7]: the grouping of the additions changes the result. Here is the smallest example I know.
A float32 has 24 bits of significand. Once a running sum is times larger than the thing you add to it, the addition can do nothing. A sum of squares over 262,144 gradient entries is thousands of small additions into a growing total, and each one rounds. Change which entries meet first and you change which rounding errors happen. The answer moves in its last bits.
A parallel reduction makes the grouping explicit. The Metal kernel that PyTorch uses for a full-tensor norm[8] gives one output a group of up to 1,024 threads. Thread adds up elements into its own partial sum, and then the partial sums are combined. The number of threads decides which elements share an accumulator. You can try it.
These gaps look like nothing. The worst one is a few parts per million. Why did I care?
Two reasons. The first is that the clipping coefficient multiplies every gradient entry in the model. A last-bit change in becomes a last-bit change in all 3.35 million coordinates of the update, and training in BF16 autocast is a chaotic system: after a few hundred steps two runs that differed by one bit have different weights everywhere. The second reason matters more to me. Once the bits differ, I can no longer check my own work. If the fast path and the reference path produce different weights, I cannot tell a harmless reordering from a bug in my packing code. Bitwise equality is the only test that says yes or no.
I should be careful about what the failed study shows. I cannot say the flat norm caused its quality failure. A later repeat of the unchanged native baseline on the larger model, same seed and same code, moved its test score by 0.135652 bits per byte on its own, because MPS embedding backward accumulates with atomic float adds and is not repeatable from run to run. The noise floor was high, and I had built a method whose correctness I could only argue statistically. I wanted one I could verify.
The part I got wrong#
The fix seemed obvious. Keep one norm per tensor, as the native code does, and only batch the launches. Take the 18 gradients of length 256, stack them into an matrix, and ask for the norm of each row. Every row still gets its own reduction. Nothing is merged across tensors. I expected identical bits.
I got this, on the small transformer's real gradients:
| Path | Global norm (float32) | Bits |
|---|---|---|
| Native, 37 scalar norms | 11.430107116699219 | 0x4136e1b8 |
| Row-batched, 4 launches | 11.430102348327637 | 0x4136e1b3 |
Five ulp apart. The per-tensor norms already disagreed, by up to 1.9073486328125e-06, before the final reduction ever ran. That surprised me. A row of 256 numbers is a row of 256 numbers.
The answer was in the dispatcher[8]. On the PyTorch revision I had pinned, the MPS norm entry point checks three things before choosing a kernel: is this an L1 or L2 norm, is there more than one output element, and is exactly one axis being reduced, the innermost one. If all three hold, it takes a fast path with a different kernel, norm_l2_reduction_inner. That kernel uses 256-thread groups and, by my reading of the source, shares each group across eight rows. A scalar norm fails the test because it has one output, so it runs the generic kernel with up to 1,024 threads to itself. Same row, same 256 numbers, different threads, different partial sums.
So batching rows the natural way silently switches kernels. Nothing in the Python API tells you. The shapes are valid and the values are right to seven digits.
The bucket view#
The fast path wants exactly one reduced axis. So give it two.
Take a bucket of gradients with elements each. Stack them to as before, then view the same memory as and reduce over the last two axes. The output still has elements, one norm per gradient. But now two axes are being reduced, the fast-path test fails, and the dispatcher falls through to the generic kernel. That is the kernel a scalar norm uses.
matrix = torch.stack([grads[i].reshape(-1) for i in bucket]) # B x K
b, k = matrix.shape
norms = torch.linalg.vector_norm(matrix.reshape(b, k // 2, 2), 2.0, dim=(1, 2))
Running the same kernel is necessary. It is not sufficient. The additions inside also have to happen in the same order, and here the generic kernel is kind. It assigns one thread group per output element, with threads, exactly as it would for a lone tensor of elements. And it walks the reduced axes in linear order. For the view index , with counting pairs and , the element sits at
Element of gradient is at position of row . The reshape moved nothing. Thread of group reads elements of its own row, which is what thread would have read if that gradient had been launched alone. The pairing into twos is a fiction for the dispatcher. The arithmetic never sees it.
Two details finish the job. A length that is odd or shorter than 4 cannot form two nontrivial axes, so those tensors fall back to individual scalar norms. And bucketing reorders the tensors, so the norms from each bucket are written back to their original positions before the final norm over all of them. That last reduction is a float sum too.
The argument rests on one file in one PyTorch revision, so I did not trust it until the device agreed. I swept 32 lengths, bucket sizes of 1, 3 and 8, and three dtypes: 288 norms, all bitwise equal to the native ones. Then full models: 128 checks across four architectures, two precisions, four handling variants and four consecutive updates, comparing losses, gradients, norms, parameters and both AdamW moment buffers. All equal.2These checks swap in a deterministic embedding backward for both sides. MPS's own embedding backward is not repeatable between runs, which would hide any difference I was looking for. The timed runs keep the native one.
Packing the optimizer#
The second half of the method is simpler. Before the first forward pass, every parameter is re-pointed at a slice of one long master vector. Autograd does not know. It still produces 37 separate gradients. After backward I concatenate them once, multiply the single vector by , and hand fused AdamW one tensor in place of 37.
This is safe because AdamW never looks sideways. Its moment updates,
act on each coordinate alone, and so does the weight update built from them. Lay the coordinates end to end in any fixed order and every one of them goes through the same arithmetic it would have gone through in its own tensor. No sums across coordinates, so no reordering to worry about. The conditions are narrow: one hyperparameter group, dense gradients for every parameter, nothing frozen. The code refuses anything else.
Which half matters#
I had two changes and one speedup. I wanted to know how the credit splits, so I ran the full 2×2: scalar or bucketed norms, crossed with native or packed layout, on the small transformer in eager mode. Eight seeds, 800 steps per cell, with the run order rotated so each cell sat in each position twice.
Norm batching alone removed 15.92% of training time. Packing alone removed 2.16%. Together, 17.86%. The interaction is 0.22% with a 99% interval of −0.65% to 1.08%, so the two changes add up and neither needs the other.
I expected packing to matter more than that. It removes 37 multiplies and shrinks the optimizer call from 37 tensors to one. But fused AdamW was already doing its job, and an in-place multiply is a cheap launch. The norm reductions are the expensive ones.
Why would a norm cost so much more than a multiply? Launch count alone does not explain it. In Figure 1 the medium transformer has 53 tensors against the small model's 37, but it saves 15.96 ms per step against 3.04 ms. That is five times the saving for 1.4 times the launches. My reading of the kernel is that the scalar path is also badly parallelized for large tensors. One output element gets one thread group of at most 1,024 threads. For a 1,048,576-element weight matrix that is 1,024 threads each walking 1,024 elements in a serial loop, and the native path runs 53 such reductions one after another. A bucket of twelve of those matrices gets twelve thread groups in a single launch. I have not profiled inside the kernel, so treat this paragraph as a hypothesis that fits the timings.
Against a compiled baseline#
Then the result that stung. When I screened stronger baselines for the extension study, plain torch.compile with TorchInductor[9] and unchanged native handling beat my method. On the small model's pilot, compiled native training took 1.227 s for 100 warmed steps. Eager Cotangent took 1.337 s. A flag I had not been using was worth more than three studies of work.
So the eager comparison was the wrong one to headline. The right question is whether gradient handling still matters once the model is compiled. Compilation covers the forward and backward graph. Clipping and the optimizer step sit outside it in both setups. I gave both sides the same compiled model, with full-graph capture and static shapes, and changed only what happens after backward. Twelve seed pairs per model, 1,200 steps each, six pairs in each run order.
The relative saving is larger with compilation than without, and the reason is plain arithmetic. On the small transformer the eager step went from 17.54 ms to 14.41 ms, a saving of 3.13 ms. The compiled step went from 12.93 ms to 9.88 ms, a saving of 3.04 ms. Same three milliseconds. The compiler shrank everything around the gradient handling and left the handling alone, so its share of the step went up. Speed up the forward and backward pass and the part nobody optimized becomes the bottleneck.
| Model | Tensors / buckets | Baseline (s) | Cotangent (s) | Reduction | 99% CI |
|---|---|---|---|---|---|
| Small transformer, 3.35M | 37 / 4 | 15.51 | 11.86 | 23.55% | 22.97 to 24.13 |
| Medium transformer, 19.28M | 53 / 5 | 56.32 | 37.16 | 34.07% | 32.87 to 35.26 |
| Gated GQA decoder, 9.74M | 52 / 4 | 35.03 | 23.99 | 31.55% | 30.73 to 32.37 |
| Causal convolution, 3.75M | 53 / 4 | 17.24 | 12.54 | 27.30% | 26.95 to 27.64 |
All 48 pairs were faster with Cotangent. Counting setup, evaluation and checkpoint writing, total completion time dropped by 17.89% to 28.73%. The compiled paths were checked too: 16 controlled comparisons with matched deterministic derivatives, all matching in losses, gradients, norms and parameter hashes.
What I have not shown#
The speed result is clean. The quality result is not, and the two should not be confused.
In the controlled checks the method produces the same bits as native handling. In the timed runs it cannot, because those runs keep MPS's native embedding backward, which is not repeatable. So the trained models differ between the two sides, as they would between two runs of the same side, and the only question left is statistical: is one side worse on average?
For the small transformer in eager mode, I have a real answer. An earlier study failed this test narrowly, with an upper bound of 0.01160035 bits per byte against a tolerance of 0.01 that I had fixed in advance. I did not move the tolerance. I froze a replication of the unchanged method with 100 fresh seed pairs, 200 runs of 2,000 steps. It passed: time to a fixed validation target fell by 15.03% (99.5% interval 13.50% to 16.56%), and the test-set difference was 0.00138 bits per byte with an upper bound of 0.00728. Fifty of the 100 pairs came out worse for Cotangent, which is what a coin does.
The compiled extension in Figure 7 has twelve pairs per model, and twelve is not enough. For three of the four models the 99% interval on the quality difference extends above 0.01. For two of them I read that as width: the small transformer's mean is +0.00365 and the medium transformer's is −0.01382, with intervals that comfortably include zero. The gated GQA decoder is different. Its mean is +0.02723 bits per byte, and Cotangent had the worse test score in 10 of 12 pairs. The interval still includes zero, at −0.00819 to +0.06264. But ten of twelve is not a pattern I am willing to call noise, and the arithmetic checks, which pass for this model, do not explain it. The causal convolution sits at the other extreme, with a mean difference of −0.000003 and an upper bound of 0.00005.
So under compilation the quality interval sits inside the tolerance for one model of four, and it is open for the other three. I do not know why the GQA runs lean the way they do.
The other limits are easier to state.
- One machine. Every number here comes from a single Apple M5 Pro with 24 GiB of memory, PyTorch 2.14.1, one pinned source revision. I have no CUDA measurements. CUDA already has multi-tensor norm kernels[10], so I would expect much less to gain there.
- The equivalence is tied to a kernel. The bucket view works because of how one dispatcher function is written today. A PyTorch update could add a fast path for two-axis reductions and the bits would move. The checks have to be rerun on every version.
- Memory went up for the small models. Peak sampled Metal driver allocation rose from 219 MiB to 1,075 MiB on the small transformer and from 180 MiB to 1,068 MiB on the convolution. The stacked buckets and the concatenated gradient are extra copies. On the two larger models the peaks were within 6% of each other.
- Every step synchronizes the device so the timings are honest. A production loop that queues work asynchronously may see a different split.
- Small models, small batches. Batch size 8, sequence length 256, at most 19.28M parameters. As matrix products grow, the fraction of time spent after backward should shrink.
What I would do next#
Three things, in order.
First, the GQA question. The clean experiment is to rerun those twelve pairs with deterministic embedding derivatives on both sides. If the method is arithmetically identical under compilation, as the controlled checks say, the two sides will produce the same weights and the difference will be exactly zero. If it is not zero, there is a bug or a compiler interaction I have not found, and I would much prefer to find it myself.
Second, a different machine. The extension cost 128 runs and about 63 minutes of machine time, setup and evaluation included. Repeating it on another Apple chip and another PyTorch release is cheap and would say whether this is a property of Metal or of my laptop.
Third, the fix belongs upstream. The bucket view is a workaround for a missing feature: a multi-tensor norm on MPS that keeps the scalar kernel's arithmetic. With that in the backend, clip_grad_norm_ would be fast for everyone and nobody would need to trick a dispatcher with a reshape. There is serious work on summation that gives the same bits in any order[11], and that would be the principled version. I took the cheap route and kept the order the backend already had.
The GQA rerun comes first. Until it is done, the claim I stand behind is the narrow one: on this machine, the time after backward was a quarter to a third of a compiled step, and most of it was 37 small reductions that could have been 4.
Notes on method#
Timing. Per-step times in Figures 1 and 6 are the mean training seconds per run divided by the step count (1,200 for the compiled comparison, 800 for the ablation). Reductions are means of per-pair values , not ratios of mean times. Intervals are paired Student-t at 99%, descriptive per comparison, with no correction across comparisons. Compiler caches were warm.
Operation counts. Figure 2 counts tensor operations issued by the handler after backward, read from research/v6/methods.py. Native: norms, one stack, one final norm, three scalar operations, multiplies, one fused step. Cotangent with buckets: stacks, norms, one stack, one final norm, three scalar operations, one concatenation, one multiply, one fused step. These are operation counts, not measured Metal command counts.
Figure 4. Values are float32 draws with standard deviation 0.01. Squares and sums are rounded to float32 with Math.fround. Lanes are combined in groups of 32, left to right, repeating until one value is left, which mirrors the structure of the generic kernel. The GPU's order inside a 32-wide group is not specified, so the exact bits on a device can differ from the browser's.
Models and data. All four models predict bytes on a pinned serialization of WikiText-2, trained from scratch with FP32 weights and BF16 autocast, AdamW at peak learning rate , , , weight decay 0.1. The test split was seen during development, so quality numbers are regression checks, not generalization claims.
The record. Six studies: sampled gradients (36 runs, failed), packing with a flat norm (24, failed), deterministic embedding derivatives with a flat norm (41, failed), bucketed norms (70, failed on quality uncertainty), the 100-pair replication (200, passed), and the extension described here (128, descriptive). Every run, including the failures, is in the repository.
References#
- A. Vahedian. Cotangent: Preserving Reduction Arithmetic in Batched Gradient Handling. Technical report, October 2026. PDF, code and records
- PyTorch contributors. MPS backend. PyTorch documentation. docs.pytorch.org/docs/stable/notes/mps.html
- R. Pascanu, T. Mikolov, Y. Bengio. On the difficulty of training recurrent neural networks. ICML, 2013. arXiv:1211.5063
- I. Loshchilov, F. Hutter. Decoupled Weight Decay Regularization. ICLR, 2019. arXiv:1711.05101
- PyTorch contributors. torch.nn.utils.clip_grad_norm_. PyTorch documentation. docs.pytorch.org
- PyTorch contributors. torch.optim.AdamW (the
foreachandfusedoptions). PyTorch documentation. docs.pytorch.org - D. Goldberg. What Every Computer Scientist Should Know About Floating-Point Arithmetic. ACM Computing Surveys 23(1), 1991. doi:10.1145/103162.103163
- PyTorch contributors. MPS reduction operations, revision 5c48869: the norm dispatcher in ReduceOps.mm and the kernels in ReduceOps.metal
- J. Ansel, E. Yang, H. He, et al. PyTorch 2: Faster Machine Learning Through Dynamic Python Bytecode Transformation and Graph Compilation. ASPLOS, 2024. doi:10.1145/3620665.3640366
- NVIDIA Apex contributors. Multi-tensor L2 norm kernel. github.com/NVIDIA/apex
- W. Ahrens, J. Demmel, H. D. Nguyen. Algorithms for Efficient Reproducible Floating Point Summation. ACM Transactions on Mathematical Software 46(3), 2020. doi:10.1145/3389360