Repository navigation
Use stacked layout for fused feed-forward projections - #4676
Conversation
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
tianyu-l
left a comment
There was a problem hiding this comment.
wonder if we should just make Linear stack-native
| class Config(Module.Config): | ||
| in_features: int | ||
| out_features: int | ||
| num_linears: int |
There was a problem hiding this comment.
Not straightforward to me why we need to have a separate class. Can we just make linear generalized, similar to GroupedLinear in #4539
o/w we'll need to handle more if-else, I feel.
kimi_k3_debugmodel trains with DistMuon instead of AdamW. Matrix parameters use per-head compute layouts for both attention variants; the fused MLA projections are split into one Newton-Schulz matrix per logical projection, following Kimi's implementation (pytorch#4692): - wq_b: per head [q_nope; q_rope] via num_rows_per_segment - wkv_a: one block [kv_latent; k_rope] - wkv_b: per head [k_nope; v] KDA q/k/v/forget_b/output_gate are per head with block_size=head_dim; forget_a and output_proj are whole-matrix. Routed experts reuse the K2.7 per-expert layout. Dense feed_forward and shared_experts w13 follow pytorch#4531 and stay whole-matrix until the stacked layout from pytorch#4676 lands. AdamW keeps the non-matrix parameters (norms, embeddings, LM head, A_log, dt_bias, depthwise convs), the per-head-scalar beta rows, the single-row residual projections, and the vision tower.
kimi_k3_debugmodel trains with DistMuon instead of AdamW. Matrix parameters use per-head compute layouts for both attention variants; the fused MLA projections are split into one Newton-Schulz matrix per logical projection, following Kimi's implementation (pytorch#4692): - wq_b: per head [q_nope; q_rope] via num_rows_per_segment - wkv_a: one block [kv_latent; k_rope] - wkv_b: per head [k_nope; v] KDA q/k/v/forget_b/output_gate are per head with block_size=head_dim; forget_a and output_proj are whole-matrix. Routed experts reuse the K2.7 per-expert layout. Dense feed_forward and shared_experts w13 follow pytorch#4531 and stay whole-matrix until the stacked layout from pytorch#4676 lands. AdamW keeps the non-matrix parameters (norms, embeddings, LM head, A_log, dt_bias, depthwise convs), the per-head-scalar beta rows, the single-row residual projections, and the vision tower.
kimi_k3_debugmodel trains with DistMuon instead of AdamW. Matrix parameters use per-head compute layouts for both attention variants; the fused MLA projections are split into one Newton-Schulz matrix per logical projection, following Kimi's implementation (pytorch#4692): - wq_b: per head [q_nope; q_rope] via num_rows_per_segment - wkv_a: one block [kv_latent; k_rope] - wkv_b: per head [k_nope; v] KDA q/k/v/forget_b/output_gate are per head with block_size=head_dim; forget_a and output_proj are whole-matrix. Routed experts reuse the K2.7 per-expert layout. Dense feed_forward and shared_experts w13 stay whole-matrix until the stacked layout from pytorch#4676 lands, then switch to Shard(0) compute over the [2, F, D] batch. AdamW keeps the non-matrix parameters (norms, embeddings, LM head, A_log, dt_bias, depthwise convs), the per-head-scalar beta rows, the single-row residual projections, and the vision tower.
Followup from #4535. Generalize Linear with num_linears while keeping ordinary projections in their standard 2D layout. Store fused W13 as [2, F, D], keeping gate and up projections contiguous without changing the flattened GEMM. Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split and merge gate/up projections only at the Hugging Face adapter boundary, avoiding FFN-sized state_dict hook copies on every RL weight sync. Shard stacked W13 on its matrix-row dimension for TP and FSDP, propagate the layout through LoRA, dist-GEMM, rematerialization, fused SwiGLU, vLLM, and quantized Linear implementations, and allow DistMuon Owned compute for native batches of matrices. Update numerical goldens and add coverage for native/HF state-dict round trips, tied Qwen FSDP loads, DeepSeek V4 TP, Kimi DistMuon, stacked initialization, and quantized FSDP gathering. ghstack-source-id: 0df121f Pull-Request: #4676
Followup from #4535. Generalize Linear with num_linears while keeping ordinary projections in their standard 2D layout. Store fused W13 as [2, F, D], keeping gate and up projections contiguous without changing the flattened GEMM. Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split and merge gate/up projections only at the Hugging Face adapter boundary, avoiding FFN-sized state_dict hook copies on every RL weight sync. Shard stacked W13 on its matrix-row dimension for TP and FSDP, propagate the layout through LoRA, dist-GEMM, rematerialization, fused SwiGLU, vLLM, and quantized Linear implementations, and allow DistMuon Owned compute for native batches of matrices. Update numerical goldens and add coverage for native/HF state-dict round trips, tied Qwen FSDP loads, DeepSeek V4 TP, Kimi DistMuon, stacked initialization, and quantized FSDP gathering. ghstack-source-id: 1242ebb Pull-Request: #4676
Followup from #4535. Generalize Linear with num_linears while keeping ordinary projections in their standard 2D layout. Store fused W13 as [2, F, D], keeping gate and up projections contiguous without changing the flattened GEMM. Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split and merge gate/up projections only at the Hugging Face adapter boundary, avoiding FFN-sized state_dict hook copies on every RL weight sync. Shard stacked W13 on its matrix-row dimension for TP and FSDP, propagate the layout through LoRA, dist-GEMM, rematerialization, fused SwiGLU, vLLM, and quantized Linear implementations, and allow DistMuon Owned compute for native batches of matrices. Update numerical goldens and add coverage for native/HF state-dict round trips, tied Qwen FSDP loads, DeepSeek V4 TP, Kimi DistMuon, stacked initialization, and quantized FSDP gathering. ghstack-source-id: c3b1478 Pull-Request: #4676
Followup from #4535. Generalize Linear with num_linears while keeping ordinary projections in their standard 2D layout. Store fused W13 as [2, F, D], keeping gate and up projections contiguous without changing the flattened GEMM. Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split and merge gate/up projections only at the Hugging Face adapter boundary, avoiding FFN-sized state_dict hook copies on every RL weight sync. Shard stacked W13 on its matrix-row dimension for TP and FSDP, propagate the layout through LoRA, dist-GEMM, rematerialization, fused SwiGLU, vLLM, and quantized Linear implementations, and allow DistMuon Owned compute for native batches of matrices. Update numerical goldens and add coverage for native/HF state-dict round trips, tied Qwen FSDP loads, DeepSeek V4 TP, Kimi DistMuon, stacked initialization, and quantized FSDP gathering. ghstack-source-id: c3b1478 Pull-Request: #4676
There was a problem hiding this comment.
the DistMuon part should be like this
- storage sharding: Shard(1) on [2, F, D]
- optimizer compute sharding: Shard(0) on [2, F, D]
this PR, as is, is a workaround of existing optimizer compute sharding of Owned on [2, F, D]. I can do a quick follow up once this is merged into main
| ) | ||
|
|
||
| def _init_param(self, name: str, param: nn.Parameter) -> None: | ||
| def _init_param(self, name: str, param: torch.Tensor) -> None: |
There was a problem hiding this comment.
what motivates this change?
There was a problem hiding this comment.
not needed anymore.
| f"got {type(rope).__qualname__}." | ||
| ) | ||
|
|
||
| def _linear_state_dict_to_hf(self, state_dict: dict[str, Any]) -> dict[str, Any]: |
There was a problem hiding this comment.
name sounds confusing, at least mention something like "native_fused_linear"_to_hf
also we need to be future-proof -- QKVLinear and GroupedLinear need to be adapted too, hopefully in the same util / pass
There was a problem hiding this comment.
Changed to _native_fused_linears_to_hf
And codex tells me that we can use this for QKVLinear and GroupedLinear as well (not in this PR though). I can do this in another PR.
| def reset_parameters(self) -> None: | ||
| Linear.reset_parameters(self) |
There was a problem hiding this comment.
Same as above, it does not inherit from Linear
| def _init_param(self, name: str, param: torch.Tensor) -> None: | ||
| if self.num_linears == 1: | ||
| param = param.flatten(0, -2) if name == "weight" else param.flatten() | ||
| Module._init_param(self, name, param) |
There was a problem hiding this comment.
won't they be covered by Linear base methods?
There was a problem hiding this comment.
Same as above, it does not inherit from Linear
| _SPARSE_STORAGE_AXES = ["dp_replicate", "efsdp", "ep"] | ||
|
|
||
|
|
||
| def linear_param_shard_placements(module: nn.Module) -> dict[nn.Parameter, Shard]: |
| """ | ||
| placements: dict[nn.Parameter, Shard] = {} | ||
| for child in module.modules(): | ||
| if not isinstance(child, nn.Linear) or child.weight.ndim == 2: |
There was a problem hiding this comment.
better use config's num_linears?
| def _init_param(self, name: str, param: torch.Tensor) -> None: | ||
| """Initialize a single projection through its standard parameter view.""" | ||
| if self.num_linears == 1: | ||
| param = param.flatten(0, -2) if name == "weight" else param.flatten() | ||
| Module._init_param(self, name, param) |
There was a problem hiding this comment.
confused by why we need this at all; I had thought users are responsible to init their param
There was a problem hiding this comment.
Removing. It is indeed unnecessary.
| output = F.linear(input, weight, bias) | ||
| return self._unflatten_output(output) | ||
|
|
||
| def extra_repr(self) -> str: |
There was a problem hiding this comment.
nn.Module.__repr__ calls this. It is only for diagnostics.
| weight = self.weight.flatten(0, -2) | ||
| bias = None if self.bias is None else self.bias.flatten() |
There was a problem hiding this comment.
can we not use the helper flatten/unflatten methods in parent cls?
There was a problem hiding this comment.
NVFP4Linear does not inherit from our Linear because of the TorchAO/Module MRO conflict. If we do want to make this better, then we need to redraw TorchAO boundary for Float8 and nvfp4 (similar to mxfp8).
Followup from #4535. Generalize Linear with num_linears while keeping ordinary projections in their standard 2D layout. Store fused W13 as [2, F, D], keeping gate and up projections contiguous without changing the flattened GEMM. Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split and merge gate/up projections only at the Hugging Face adapter boundary, avoiding FFN-sized state_dict hook copies on every RL weight sync. Shard stacked W13 on its matrix-row dimension for TP and FSDP, propagate the layout through LoRA, dist-GEMM, rematerialization, fused SwiGLU, vLLM, and quantized Linear implementations, and allow DistMuon Owned compute for native batches of matrices. Update numerical goldens and add coverage for native/HF state-dict round trips, tied Qwen FSDP loads, DeepSeek V4 TP, Kimi DistMuon, stacked initialization, and quantized FSDP gathering. ghstack-source-id: c1be08b Pull-Request: #4676
Followup from #4535. Generalize Linear with num_linears while keeping ordinary projections in their standard 2D layout. Store fused W13 as [2, F, D], keeping gate and up projections contiguous without changing the flattened GEMM. Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split and merge gate/up projections only at the Hugging Face adapter boundary, avoiding FFN-sized state_dict hook copies on every RL weight sync. Shard stacked W13 on its matrix-row dimension for TP and FSDP, propagate the layout through LoRA, dist-GEMM, rematerialization, fused SwiGLU, vLLM, and quantized Linear implementations, and allow DistMuon Owned compute for native batches of matrices. Update numerical goldens and add coverage for native/HF state-dict round trips, tied Qwen FSDP loads, DeepSeek V4 TP, Kimi DistMuon, stacked initialization, and quantized FSDP gathering. ghstack-source-id: a90409c Pull-Request: #4676
Followup from #4535. Generalize Linear with num_linears while keeping ordinary projections in their standard 2D layout. Store fused W13 as [2, F, D], keeping gate and up projections contiguous without changing the flattened GEMM. Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split and merge gate/up projections only at the Hugging Face adapter boundary, avoiding FFN-sized state_dict hook copies on every RL weight sync. Shard stacked W13 on its matrix-row dimension for TP and FSDP, propagate the layout through LoRA, dist-GEMM, rematerialization, fused SwiGLU, vLLM, and quantized Linear implementations, and allow DistMuon Owned compute for native batches of matrices. Update numerical goldens and add coverage for native/HF state-dict round trips, tied Qwen FSDP loads, DeepSeek V4 TP, Kimi DistMuon, stacked initialization, and quantized FSDP gathering. ghstack-source-id: ab41ed0 Pull-Request: #4676
|
|
||
| def forward(self, input: torch.Tensor) -> torch.Tensor: | ||
| if torch.is_autocast_enabled(): | ||
| input = input.to(torch.get_autocast_gpu_dtype()) |
There was a problem hiding this comment.
curious why do we need this? Is it because torchao TorchAOFloat8Linear does this?
There was a problem hiding this comment.
| def _flatten_weight_and_bias( | ||
| self, | ||
| *, | ||
| weight: torch.Tensor | None = None, |
There was a problem hiding this comment.
why sending this -- who calls it?
There was a problem hiding this comment.
thanks for catching, not needed.
| if weight is None: | ||
| weight = self.weight | ||
| weight = weight.flatten(0, -2) | ||
| bias = None if self.bias is None else self.bias.flatten() |
There was a problem hiding this comment.
this should work even when the module is FSDP wrapped right?
There was a problem hiding this comment.
Yes.
FSDP2’s
__call__hooks unshard the parameter before entering forward, so this helper reads the active unsharded self.weight.
| input = input.to(torch.get_autocast_gpu_dtype()) | ||
| weight = self.weight.flatten(0, -2) | ||
| bias = None if self.bias is None else self.bias.flatten() | ||
| output = matmul_with_hp_or_float8_args.apply( |
There was a problem hiding this comment.
if we are already calling this manually, do we still need to inherit TorchAOFloat8Linear at all?
If shifting the boundary makes most sense, we should do it, now
There was a problem hiding this comment.
So you are right that we are almost copying the forward method from here - https://github.com/pytorch/ao/blob/df97218e877fb0c2f7e869d8e5c7853e1a9ea1ea/torchao/float8/float8_linear.py#L254
But inheritance does other things like __init__ (https://github.com/pytorch/ao/blob/df97218e877fb0c2f7e869d8e5c7853e1a9ea1ea/torchao/float8/float8_linear.py#L215) . The reason we had to override forward is to flatten the weights and unflatten the output. So, we still want inheritance to prevent __init__ copying.
For me, the shifting boundary is bigger work like MxFP8Linear (and not just inheritance removal) so that it can compose with FSDP and we have consistent float8 support.
I have similar take for nvfp4. In this PR, I am just doing whatever needed to make these float8 and nvfp4 pass, and then later revisit how to refactor them. This will probably need some AO work as well.
Followup from #4535. Generalize Linear with num_linears while keeping ordinary projections in their standard 2D layout. Store fused W13 as [2, F, D], keeping gate and up projections contiguous without changing the flattened GEMM. Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split and merge gate/up projections only at the Hugging Face adapter boundary, avoiding FFN-sized state_dict hook copies on every RL weight sync. Shard stacked W13 on its matrix-row dimension for TP and FSDP, propagate the layout through LoRA, dist-GEMM, rematerialization, fused SwiGLU, vLLM, and quantized Linear implementations, and allow DistMuon Owned compute for native batches of matrices. Update numerical goldens and add coverage for native/HF state-dict round trips, tied Qwen FSDP loads, DeepSeek V4 TP, Kimi DistMuon, stacked initialization, and quantized FSDP gathering. ghstack-source-id: f9eda5c Pull-Request: #4676
|
@anijain2305 sorry I accidentally merged it, into ghstack head |
no worries at all, happened to me twice already haha. Thanks for trying to merge and saving me time though :) |
Relands #4676 against `main`. #4676 was accidentally merged into its ghstack base branch and never landed on `main`. This PR contains the same reviewed change, rebased onto current `main`. Followup from #4535. W13 currently stores W1 and W3 as interleaved rows in a [2F, D] tensor, logically [F, 2, D]. This works well for TP, but block-quantization tiles can span both projections and force them to share scales. Generalize Linear with num_linears and store W13 as [2, F, D], keeping each projection contiguous. The GEMM still uses a flattened [2F, D] view. State dicts ----------- Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split w13 into gate/up projections, and merge them on load, only at the Hugging Face adapter boundary. This avoids materializing FFN-sized hook outputs on every state_dict() call. Quantization ------------ Teach the Float8, MXFP8, and NVFP4 Linear implementations to preserve the stacked layout. Generalize quantized FSDP gathering to support weights sharded on dimension 1. Tensor parallelism ------------------ Shard dimension 1 so every TP rank receives matching feature slices of W1 and W3. LoRA ---- Use a shared A weight [r, D] and a stacked B weight [2, F, r]. Carry the stacked layout through rematerialization, dist-GEMM, fused SwiGLU, and vLLM state-dict handling.
kimi_k3_debugmodel trains with DistMuon instead of AdamW. Matrix parameters use per-head compute layouts for both attention variants; the fused MLA projections are split into one Newton-Schulz matrix per logical projection, following Kimi's implementation (pytorch#4692): - wq_b: per head [q_nope; q_rope] via num_rows_per_segment - wkv_a: one block [kv_latent; k_rope] - wkv_b: per head [k_nope; v] KDA q/k/v/forget_b/output_gate are per head with block_size=head_dim; forget_a and output_proj are whole-matrix. Routed experts reuse the K2.7 per-expert layout. Dense feed_forward and shared_experts w13 stay whole-matrix until the stacked layout from pytorch#4676 lands, then switch to Shard(0) compute over the [2, F, D] batch. AdamW keeps the non-matrix parameters (norms, embeddings, LM head, A_log, dt_bias, depthwise convs), the per-head-scalar beta rows, the single-row residual projections, and the vision tower.
kimi_k3_debugmodel trains with DistMuon instead of AdamW. Matrix parameters use per-head compute layouts for both attention variants; the fused MLA projections are split into one Newton-Schulz matrix per logical projection, following Kimi's implementation (pytorch#4692): - wq_b: per head [q_nope; q_rope] via num_rows_per_segment - wkv_a: one block [kv_latent; k_rope] - wkv_b: per head [k_nope; v] KDA q/k/v/forget_b/output_gate are per head with block_size=head_dim; forget_a and output_proj are whole-matrix. Routed experts reuse the K2.7 per-expert layout. Dense feed_forward and shared_experts w13 stay whole-matrix until the stacked layout from pytorch#4676 lands, then switch to Shard(0) compute over the [2, F, D] batch. AdamW keeps the non-matrix parameters (norms, embeddings, LM head, A_log, dt_bias, depthwise convs), the per-head-scalar beta rows, the single-row residual projections, and the vision tower.
kimi_k3_debugmodel trains with DistMuon instead of AdamW. Matrix parameters use per-head compute layouts for both attention variants; the fused MLA projections are split into one Newton-Schulz matrix per logical projection, following Kimi's implementation (pytorch#4692): - wq_b: per head [q_nope; q_rope] via num_rows_per_segment - wkv_a: one block [kv_latent; k_rope] - wkv_b: per head [k_nope; v] KDA q/k/v/forget_b/output_gate are per head with block_size=head_dim; forget_a and output_proj are whole-matrix. Routed experts reuse the K2.7 per-expert layout. Dense feed_forward and shared_experts w13 stay whole-matrix until the stacked layout from pytorch#4676 lands, then switch to Shard(0) compute over the [2, F, D] batch. AdamW keeps the non-matrix parameters (norms, embeddings, LM head, A_log, dt_bias, depthwise convs), the per-head-scalar beta rows, the single-row residual projections, and the vision tower.
kimi_k3_debugmodel trains with DistMuon instead of AdamW. Matrix parameters use per-head compute layouts for both attention variants; the fused MLA projections are split into one Newton-Schulz matrix per logical projection, following Kimi's implementation (pytorch#4692): - wq_b: per head [q_nope; q_rope] via num_rows_per_segment - wkv_a: one block [kv_latent; k_rope] - wkv_b: per head [k_nope; v] KDA q/k/v/forget_b/output_gate are per head with block_size=head_dim; forget_a and output_proj are whole-matrix. Routed experts reuse the K2.7 per-expert layout. Dense feed_forward and shared_experts w13 stay whole-matrix until the stacked layout from pytorch#4676 lands, then switch to Shard(0) compute over the [2, F, D] batch. AdamW keeps the non-matrix parameters (norms, embeddings, LM head, A_log, dt_bias, depthwise convs), the per-head-scalar beta rows, the single-row residual projections, and the vision tower.
Stack from ghstack (oldest at bottom):
Followup from #4535.
W13 currently stores W1 and W3 as interleaved rows in a [2F, D] tensor, logically [F, 2, D]. This works well for TP, but block-quantization tiles can span both projections and force them to share scales.
Generalize Linear with num_linears and store W13 as [2, F, D], keeping each projection contiguous. The GEMM still uses a flattened [2F, D] view.
State dicts
Keep native DCP checkpoints and RL weight synchronization in the physical w13 layout. Split w13 into gate/up projections, and merge them on load, only at the Hugging Face adapter boundary. This avoids materializing FFN-sized hook outputs on every state_dict() call.
Quantization
Teach the Float8, MXFP8, and NVFP4 Linear implementations to preserve the stacked layout. Generalize quantized FSDP gathering to support weights sharded on dimension 1.
Tensor parallelism
Shard dimension 1 so every TP rank receives matching feature slices of W1 and W3.
LoRA
Use a shared A weight [r, D] and a stacked B weight [2, F, r]. Carry the stacked layout through rematerialization, dist-GEMM, fused SwiGLU, and vLLM state-dict handling.