Repository: huggingface/transformers
Pull request: stable grouped_mm API

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker @Cyrilvallez
- vision models: @yonigozlan @molbap
- audio models: @eustlb @ebezzam @vasqu
- multimodal models: @zucchini-nlp
- graph models: @clefourrier

Library:

- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- continuous batching: @remi-or @ArthurZucker @McPatate
- pipelines: @Rocketknight1
- tokenizers: @ArthurZucker and @itazap
- trainer: @SunMarc
- attention: @vasqu @ArthurZucker @CyrilVallez
- model loading (from pretrained, etc): @CyrilVallez
- distributed: @3outeille @ArthurZucker
- CIs: @ydshieh

Integrations:

- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization: @SunMarc @MekkCyber
- kernels: @MekkCyber @drbh
- peft: @BenjaminBossan @githubnemo

Devices/Backends:

- AMD ROCm: @ivarflakstad
- Intel XPU: @IlyasMoutawwakil
- Ascend NPU: @ivarflakstad 

Documentation: @stevhliu

Research projects are not maintained and should be taken as is.

 -->


Changed files:
filename: docs/source/en/experts_interface.md
patch: @@ -19,11 +19,11 @@ All Mixture-of-Experts (MoE) implementations perform the same high-level computa
 
 The [`ExpertsInterface`] provides optimized experts backends. It decouples the experts implementation from the model code to simplify experimentation with different functions. Add new backends through the same interface.
 
-| experts backend | description                                                                                                                                                                                                                  | GPU                                                                                                                 | CPU                                                         |
-| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
-| `"eager"`       | Reference implementation that loops over selected experts and applies projections on their tokens.                                                                                                                           | Reasonable baseline performance without requiring compilation.                                                      | Slower than `grouped_mm` but faster than `batched_mm`.      |
-| `"batched_mm"`  | Duplicates selected expert parameters for each token and projects all tokens in a single batched GEMM using [`torch.bmm`](https://docs.pytorch.org/docs/stable/generated/torch.bmm.html).                                    | Fastest for small inputs, especially with compilation. Uses more memory due to parameter duplication.               | Not recommended (significantly slower than other backends). |
-| `"grouped_mm"`  | Orders tokens by selected experts and uses [`torch._grouped_mm`](https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.grouped_mm.html) to project all tokens in a single grouped GEMM (requires PyTorch 2.9+). | Best for larger inputs and more memory efficient as it avoids duplicating expert parameters. Fast with compilation. | Most efficient backend for all input sizes.                 |
+| experts backend | description                                                                                                                                                                                                                               | GPU                                                                                                                 | CPU                                                         |
+| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
+| `"eager"`       | Reference implementation that loops over selected experts and applies projections on their tokens.                                                                                                                                        | Reasonable baseline performance without requiring compilation.                                                      | Slower than `grouped_mm` but faster than `batched_mm`.      |
+| `"batched_mm"`  | Duplicates selected expert parameters for each token and projects all tokens in a single batched GEMM using [`torch.bmm`](https://docs.pytorch.org/docs/stable/generated/torch.bmm.html).                                                 | Fastest for small inputs, especially with compilation. Uses more memory due to parameter duplication.               | Not recommended (significantly slower than other backends). |
+| `"grouped_mm"`  | Orders tokens by selected experts and uses [`torch.nn.functional.grouped_mm`](https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.grouped_mm.html) to project all tokens in a single grouped GEMM (requires PyTorch 2.9+). | Best for larger inputs and more memory efficient as it avoids duplicating expert parameters. Fast with compilation. | Most efficient backend for all input sizes.                 |
 
 > [!NOTE]
 > When using `experts_implementation="grouped_mm"` on GPU, the model automatically switches to `"batched_mm"` during the decode stage of generation (after prefill). This is because `batched_mm` is significantly faster on lower token count during autoregressive decoding on GPU. On CPU, `grouped_mm` remains active throughout generation as it is more efficient for all input sizes.

filename: src/transformers/core_model_loading.py
patch: @@ -442,7 +442,7 @@ def reverse_op(self) -> ConversionOps:
 class Force16BytesAlignment(ConversionOps):
     """
     Ensures that the given tensor is 16-bytes aligned in memory and clones it if not.
-    This guarantees 16-bytes alignment for kernels / implementations that use TMA or SIMD instructions like torch._grouped_mm.
+    This guarantees 16-bytes alignment for kernels / implementations that use TMA or SIMD instructions like torch.nn.functional.grouped_mm.
     """
 
     @torch.no_grad()

filename: src/transformers/integrations/moe.py
patch: @@ -156,6 +156,39 @@ def batched_mm_experts_forward(
     return final_hidden_states.to(hidden_states.dtype)
 
 
+def _grouped_mm(
+    input: torch.Tensor,
+    weight: torch.Tensor,
+    offs: torch.Tensor | None = None,
+) -> torch.Tensor:
+    """Grouped matrix multiplication dispatcher that uses torch.nn.functional.grouped_mm if available, else falls back to torch._grouped_mm.
+    Args:
+        input (`torch.Tensor`):
+            Input tensor of shape (S, input_dim).
+        weight (`torch.Tensor`):
+            Weight tensor of shape (num_experts, output_dim, input_dim).
+        offs (`torch.Tensor`, *optional*):
+            Offsets tensor indicating the boundaries of each group in the input tensor.
+    Returns:
+        `torch.Tensor`: Output tensor of shape (S, output_dim).
+    Raises:
+        ImportError: If neither `torch.nn.functional.grouped_mm` nor `torch._grouped_mm` is available, indicating that the PyTorch version is incompatible.
+    """
+
+    # torch.nn.functional.grouped_mm is not autocast-enabled, so if autocast is enabled we might end up with input tensors in fp32 (e.g. LayerNorm output) and weight tensors in fp16/bf16
+    # In that case we need to cast the input to the weight dtype to avoid dtype mismatch errors.
+    # See: https://github.com/pytorch/pytorch/issues/174763
+    if hasattr(torch.nn.functional, "grouped_mm"):
+        return torch.nn.functional.grouped_mm(input.to(weight.dtype), weight, offs=offs)
+    elif hasattr(torch, "_grouped_mm"):
+        return torch._grouped_mm(input.to(weight.dtype), weight, offs=offs)
+    else:
+        raise ImportError(
+            "Neither torch.nn.functional.grouped_mm nor torch._grouped_mm is available. "
+            "Please make sure you are using a PyTorch version that includes grouped_mm (2.9+)."
+        )
+
+
 def _grouped_linear(
     input: torch.Tensor,
     weight: torch.Tensor,
@@ -180,15 +213,12 @@ def _grouped_linear(
     Returns:
         `torch.Tensor`: Output tensor of shape (S, output_dim).
     """
-    # torch._grouped_mm is not autocast-enabled, so we disable autocast to avoid dtype mismatch.
-    # See: https://github.com/pytorch/pytorch/issues/174763
-    with torch.amp.autocast(device_type=input.device.type, enabled=False):
-        if is_transposed:
-            # (S, input_dim) @ grouped (num_experts, input_dim, output_dim) -> (S, output_dim)
-            out = torch._grouped_mm(input, weight, offs=offs)
-        else:
-            # (S, input_dim) @ grouped (num_experts, output_dim, input_dim).T -> (S, output_dim)
-            out = torch._grouped_mm(input, weight.transpose(-2, -1), offs=offs)
+    if is_transposed:
+        # (S, input_dim) @ grouped (num_experts, input_dim, output_dim) -> (S, output_dim)
+        out = _grouped_mm(input, weight, offs=offs)
+    else:
+        # (S, input_dim) @ grouped (num_experts, output_dim, input_dim).T -> (S, output_dim)
+        out = _grouped_mm(input, weight.transpose(-2, -1), offs=offs)
 
     if bias is not None:
         # We should be able to pass bias to the grouped_mm call, but it's not yet supported.
@@ -203,11 +233,6 @@ def grouped_mm_experts_forward(
     top_k_index: torch.Tensor,
     top_k_weights: torch.Tensor,
 ) -> torch.Tensor:
-    if not hasattr(torch, "_grouped_mm"):
-        raise ImportError(
-            "torch._grouped_mm is not available. Please make sure you are using a PyTorch version that includes it (2.9+)."
-        )
-
     device = hidden_states.device
     num_top_k = top_k_index.size(-1)
     num_tokens = hidden_states.size(0)

filename: src/transformers/modeling_utils.py
patch: @@ -3741,7 +3741,7 @@ def from_pretrained(
 
                 - `"eager"` (sequential implementation of the experts matrix multiplications).
                 - `"batched_mm"` (using [`torch.bmm`](https://pytorch.org/docs/stable/generated/torch.bmm.html)).
-                - `"grouped_mm"` (using [`torch._grouped_mm`](https://docs.pytorch.org/docs/main/generated/torch.nn.functional.grouped_mm.html)).
+                - `"grouped_mm"` (using [`torch.nn.functional.grouped_mm`](https://docs.pytorch.org/docs/main/generated/torch.nn.functional.grouped_mm.html)).
 
                 By default, if available, `grouped_mm` will be used for torch>=2.9.0. The default is otherwise the sequential `"eager"` implementation.
 

filename: tests/test_modeling_common.py
patch: @@ -4064,8 +4064,8 @@ def test_torch_compile_for_training(self):
 
         model = cls(config).to(device=torch_device)
 
-        # torch._grouped_mm still only supports bfloat16 when used with torch.compile
-        # bfloat16 is problematic with precisions so we keep an implementation with full precision
+        # torch.nn.functional.grouped_mm still only supports bfloat16 when used with torch.compile
+        # bfloat16 is problematic with precisions so we use an implementation with full precision
         if model.config._experts_implementation == "grouped_mm":
             model.set_experts_implementation("batched_mm")