Sum the MoE experts' top-k outputs without a float32 copy of all rows (#51491)
* Sum the MoE experts' top-k outputs without a float32 copy of all rows
Most routers return float32 routing weights, so `proj_out * weights` in
grouped_mm_experts_forward and batched_mm_experts_forward promoted the whole
(num_tokens * top_k, hidden) expert output to float32. grouped_mm then reordered
that float32 copy, and the backward allocated more float32 buffers of the same size.
The rows are now reordered in their own dtype and weighted and summed in chunks of
tokens. The sums stay in float32, so outputs and gradients are unchanged.
* Leave the expert-parallel sentinel comment as it was
* Cast each chunk's sum to the rows' dtype, and use one expression when compiling
Co-authored-by: Ilyas Moutawwakil <57442720+IlyasMoutawwakil@users.noreply.github.com>
* Restore the experts order with index_copy_ when gradients are needed
Co-authored-by: Ilyas Moutawwakil <57442720+IlyasMoutawwakil@users.noreply.github.com>
* Move the reshape+sum explanation into _weighted_sum's docstring
* Chunk the weighted sum only when gradients are needed
* Check compiling and no-grad before computing the chunk size
* Weighted sum: is_torchdynamo_compiling and a grad-enabled training check, one chunked path
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Move the unsort into _unsort, inline the single-use training check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* _unsort: index_copy_ when compiling too, keep the single-chunk path of _weighted_sum
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Ilyas Moutawwakil <57442720+IlyasMoutawwakil@users.noreply.github.com>
Co-authored-by: IlyasMoutawwakil <moutawwakil.ilyas.tsi@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>