Skip to content

MoE grouped GEMM: require sm90 on every visible card for TMA and launch on the operands' device - #14358

Merged
danielhanchen merged 7 commits into
mainfrom
moe-grouped-gemm-tma-every-card
Oct 20, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
moe-grouped-gemm-tma-every-card

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

The MoE grouped GEMM decided TMA support from the current device only (torch.cuda.get_device_capability()), so on an H100 (cuda:0) + A100 (cuda:1) host with experts on cuda:1, TMA configs were kept for the sm80 card. Launches, the SM count and the Triton scratch allocations also used the current device instead of the operands' device.

What changes

  • _check_tma_support requires every visible CUDA card to be sm90 or newer, mirroring the GRPO TMA compile option in unsloth/models/rl.py. An unreadable card means no TMA instead of an import-time error. HIP and XPU are unchanged.
  • Forward, dX and dW launches run under torch_gpu_device(<input>.device), like the other Unsloth kernels.
  • NUM_SMS and the Triton scratch allocator use the input tensor's device instead of "cuda".

Hosts affected

  • Mixed NVIDIA hosts with an sm90+ card at the current index and an older card elsewhere: TMA is now off.
  • Multi-GPU hosts with experts off the current device: kernels launch on, and size the grid for, the right card.
  • Single-GPU and homogeneous hosts: unchanged. The guard is a nullcontext on one card (about 0.3 us per call).

Tests

  • tests/test_grouped_gemm_mixed_tma_device.py: spoofed per-index capabilities (h100+a100 and h100+l4+h100 give no TMA; h100x2, h100+b200 and a single h100 give TMA; a single a100 gives no TMA; an unreadable card gives no TMA), plus a mocked device guard confirming all three launches and the scratch allocations follow a cuda:1 input. 4 of the 11 fail on the merge base, all pass here.
  • Enumeration of the TMA check over 1 to 3 cards x {sm75, sm80, sm90, sm100, unreadable} x Triton API x current device: 860 cells, 550 identical, 138 True to False (mixed hosts), 172 import-time error to False, none False to True.
  • Existing grouped GEMM and capability tests in unsloth and unsloth-zoo: identical results before and after.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-20T15:46:25.561285Z 5607651 New commits
🔒 Security Review ⚠️ Failed 2026-10-20T14:03:14.485486Z d3373f5 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d3373f5a8e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


def alloc_fn(size: int, alignment: int, stream: int):
return torch.empty(size, device = "cuda", dtype = torch.int8)
return torch.empty(size, device = X.device, dtype = torch.int8)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep Triton's global allocator device-dynamic

When grouped GEMMs execute concurrently on different GPUs, triton.set_allocator remains process-global, so one thread can replace the callback after another thread installs it but before that thread launches. Because the new callback captures X.device, the losing launch receives scratch memory from the other GPU, resulting in an invalid cross-device pointer or launch failure. The new torch_gpu_device launch guard already makes a current-device-based allocation resolve to the operand's card, so the allocator should not persistently capture a particular input device; the equivalent dX and dW callbacks have the same issue.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 20, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 82e0586: the three allocators go back to device="cuda". The launch guard makes that the operands' card, and the process-wide callback no longer captures one launch's device.

**kernel_args, enable_fp_fusion = True
)
# Triton launches on the current device: pin it to the operands' card.
with torch_gpu_device(X.device):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Partition autotuning state by operand device

When autotune=True runs the same shape on heterogeneous GPUs, moving the launch into this device guard is insufficient because the autotuners' keys omit the device (kernels/forward.py:226-233 and the analogous backward keys), while kernels/tuning.py:34-48 also caches the first device's shared-memory properties process-wide. Consequently, after an H100 populates these caches, an A100/L4 launch can reuse a configuration selected and pruned for the H100; that configuration may exceed the smaller card's resources and fail rather than tuning on the operand's device. Include the device/target in the tuning state or maintain per-device autotuners and device-property caches.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 20, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 82e0586: tuning.get_device_properties now caches per current device, and on multi-GPU hosts each card autotunes its own shallow copy of the autotuner (separate cache; no shared state mutated, so concurrent launches on different cards cannot race). Single GPU keeps the shared autotuner.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 82e0586115

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +70 to +72
tuner = copy.copy(kernel)
tuner.cache = {}
_DEVICE_AUTOTUNERS[key] = tuner

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Expose the per-device tuner's selected config

On any host with more than one visible GPU, this shallow copy receives best_config, while the original autotuner remains unchanged. After each interface call, _run_moe_autotuning still reads the original kernels at autotune_cache.py:293, :318, and :343; on a fresh process those objects have no best_config, so the exception is caught and every multi-GPU autotuning attempt silently falls back to the non-optimal defaults (or can consume a stale config if the original was tuned separately). Return the selected per-device tuner to that caller or otherwise propagate its selected config.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 16ee919: _run_moe_autotuning reads best_config through _autotuner_for(kernel, operand.device), the same per-card tuner the interface launched, so multi-GPU tuning keeps its result. Single GPU returns the shared kernel as before.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 16ee91962c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +70 to +71
tuner = copy.copy(kernel)
tuner.cache = {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Read the per-device cache when saving benchmark results

On hosts with more than one visible GPU, autotuning now populates only this copied tuner's fresh cache, but benchmark/utils.py:get_autotuner still returns the original kernel and postprocess_autotune_results iterates that original object's cache. Consequently, benchmark_fused_moe.py completes autotuning but silently prints and saves no selected configurations; expose the selected per-device tuner to the benchmark path just as _run_moe_autotuning now does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 97eb837: get_autotuner now returns the current card's tuner through _autotuner_for, so postprocess_autotune_results reads the cache that actually holds the selected config. On a single card it is still the shared kernel object (checked on GPU). Test: test_benchmark_postprocesses_the_per_card_tuner.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 97eb8371d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 9b5e9b9 into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the moe-grouped-gemm-tma-every-card branch October 20, 2026 18:18
danielhanchen added a commit that referenced this pull request Oct 20, 2026
## Problem


`tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding`
fails on main, so the `Repo tests (CPU, rest)` shard is red on every PR
(for example #14395):

```
AssertionError: 3 file reads in the test trees touch a checked-in file with the platform default encoding, so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8": ['tests/test_grouped_gemm_mixed_tma_device.py:218: read_text()', ...]
AssertionError: 2 file reads in the test trees touch a checked-in file with the platform default encoding, ... ['studio/backend/tests/test_diffusion_vae_oom.py:1726: read_text()', 'tests/test_legacy_block_compile_install.py:15: read_text()']
```

Three test files that merged today read checked-in sources with a bare
`read_text()`:

| File | Reads | Added by |
|---|---|---|
| `tests/test_grouped_gemm_mixed_tma_device.py` | 3 | #14358 |
| `studio/backend/tests/test_diffusion_vae_oom.py` | 1 | #13802 |
| `tests/test_legacy_block_compile_install.py` | 1 | #14398 |

The guard is right: on Windows, `read_text()` decodes with the locale
codec (cp1252), so these break as soon as one of those sources gains a
non-ASCII byte.

## Fix

Pass `encoding = "utf-8"` to the five reads. No other change.

## Verification

- On main: `tests/test_source_read_encoding.py`: 2 failed, 14 passed
(the two failures above).
- With this change: the guard and the two touched `tests/` files pass,
apart from 4 `test_legacy_gate` errors.
- Some failures on this host are the same with and without this change,
so they come from the local environment, not this PR:
- the 4 `test_legacy_gate` setup errors in
`tests/test_legacy_block_compile_install.py`;
- 8 failures in `studio/backend/tests/test_diffusion_vae_oom.py` (102
passed).
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Oct 21, 2026
…A test on one-GPU hosts and macOS (unslothai#14490)

## Summary
Follow-up to unslothai#14358 from a post-merge regression review. Three problems,
all fixed here.

## What changes
- **Identical cards tune once again.** unslothai#14358 gave every device index
its own copy of each Triton autotuner with its own results cache, so a
homogeneous multi-GPU host (`device_map="auto"` over identical cards)
re-ran autotuning on every card. Each card still gets its own tuner
object (Triton keeps per-run state such as `nargs` on it, and backward
runs one autograd thread per device, so a shared object races), but
copies on the same card model (name, compute capability, SM count) now
share one results cache. Different models or MIG sizes stay separate, a
single GPU still uses the kernel itself, and each copy follows a
reassigned `kernel.configs`. Checked with the real Triton 3.6 autotuner:
two concurrent cold-key calls on identical cards raise `TypeError` with
one shared tuner and pass here.
- **`test_launches_are_guarded_on_the_operands_device` failed on any
single-GPU CUDA host** with `CUDA error: invalid device ordinal`:
`FakeTensorMode` initialised a real `cuda:1` context. The test now stubs
`torch._subclasses.fake_tensor.init_gpu_context`, so no real context
opens.
- **The same test file failed on Apple Silicon.** unsloth_zoo installs a
permissive triton stub on macOS arm64 + MLX, so deleting
`make_tensor_descriptor` did not hide it. The module now skips when
`triton` is that stub.

## Not changed
One older visible card still turns TMA off process-wide (the flag is
precomputed to avoid graph breaks, and the default autotune configs
already disable TMA).

## Tests
- `tests/test_grouped_gemm_mixed_tma_device.py`: 18 passed; 2 fail
against main's source.
- On one real B200: main fails the guard test with `invalid device
ordinal`, this branch passes all 18.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…n GPU (unslothai#14719)

## Summary

On a `device_map` split across different GPU models, the MoE grouped
GEMM autotune lookup read the current CUDA device for everything: the
cache key, the tuning run (`device = "cuda"`), the disk-cache capability
check and the shared-memory fit. A layer whose experts live on another
card therefore got tiles keyed, tuned and SMEM-fitted for the current
card, and since unslothai#14578 / unslothai#14617 that choice is also reused from disk by
later processes.

`get_or_autotune_moe_kernels` now takes an optional `device`. When it
names a CUDA card other than the current one, the lookup runs with that
card current (`torch.cuda.device`), so the key carries the experts'
capability, tuning benchmarks run there, and `_device_smem_per_block` /
`_fit_configs_to_smem` read that card. `device=None`, the current card,
CPU and unindexed devices take exactly today's path.

The zoo side (unslothai/unsloth-zoo, branch
`moe-autotune-operand-device`) passes `gemm_hidden_states.device` when
the installed unsloth accepts the parameter, so either repo can land
first.

## What does not change

- Single-GPU and same-model multi-GPU hosts: same key, same tuning, same
tiles.
- The per-module config cache in zoo (`_unsloth_moe_configs`) still
makes this one lookup per layer, not per step; no device property is
read per launch.
- TMA: left as is. The shipped autotuner keeps TMA off (`autotuning.py`,
`_TRITON_HAS_TMA = False`), so the process-wide sm90 check from unslothai#14358
has no effect on the configs used today.

## Tests

- New `tests/test_moe_autotune_operand_device.py` (spoofed sm90 + sm80
host): a layer on card 1 tunes and keys for sm80 and leaves the current
device untouched; `device=None` and the current card share one cached
entry; CPU / unindexed devices keep the current path. All 3 fail on main
and pass here.
- Existing autotune and fallback suites (`test_moe_autotune_cache_hit`,
`_cache_validate`, `test_moe_fallback_smem`,
`test_moe_fallback_tile_dims`): 211 passed with the new file.

## Not covered

No mixed-model multi-GPU host was available; the device switching is
proven with a spoofed CUDA runtime, not a real H100 + L4 split.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant