Repository navigation
Conversation
The attention residual held two FP32 [T, N + 1, D] intermediates per call, the upcast values and the normalized keys, for the whole forward. At the real model's shape that is 1008 MiB for one call. Save the scores, the inverse RMS and the softmax weights instead, none of which carry a hidden-size factor, and recompute the rest in backward. The score weight is the product of the norm weight and the projection weight, and both factors are upcast before multiplying so a bfloat16 parameter does not round the product.
The depth weights come from a softmax over per-source scores, and the score weight is the product of the norm weight and the residual projection. With the projection drawn from trunc_normal the initial depth weights are arbitrary. The report requires them to be uniform at initialisation for training stability, so initialise the three residual projections to zero. At zero the aggregation returns the mean of its sources exactly. The projection still receives a gradient; the norm weight does not, since it reaches the loss only through its product with the projection, and it gains one as soon as the projection leaves zero. Both are covered by tests.
|
|
|
@claude It's not clear to me what problem this PR is solving. Could you explain using simple terms? Also, since the autograd function uses many small ops, I would doubt about the performance. Maybe we should use something like https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/attnres/fused.py as a fused op, e.g. through the override mechanism in the repo. |
|
Claude finished @tianyu-l's task in 1m 38s —— View job What this PR fixesBackground. Kimi K3 doesn't use a plain residual ( The PR bundles two unrelated changes:
In short, the goal is lower peak memory for this one op. It does not change results beyond about 1 bf16 ulp. On performance: I agree with your concern
The op is memory-bound and does a small reduction over depth for each token. The right kernel makes one pass over the How to route it through the override mechanism
A cheaper option to measure first: Recommendation
No code changes were made. |
|
|
||
| values_TND = torch.cat((block_residual_TND, prefix_sum_TD.unsqueeze(1)), dim=1) | ||
| values_float = values_TND.float() | ||
| variance = values_float.pow(2).mean(dim=-1, keepdim=True) | ||
| keys_TND = values_float * torch.rsqrt(variance + norm.eps) | ||
| score_weight_D = norm.weight.float() * projection.weight.squeeze(0).float() | ||
| scores_TN = (keys_TND * score_weight_D).sum(dim=-1) | ||
| probs_T1N = torch.softmax(scores_TN, dim=-1).unsqueeze(1) | ||
| output_TD = torch.matmul(probs_T1N, values_float).squeeze(1) | ||
| return output_TD.to(values_TND.dtype) |
There was a problem hiding this comment.
after reading claude's analysis, I would suggest:
- fix the init in its own PR
- use torch_remat to solve the recomputation issue, as we are migrating from torch.utils.checkpoint to torch_remat (cc @anijain2305 ), instead of introducing an autograd function
- make
_apply_attention_residuala configurable function (https://github.com/pytorch/torchtitan/blob/main/torchtitan/config/function.py#L16), with this reference impl as default, but maybe use torch.compiled version (or even call / copy FLAs' fused impl) as override https://github.com/pytorch/torchtitan/tree/main/torchtitan/overrides (can leave to @acisseJZhong)
There was a problem hiding this comment.
Could you tell me "with this reference impl as default" refer to the original eager implementation (I suspect this one) or the new autograd.Function version ?
And we don't need the autograd.Function in current PR but due to performance concern (too many small OPs) in this commit, want to know the torch.compiled version is coming from which place (optimizing the current autograd.Function version impl ?)
If the entire point 3 is handled together, happy to leave it to Jessica @acisseJZhong
I think the recomputation issue seems have been addressed in #4656 , but anyway these 2 PRs need to be considered together, I will address @shuhuayu 's comment in the #4656 and LMK if any combined plan on these 2 together, thanks!
|
closing this PR since the zero init and activation checkpointing of attn res is splitted away to #4881 and #4656 autograd.Function with bunch of small op is concerning in performance, hence not proceed the compile part saw: felipemello1#109 and will be handled by meta maintainers |
Initialize Kimi K3's attention residual projections to zero, as Section 5 of the Attention Residuals technical report requires, so the depth softmax starts uniform and each residual starts as an equal-weight average of its sources. - `torchtitan/models/kimi_k3/__init__.py`: `attention_res_proj`, `ffn_res_proj` and `output_res_proj` take `nn.init.zeros_` instead of `trunc_normal_` at std 0.02. - `tests/unit_tests/cpu/test_kimi_k3_attention_residual_init.py`: the projections are zero initialized; at zero the aggregation returns the mean of its sources; the projection still gets a gradient and the norm weight does not. Split out of #4780, as suggested there. ## Test plan - The three projections of the debug model take `nn.init.zeros_`, and at zero the aggregation returns the mean of its sources (checked locally).
Summary
Two independent corrections to Kimi K3's attention residual, both in the aggregation that #4025 introduced and both unrelated to parallelism.
The pseudo-query initialisation does not match the report. Section 5 of the Kimi Linear tech report states that all pseudo-query vectors must be initialised to zero, which is what makes the depth softmax start uniform and the residual reduce to a standard residual at step 0. The three residual projections are built with
trunc_normal_at std 0.02 instead.The aggregation retains more than it needs.
_apply_attention_residualkeeps two FP32[T, N + 1, D]intermediates alive until backward, the upcast values and the normalized keys. With activation checkpointing on, which is the default, they are rebuilt during recompute as well, so they set the backward peak.torchtitan/models/kimi_k3/__init__.py: the three residual projections initialise to zero.torchtitan/models/kimi_k3/model.py:_AttentionResidualAggregation, registered as a local autograd Function for SPMD type checking;_apply_attention_residualkeeps its signature and becomes a thin call into it.tests/unit_tests/cpu/test_kimi_k3_attention_residual.py: the aggregation against a plain autograd reference, a bfloat16 precision case, the registration, and the initialisation.Design
The forward unbinds the block stack into per-source views, computes each source's inverse RMS and its score against the query, and forms the depth softmax from those. It saves the score weight, the norm weight, the softmax weights, the scores, the inverse RMS and references to the two inputs. None of the saved statistics carries a hidden-size factor. The backward recomputes one FP32 upcast per source and applies the softmax Jacobian, the score path and the variance path explicitly, accumulating the query gradient as a GEMV per source so the reduction order is fixed.
Both factors of the score weight are upcast before multiplying. Multiplying them in bfloat16 and upcasting the product moves the output by about half a percent at a realistic logit scale, which is larger than the reordering this change introduces.
The Function is registered with
register_local_autograd_function. It runs no collective, leaves the token dimension alone, and reduces over the stack and hidden axes, neither of which is sharded; the two parameters are declared TP unsharded. Without the registration the type checker raises in strict mode, which the multimodal cell runs under.At zero initialisation the scores are zero, the depth softmax is uniform, and the aggregation returns the mean of its sources. The projection still receives a gradient and moves off zero on the first step; the norm weight reaches the loss only through its product with the projection, so it gains one once the projection is nonzero.
Compilation
Nothing here interacts with
torch.compile, and the custom Function does not stand in its way.parallelize_kimi_k3callstorch.compilenowhere today, so this path does not exist for Kimi K3 as the tree stands. The change touchesmodel.py, the model's__init__.pyand one test file, none of which is compile related. The Kimi K3 model carries nocompile_with_inductorannotation either, so the regional inductor backend indistributed/compile.pyhas no region near the aggregation to lower.If per-block compilation is turned on later it arrives as
transformer_block.compile(backend=backend, fullgraph=True), where a graph break is an error rather than a fallback. Checked withtorch._dynamo.explainon the aggregation itself, the Function traces into one graph with no break, and the op count drops from 8 to 2. That is the aggregation in isolation rather than a whole block underfullgraph=True, which cannot be run here while the model does not compile.Relation to #4656
The two touch the same function from opposite sides and compose. #4656 wraps
_apply_attention_residualin a checkpoint or, under RegionAC, declares it as a named region whose output the save policy may keep instead of replaying. This change rewrites the body of that function. All four combinations run.They are complementary rather than alternative. Keeping the region saved costs whatever the region retains, and this change is what makes that cheap: on one aggregation at 2048 tokens and
D7168, a saved region costs 1036.2 MiB without this change and 28.2 MiB with it.Results
One aggregation, bfloat16, H100 80GB, one shape per process, 10 warmups and the median of 7. Shapes run from the debug flavor up to the released model's hidden size and block count,
dim7168 with a stack of 8.keptcounts the storages autograd holds that are not already live as inputs, and the two peak columns are increments over the allocation already standing when the call begins.tokensistraining.num_tokens_per_microbatch_per_dp_rank, described in the config as the number of input-token slots processed per data-parallel rank in one model forward, before context or tensor parallel sharding. Kimi K3's hidden states are token-major[T, D], so it is the leading dimension of every tensor below. For reference the released flavor sets it to one timesmax_context_length, which is 262144, so even the widest row here is an eighth of that default.With activation checkpointing, which is the default
The block checkpoint discards the saved tensors, so neither form retains anything and the difference is entirely in peak. The naive form still builds both FP32 tensors in forward, and builds them a second time during recompute.
Forward peak falls 6.3x and backward peak 4.7x once the stack reaches 8, and both ratios hold as the context grows. At the widest shape a single aggregation's backward peak is 47.25 GiB against 10.07 GiB, a difference of 37.2 GiB on one call.
Without activation checkpointing
Here the retained bytes are the visible difference, and they stop growing with the shape.
48.1, 320.1, 1008.2, 4032.6 and 16130.3 MiB become 0.1, 0.1, 0.2, 0.8 and 3.4.
Forward is consistently slower, between 3% and 21%, because a few large operations become
N + 1smaller ones. Backward is slower at the smallest shape and faster fromdim4096 upward, reaching 1.14x with checkpointing on at the widest shape.The result is not bitwise. The reordering takes the dot product first and scales by the inverse RMS where the current form normalizes and then contracts, which lands at about one bfloat16 ulp. In FP32 the two agree exactly, forward and every gradient, which the CPU test asserts at the default tolerance.
The released model, computed rather than measured
93 layers at block size 12 gives 8 blocks and 186 aggregations, and an aggregation inside block
bruns overb + 2values. Each call retains two FP32[T, b + 2, D]tensors today against three FP32[b + 2, T]statistics after, so the ratio is the hidden size. Computed from that structure atdim7168 with pipeline degree 8, with no block level checkpointing, where retained bytes are what the change removes:Under the default checkpointing that residency is already absorbed by the block checkpoint, and what the change removes instead is the peak of a single aggregation, which does not accumulate across layers. The measured peaks in the first table are the relevant figures there.
Where the naive form stops fitting
Same hidden size and stack, one process per point, peak reported as the process total rather than as an increment, so these numbers are larger than the two tables above and are not comparable to them.
On a 79.18 GiB card the naive form stops at 32768 tokens and this change reaches 131072, four times further. Neither reaches 262144, so this raises the context a single rank can carry through one aggregation and does not make the released default fit on one card; that configuration is sharded by context, tensor and pipeline parallelism, and
tokenshere is counted before any of that sharding.Test plan
The cases are the aggregation against a plain autograd reference in FP32 at stack widths 1 and 3, a bfloat16 case that fails if the score weight is rounded before the upcast, a check that the Function is registered for SPMD type checking, and three for the initialisation: the uniform depth weights, the gradient behaviour of the two parameters, and that all three residual projections carry a zero initialiser.
The whole CPU suite was also run against a worktree at unmodified
upstream/main, since a count from any other tree is not a baseline. Failures and errors are identical on both sides, 19 and 7, the same files in both cases and none of them a Kimi K3 test; the seven errors are missing packages in that environment. Passed differs only by the tests this PR adds, and the new file was confirmed present in the collection list rather than inferred from the counts.tests/unit_tests/gpu/test_kimi_k3.pyhas no case covering the aggregation, so the GPU suite does not exercise this path today.