Skip to content

Add token permute/unpermute helpers - #718

Merged
AkshitaB merged 17 commits into
akshitab/moe-v2-corefrom
akshitab/moe-v2-permute-utils
Jun 23, 2026
Merged

AkshitaB merged 17 commits into
akshitab/moe-v2-corefrom
akshitab/moe-v2-permute-utils

Conversation

@AkshitaB

Copy link
Copy Markdown
Contributor

Adds nn/moe/utils.py: the autograd-aware, torch.compile-safe wrapper layer over the MoE token permute / unpermute / chunk-reorder CUDA kernels (with optional Triton and TransformerEngine backends). These move tokens between the router's assignment order and the experts' grouped (per-expert-contiguous) order, in both forward and backward.

Contents:

  • Permute / unpermute with custom autograd — including fused capacity-drop and row-id-map variants (moe_permute_1d_fused_drop_no_compile, moe_unpermute_1d_fused_drop_no_compile, moe_reorder_rows_permutation).
  • Chunk reordering for the grouped-expert layout, with TE / CUDA backend selection (moe_chunk_reorder_no_compile, build_chunk_te_routing_map).
  • Small @torch.compiler.disable stream/event sync helpers and eager kernel passthroughs.

It depends only on the permute/reorder kernels already in olmo_core.kernels plus olmo_core.utils.get_or_init_stream; Triton and TransformerEngine are optional, guarded imports, so the module imports on CPU.

Also includes a CPU test for the chunk-reorder torch reference paths (_chunk_unpermute_torch zeroing out-of-range rows; _dispatch_permute_by_row_id_map honoring an out= buffer). The fused permute/unpermute correctness tests are GPU + TransformerEngine gated and will follow.

🤖 Generated with Claude Code

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Credits must be used to enable repository wide code reviews.

@AkshitaB AkshitaB changed the title Add MoE-v2 token permute/unpermute helpers Add token permute/unpermute helpers Jun 11, 2026
@AkshitaB
AkshitaB force-pushed the akshitab/moe-v2-permute-utils branch from b4196ef to 2d7d56e Compare June 11, 2026 23:36
@farhatkevin

Copy link
Copy Markdown
Contributor

@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: 2d7d56e01a

ℹ️ 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 thread src/olmo_core/nn/moe/utils.py Resolved
TianhuaTao and others added 6 commits June 22, 2026 16:39
Adds `nn/moe/utils.py`: the autograd-aware, torch.compile-safe wrapper layer
over the MoE permute/unpermute/chunk-reorder CUDA kernels (with optional Triton
and TransformerEngine backends). Provides:

- permute / unpermute with custom autograd, including fused capacity-drop and
  row-id-map variants (`moe_permute_1d_fused_drop_no_compile`,
  `moe_unpermute_1d_fused_drop_no_compile`, `moe_reorder_rows_permutation`)
- chunk reordering for the grouped-expert layout (TE / CUDA backends)
- small `@torch.compiler.disable` stream/event sync helpers used by EP comm

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- Add docstrings to the public entry points (async_copy_to_cpu,
  moe_reorder_rows_permutation, build_chunk_te_routing_map,
  moe_chunk_reorder_no_compile).
- Remove dead debug code (the LAST_STREAM_ID block, a stale alt copy line,
  a commented clamp).
- Use the builtin `tuple` annotation instead of `typing.Tuple`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Covers the chunk permute/unpermute torch reference paths
(`_chunk_unpermute_torch` zeros out-of-range rows; `_dispatch_permute_by_row_id_map`
honors a provided out buffer) that back `moe_chunk_reorder_no_compile`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rror

Match the rest of the codebase, which guards optional dependencies with
`except ImportError` rather than a broad `except Exception`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rror in mxfp8_utils

Match the import-guard convention used elsewhere (and in nn/moe/utils.py): catch
ImportError rather than a broad Exception for the optional triton and
TransformerEngine imports.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The "te" branch in moe_chunk_reorder_no_compile raises immediately (deprecated).
Flag it with a TODO to revisit — re-enable or remove the dead TE path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@AkshitaB
AkshitaB force-pushed the akshitab/moe-v2-permute-utils branch from 2d7d56e to 95df75d Compare June 22, 2026 23:39

@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: 95df75d95e

ℹ️ 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".

requested_offsets=requested_offsets,
keep_offsets=keep_offsets,
keep_splits=keep_i64,
num_out_tokens=num_out_tokens,

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 Handle zero kept tokens before calling permute-drop

When requested_splits/keep_splits are used and every kept split is zero, this forwards num_out_tokens=0 into moe_permute_drop_fwd. The CUDA wrapper treats num_out_tokens <= 0 as the default sentinel and replaces it with expanded_rows, so an all-dropped microbatch/rank returns a full-sized activation buffer instead of an empty kept-token buffer; downstream expert compute can then process unwritten rows. Please special-case the zero-kept path before this call or use a sentinel that does not collide with a valid zero output size.

Useful? React with 👍 / 👎.

Drop the redundant `_HAS_TRITON` boolean and gate the triton path on
`triton is not None` directly, matching the import-guard convention used
elsewhere (e.g. kernels/mxfp8_utils.py).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@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: e15a6da3bb

ℹ️ 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".

"packed_keep_mask/local_inverse_reorder_indices size mismatch: "
f"{packed_keep_mask.numel()} vs {local_inverse_reorder_indices.numel()}"
)
if inp.shape[0] != packed_keep_mask.numel():

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 Allow kept rows through fused-drop unpermute

When capacity drop removes any routed row, moe_permute_1d_fused_drop_no_compile returns only the kept num_out_tokens rows, while row_id_map, local_inverse_reorder_indices, and this mask still describe the full expanded tokens * topK map. This check rejects the normal kept-only expert output (inp.shape[0] == num_kept < packed_keep_mask.numel()) before the remap can mark dropped entries as -1, so batches with actual drops fail unpermute; compare against num_kept or otherwise allow kept-only input instead.

Useful? React with 👍 / 👎.

Expose `has_triton()` in nn/moe/utils.py (and use it at the triton gate sites),
mirroring `has_te_attn()` / `has_fla()`. Add a `requires_triton` pytest marker
(gpu + skip-if-unavailable) in olmo_core.testing, for the GPU/triton tests that
land later.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@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: 42db597271

ℹ️ 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 thread src/olmo_core/nn/moe/utils.py Outdated
Comment on lines +75 to +76
# NOTE: gpu_buf.record_stream(dtoh_stream) would keep the source alive until the
# copy finishes, but does not work under torch.compile.

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 Keep async copy sources alive

When callers pass a temporary GPU tensor (or otherwise let gpu_buf go out of scope) and wait on the returned event later, the D2H copy is still running on dtoh_stream but the CUDA caching allocator was never told that this stream uses gpu_buf. The storage can be recycled on the default stream before the copy finishes, so split sizes copied by this helper can be corrupted under memory pressure; either record the source on dtoh_stream or otherwise keep/return it until the event is waited.

Useful? React with 👍 / 👎.

TianhuaTao and others added 2 commits June 22, 2026 17:59
…ozen, add GPU tests

The fused index-map unpermute backward gated the whole gradient
computation on the expert-output gradient (input 0). When only the
merging probabilities (input 2) require grad — e.g. frozen/detached
experts with a trainable router — this dropped the probability
gradients entirely. Run the backward whenever input 0 or input 2 needs
grad (the kernel produces both in one pass), only write into the
caller's gradient buffer when the input-0 grad was requested, and drop
whichever gradient was not asked for.

Add GPU tests covering the one-shot custom-CUDA permute+drop path, the
packed unpermute backward buffer, and the frozen-experts prob-gradient
case.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add notes at three spots flagged by review where a defensive concern is
real in principle but does not arise on the actual code paths:

- async_copy_to_cpu: the missing record_stream could let a source buffer
  be recycled mid-copy, but callers pass persistent buffers, and
  record_stream does not work under torch.compile.
- moe_permute_drop_fwd call: num_out_tokens <= 0 collides with the CUDA
  "use expanded_rows" sentinel, but callers always pass the full count.
- moe_unpermute_1d_fused_drop_no_compile: the full-size-input guard is
  correct because the EP paths use full buffers + reorder-to-tail + mask,
  never kept-only input.

Each note records the future-revisit condition.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@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: 0d941c6318

ℹ️ 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".

moe_sort_chunks_by_index,
moe_unpermute,
)
except ImportError:

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 Catch non-ImportError TE import failures

When TransformerEngine is present but unusable or incompletely installed (for example the core package exists but the PyTorch shared object is missing), this import path can raise FileNotFoundError/OSError rather than ImportError. That now escapes during a plain import of olmo_core.nn.moe.utils (and olmo_core.testing, which imports it for has_triton), even though TE is intended to be optional, so the guard should disable the TE helpers for any failed optional import instead of only ImportError.

Useful? React with 👍 / 👎.

AkshitaB and others added 4 commits June 22, 2026 18:52
The runtime install was resolving torch to the new CUDA-13 default 2.10
wheel, which the Beaker nodes' CUDA 12.8 driver cannot initialize. That
made torch.cuda.is_available() False, so every -m gpu test silently
skipped while the jobs still reported success.

Force-reinstall the cu128 torch build in each GPU matrix entry (2.9.1 for
the shared tch291cu128 image, 2.10.0 for the kernels job) and assert CUDA
is available before running pytest, so a recurrence fails loudly instead
of skipping everything. The kernels image is currently a cu130 build, so
this override also brings it back in line with the 12.8 driver; the
durable fix there is a cu128 image or newer-driver nodes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The cu130 image cannot initialize CUDA on the Beaker CUDA 12.8 driver.
Switch back to the cu128 image; the cu128 torch reinstall added to this
job now just guards against the runtime resolving torch to the CUDA-13
default, matching the other GPU jobs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rrectly

gantry execs the command after -- directly (not via a shell), so the
multi-line cu128-reinstall + pytest blocks were being mis-handled:
gantry got no args (the leading comment commented them out) and the
pip/pytest lines ran as separate shell commands. Wrap the per-task
command in `bash -ec "..."` so it runs as one script with errexit (a
failed reinstall or CUDA-availability assert now aborts before pytest),
and drop the double quotes inside the run blocks so they don't clash
with the wrapper.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@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: c3c3130c12

ℹ️ 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".

import triton
import triton.language as tl
except Exception: # pragma: no cover - Triton may be unavailable in some test envs.
except ImportError:

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 Restore broad optional Triton import handling

If a Triton wheel is present but unusable (for example a shared-library or CUDA mismatch that raises OSError/RuntimeError during import), this module now aborts at import time because only ImportError is caught. The rest of mxfp8_utils already treats Triton as optional by setting triton = None and using non-Triton fallbacks where possible, so this regression can break importing MXFP8/kernel code in environments that previously fell back cleanly.

Useful? React with 👍 / 👎.

MXFP8Tensor,
)
except Exception:
except ImportError:

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 Restore fallback for broken TransformerEngine installs

When transformer_engine is installed but one of its native components cannot load, these imports can raise FileNotFoundError/OSError rather than ImportError. _get_te_mxfp8_state() is only used to decide whether to return None and fall back to the Triton path, so the narrowed catch now turns an optional TE failure into a hard failure for MXFP8 quant/dequant; the fresh evidence is that this diff made the same optional-import narrowing in mxfp8_utils, separate from the MoE guard already discussed.

Useful? React with 👍 / 👎.

AkshitaB and others added 2 commits June 22, 2026 23:16
…uat cu128

The shared GPU image already ships torch 2.9.1+cu128 with working CUDA, so
the force-reinstall was unnecessary there and, by leaving torchvision and
torchaudio unpinned, upgraded them to torch-2.10-built wheels — producing
an "undefined symbol: torch_library_impl" ABI break in torchaudio that
failed transformers import collection in the Test (GPU) and Test
transformer (GPU) jobs.

The only job that actually skipped was the MoE kernels job, caused by
switching its image to a cu130 build the Beaker CUDA 12.8 driver cannot
init. Restoring the kernels image to tianhuat/olmo-core-torch210-2404-cu128
fixes that without touching the other jobs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…driver

The kernels image (tianhuat cu128) actually ships a CUDA-13 torch build,
which the Beaker CUDA 12.8 driver cannot initialize, so every kernel test
silently skips. Reinstall the cu128 torch 2.10 build (still provides
torch.nn.functional.grouped_mm) in that job to match the driver, and
assert CUDA is available so a recurrence fails loudly.

Scoped to the kernels job only: the shared GPU image already ships a
working cu128 torch, and the kernel tests don't import torchvision or
torchaudio, so we pin only torch and avoid the ABI mismatch that would
otherwise break the HF-importing jobs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@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: 6dea51c2a8

ℹ️ 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 thread .github/workflows/main.yml Outdated
bash -ec '
pip install --force-reinstall --index-url https://download.pytorch.org/whl/cu128 torch==2.10.0
python -c "import torch; assert torch.cuda.is_available()"
pytest -v --color=yes --durations=3 -m gpu src/test/kernels/

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 Run fused MoE tests in the kernel image

The new fused tests under src/test/nn/moe/v2 call the MoE CUDA extensions (moe_permute_drop_fwd / moe_unpermute_bwd), but this torch-2.10/nvcc job still collects only src/test/kernels/. The standard Test MoE (GPU) workflow section collects src/test/nn/moe* on the torch-2.9 image, while the comment immediately above this job says these MoE kernel tests need the torch-2.10+nvcc image; when TransformerEngine is present, the new tests run in the wrong image instead of being validated here. Include the fused test path in this job or move those tests under src/test/kernels.

Useful? React with 👍 / 👎.

… image

The permute/unpermute tests added under src/test/nn/moe/v2 need
TransformerEngine and the custom .cu kernels, which the shared torch-2.9
GPU image lacks, so they were silently skipping in the "Test MoE (GPU)"
job. Route src/test/nn/moe/v2 to the "Test MoE kernels" job (torch 2.10 +
TE + nvcc + the cu128 reinstall) and exclude it from the torch-2.9 MoE
job. v1 MoE GPU tests stay on the shared image.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@AkshitaB
AkshitaB merged commit d4fdf22 into akshitab/moe-v2-core Jun 23, 2026
46 of 47 checks passed
@AkshitaB
AkshitaB deleted the akshitab/moe-v2-permute-utils branch June 23, 2026 07:11
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.

3 participants