Skip to content

feat(ep/v2): plans report the arena and staging sizes they need (info + describe) - #844

Merged
jhchouuu merged 5 commits into
mainfrom
jiahzhou/ep-v2-plan-sizes
Oct 28, 2026
Merged

jhchouuu merged 5 commits into
mainfrom
jiahzhou/ep-v2-plan-sizes

Conversation

@jhchouuu

@jhchouuu jhchouuu commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Why

An EP v2 plan binds arena offsets but has never known the sizes behind them. The region sizes lived only in hip_backend._regions(), the push combine's landing layout only in ep_intranode_1250x.hpp, and the staging size in a Python mirror of EpStagingTotalBytes. A caller that builds its own arena (aiter's MegaMoE) copies all of those formulas, so every layout change in mori breaks it without an error. #843 is the current example: it changes the staging scale rows and adds an agg_reserve argument to ep_staging_bytes, and a caller that does not pass it under-allocates at EP1/EP2.

This PR makes C++ the single source of those sizes. The plan reports them, a caller can ask for them before the plan exists, and binding refuses an arena or staging buffer that is too small.

What changes

C++ (feat(jit/v2))

  • ep_cfg.hpp now holds the push combine layout (EpCombinePush{Rows,LandRows,WireBytes,LandOff,FlagOff,OvlAny}), moved from the device header, which now calls it. It also adds EpRegion*Bytes for the nine arena regions. None of these depend on launch geometry, so one arena serves every schedule variant.
  • EP plan info gains:
    • region.<stem>=<bytes> for every region, in EpArgs order. The value is 0 where the other kernel's Cfg sizes the region: dispOut and outScales belong to dispatch, outTok to combine.
    • scaleStride and stagingBytes on dispatch plans. stagingBytes is the size the kernel needs, so it is 0 off gfx125x.
    • pushWireBytes, pushLandRows and pushLandOff on push combine plans.
  • New C ABI mori_jit_plan_describe and PlanVTable::describe return the info a plan would report, without compiling.
    • create and describe resolve the request through one helper (request, Cfg, info, source, geometry), so describe runs everything create does except the compile, and fails where create would.
    • Every plan registered through MORI_JIT_DEFINE_PLAN gets it, the internode plans included (their info has no region.* keys).
    • describe is the last vtable field, so the existing fields keep their offsets.
    • Both entry points end with catch (...), so no exception crosses extern "C". create holds its handle in a unique_ptr until the compile returns, so a compile error no longer leaks it.

Python (feat(ep/v2))

  • Plan.describe(**request) exposes the new ABI. plan_api.arena_regions(*infos, region_names=...) (re-exported from ep_plans) turns region.* keys into a SymmArena region list: the largest size per region, in args order, with zero-size regions dropped. Pass the info of every plan bound to the arena: dispatch reports 0 for outTok and combine for dispOut, but binding still needs both regions to exist.

  • A plan built with arena= checks every region it reports against arena.size(name) when the arena has size(). A region a plan reports as 0 is one its kernel never dereferences; the plan that does use it checks it. An arena without size() is still bound, with a FutureWarning that its regions go unchecked.

  • EpDispatchPlan.bind(staging_base=<tensor>) checks the tensor:

    • it must be on the device the plan launches on;
    • its own extent is compared with info["stagingBytes"], and it must be contiguous, so a short slice of a larger buffer is refused;
    • it must be 128 B aligned.

    Once the bind succeeds, the plan holds the tensor and binds its address. An int address is still accepted unchecked, and any other object with data_ptr() is still read at each launch. The fallback staging is sized from info["stagingBytes"].

  • The HIP intranode op describes every (block, warp) variant it will build in its constructor, before the arena exists, and sizes the arena, the staging buffer and the push landing view from those infos. It now decides MORI_EP_TOKOFF_EXT before its gate, so the push combine with TokOffExt is rejected at construction. Before, that config passed the gate, and the op was built with no kernels and failed at the first dispatch.

  • ep_staging_bytes, push_wire_nbytes, push_land_rows and scale_stride_bytes remain as module functions for callers that size without a plan (aiter's MegaMoE calls all four). They are now cached wrappers over describe(), so the formulas live only in C++, and they answer as the plan would:

    • staging is 0 where the dispatch does not stage;
    • the push sizes are gfx125x only, as the push combine is.
  • Unchanged: internode regions, the FlyDSL backend and its arena, and SymmArena.

Layout change

The push combine's per-row flags (one u64 per landing row, after the landing rows in out_tok) are now reserved only where the overlapped reduce can run: push, not fp4_blockwise_fp32, not wide EP, at least four ranks. The previous Python rule reserved them from four ranks up in every case. The kernel reads and writes the flags only under EpFp4Ovl<kCfg>(), which implies EpCombinePushOvlAny (a static_assert in the combine body holds it), so the smaller out_tok is never overrun. Every other region keeps its size and order. In those configs the regions after out_tok (cross_device_barrier, out_scales) start that much lower; offsets are bound at runtime, so nothing depends on them.

For callers that build their own arena

d = EpDispatchPlan.describe(**dispatch_request)   # no compile
c = EpCombinePlan.describe(**combine_request)
regions = arena_regions(d, c, region_names=my_region_names)   # merge into the caller's arena
staging = torch.zeros(d["stagingBytes"], dtype=torch.uint8, device=dev)
plan = EpDispatchPlan(**dispatch_request, arena=arena, region_names=my_region_names)
plan.bind(staging_base=staging)                   # checked against the plan

An arena class only needs size(name) to get the bind-time check.

Testing

  • tests/cpp/jit/test_jit_core.cpp (no GPU):
    • EpStagingTotalBytes is pinned to the values the Python mirror's test pins.
    • Push wire, land rows and outTok are checked for fp4, fp4b and fp8 at ws 2, 4, 8 and 64, along with every region size.
    • describe is called through the vtable under a fake gfx1250 toolchain and a fake gfx942 toolchain.
    • jit_host_device_split passes.
  • test_jit_binding.py:
    • describe() equals .info apart from cacheDir.
    • The region keys follow args order.
    • arena_regions matches the layout the op used to build across dispatch dtypes, scales, topk and world sizes. The push cases run on gfx125x.
    • stagingBytes matches ep_staging_bytes.
    • The module functions give the C++ values on gfx125x, and the push ones raise elsewhere.
    • A short arena is refused, and so is a short, sliced, misaligned or off-device staging tensor. A failed bind holds no staging. An arena built from only one plan's regions cannot be bound, and one without size() warns.
    • Result: 113 passed on gfx1250.
  • gfx950, EP8, hip and flydsl backends:
    • test_op, test_asym_dtype, test_graph_capture, test_op_lifecycle, test_routing_snapshot, test_ep_backend_parity and test_internode_regions pass.
    • test_dispatch_combine_v2_intranode with the hip backend gives the same results as main: the 11 configs the hip backend rejects at its gate fail on both.
    • bench_ep (pull, eager) at 512 tokens per rank: same time as main.
  • gfx1250, EP4:
    • test_op (topk 4, 8, 9 and scales), test_asym_dtype (fp8, fp4), graph capture, lifecycle, snapshot and backend parity pass.
    • With MORI_EP_TOKOFF_EXT=1, bf16 test_op passes on main and on this branch. With a push quant type, main builds the op and fails at the first dispatch with KeyError; this branch rejects the config at construction.
    • bench_ep correctness and timing were run interleaved against main at 128 and 512 tokens per rank, two rounds: bf16, fp8 and fp4 dispatch with the fp4 push; bf16 dispatch with the fp8 and fp4b push; and pull. Every point verifies, and times match main.
  • gfx1250 code objects for dispatch (bf16, fp8+scales, fp4+scales) and combine (bf16, fp4, fp4b, fp8 push) at ws 4/8 and warps 16/24 are instruction-identical to main. Only assert string addresses differ.
  • Building the op on main and on this branch for 24 configs (bf16/fp8/fp4 dispatch × pull/fp4/fp4b/fp8 push × 512/4096 tokens per rank) yields the same arena layout, staging size, Cfg, geometry and bound arguments for every plan. The only difference is the fp4b out_tok flag area described above.

Relation to #843

#843's new Cfg fields (callTokMax, ll128, ll128CombineOnly) are what its extra sizes depend on. On top of this PR they become cases in EpStagingScaleBytes and the EpRegion* functions, and callers pick them up through stagingBytes and region.* with no change on their side. The op already takes the largest size over all of its plans, which covers one LL128 plan among several and per-bucket callTokMax.

Pre-existing on main, seen while testing (not changed here)

  • gfx1250 EP4 at 4096 tokens per rank: the bf16 dispatch reports byte mismatches and an fp8 dispatch hung. The arena, Cfg and arguments are identical with and without this PR.
  • TUNED=1 test_op.py (hip backend, gfx1250): the ep_dispatch launch returns invalid argument at 512 tokens; main fails the same way.
  • bench_ep.py graph mode on gfx950 EP8 (hip): the ep_dispatch launch returns invalid argument during capture, on main as well.
  • The fp4b push combine does not compile at 24 warps per block on main either: static_assert(kOvlp || kTileB >= kStageOff + kStageB).
  • test_op.py with COMBINE=scatter and a push quant type raises NotImplementedError on main as well: the test passes weights to combine, and the push combine folds none. The push combine's correctness is covered by bench_ep.

🤖 Generated with Claude Code

jhchouuu and others added 2 commits October 26, 2026 13:00
A plan bound arena offsets but knew no sizes: the region sizes lived only in
hip_backend._regions(), the push combine's landing layout only in the device
header, and every out-of-tree caller (aiter's MegaMoE) copied those formulas.
A layout change in mori then broke its callers silently.

- ep_cfg.hpp: the push combine layout (EpCombinePush{Rows,LandRows,WireBytes,
  LandOff,FlagOff,OvlAny}) moves here from ep_intranode_1250x.hpp, which now
  calls it; plus EpRegion*Bytes for the nine arena regions. Region sizes do
  not depend on geometry, so one arena serves every schedule variant.
- EP plan info gains region.<stem> (0 where the other kernel's Cfg sizes the
  region), scaleStride and stagingBytes (dispatch; 0 off gfx125x), and
  pushWireBytes/pushLandRows/pushLandOff (push combine).
- New C ABI mori_jit_plan_describe + PlanVTable::describe: a request's info
  without compiling, so a caller can size buffers before building the plan.
  Every plan registered through MORI_JIT_DEFINE_PLAN gets it.
- The push row flags are now reserved only where the overlapped reduce can
  run (not for fp4_blockwise_fp32, not for wide EP). The previous Python
  rule reserved them from four ranks up regardless; nothing else in the
  layout moves.

The gfx1250 code objects are instruction-identical to main for dispatch
(bf16/fp8/fp4) and combine (bf16, fp4/fp4b/fp8 push) at EP4/EP8; only assert
string addresses differ.

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

- plan_api: Plan.describe(**request) returns the info a plan would report,
  without compiling; arena_regions(*infos, region_names=) turns their
  region.<stem> keys into a SymmArena region list (largest per region, args
  order, zero-size regions dropped). A plan built with an arena that has
  size() checks every region against what it needs and refuses a short one.
- ep_plans: EpDispatchPlan.bind(staging_base=<tensor>) checks the tensor
  against info["stagingBytes"] and 128 B alignment and holds it; an int
  address is taken on trust as before. The fallback staging is sized from
  info["stagingBytes"].
- hip_backend: the intranode op describes every (block, warp) variant it
  will build and sizes the arena, the staging buffer and the push landing
  view from those infos instead of its own formulas.
- ep_staging_bytes, push_wire_nbytes, push_land_rows and scale_stride_bytes
  stay as module functions for callers that size without a plan; tests pin
  them to the C++ values.

Internode regions and the FlyDSL backend are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@jhchouuu
jhchouuu requested a review from kawhil-amd October 26, 2026 13:06
- EpDispatchPlan.bind(staging_base=<tensor>) measures the tensor's own
  extent (it must be contiguous) rather than its storage's: a short slice of
  a larger buffer passed the check and the kernel wrote past it.
- PlanVTable::describe moves to the end of the struct, so the fields an op
  library registers keep their offsets; mori_jit_plan_describe refuses a
  plan that registers none.
- The HIP op decides MORI_EP_TOKOFF_EXT before its gate, so the push
  combine with TokOffExt is rejected at construction. Before, it passed the
  gate, and the op was built with no kernels and failed at the first dispatch.
- arena_regions() and the short-arena error say to pass the info of every
  plan bound to the arena: each EP plan reports 0 for the region the other
  kernel sizes, yet binding still needs that region to exist.
- Tests pin push_wire_nbytes, push_land_rows and scale_stride_bytes to the
  C++ values (and to describe() where it applies); the fake arena raises
  KeyError for a missing region, as SymmArena does.

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

@kawhil-amd kawhil-amd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of #844. Four points could cause a crash or silent corruption (describe's catch, staging bind checks, arena size check, OvlAny/EpFp4Ovl coupling). The rest are maintainability notes. See the inline comments.

Comment thread src/jit/v2/plan_api.cpp
return s.c_str();
} catch (const std::exception& e) {
SetPlanError(e.what());
return nullptr;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bug: mori_jit_plan_describe catches only std::exception. The other ABI entries (mori_jit_plan_args_schema, request_schema, args_size) end with catch (...), and this file's own comment says an exception crossing extern "C" terminates the interpreter. A non-std throw from REQUEST_FN / RenderSource / INFO_FN kills the process. describe is new and is called from the op constructor for every variant, so please add catch (...) that calls SetPlanError("unknown error") and returns nullptr.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed. mori_jit_plan_describe now ends with catch (...), which calls SetPlanError and returns nullptr. mori_jit_plan_create had the same gap, so it gets the same handler.

)
if buf.data_ptr() % 128:
raise ValueError("ep_dispatch: staging_base must be 128 B aligned")
self._staging = buf

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bug: the staging validation has gaps.

  • It runs only for objects with untyped_storage, and checks size and alignment but not device or dtype. A CPU tensor passes and is bound as a device pointer, so the kernel faults.
  • An object with data_ptr() but no untyped_storage skips every check. Before this change such an object was re-read on every launch, so that case worked.
  • self._staging = buf is assigned before super().bind runs. If the bind fails, _staging holds a buffer that was never bound.

Suggest: check device (and that it is a CUDA/HIP tensor) in the same branch, and assign _staging only after super().bind succeeds.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed two of these; the third is intended.

  • Device. A staging tensor must now be on the device the plan launches on (cuda:<current>). A CPU tensor is refused at bind.
  • Bind order. _staging is assigned only after super().bind() returns. Tests cover both.
  • dtype. Not checked on purpose: the size is counted in bytes (numel * element_size), and the kernel addresses the buffer as bytes.
  • Objects with data_ptr() but no untyped_storage. These pass through on purpose. The plan's own _FallbackStaging is one of them. Such an object is read at every launch, exactly as before this PR, so nothing changed for it. Only a tensor can be checked at bind time.

# trusted, as before.
info = self.info
for region in arg_regions.values():
need = int(info.get(_REGION_KEY + region, 0))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Risk: this guard can be bypassed.

  • An arena without size() is accepted unchecked. A too-small arena is then overrun silently, on a peer as often as locally.
  • A region the plan reports as 0 is skipped (if not need: continue), but the plan still binds that region's offset. Dispatch reports region.outTok=0 yet binds offOutTok, so an arena whose out_tok region is tiny (or is not the combine's buffer) passes.

The guard therefore depends on the caller passing the info of every plan, which is the failure mode this PR sets out to close. Consider raising when size() is missing, and checking every region the plan binds, not only need > 0.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Arenas without size(). Refusing them outright would break every caller whose arena predates this PR; aiter's MegaMoE on main is one. Instead, binding such an arena now raises a FutureWarning that says its regions go unchecked and that unchecked arenas will be refused. aiter's next MegaMoE update (ROCm/aiter#6430) adds size().

Regions reported as 0. These are not a gap. A plan reports 0 exactly for the regions its kernel never dereferences:

  • For dispatch and outTok, every read of args.offOutTok is in combine code: EpFp4CombineSend, EpFp4ReducePrep, EpFp4ReduceWs, EpFp4OvlRound and EpCombine1250xBody in ep_intranode_1250x.hpp, and EpCombineBody in ep_intranode_kernel.hpp. So a tiny outTok cannot be overrun by the dispatch plan.
  • The combine plan reports outTok and checks it at its own bind. Every region is therefore checked by each plan that touches it, whichever infos the caller passed to arena_regions.
  • This is also what lets aiter bind dispatch's outTok to its own comb_inp; test_a_region_the_other_kernel_sizes_is_not_checked pins it.

I updated the comment in _check_arena to say this.

return EpCombinePushLandOff(c) + (size_t)EpCombinePushLandRows(c) * EpCombinePushWireBytes(c);
}
// True when some warp count takes the overlapped reduce (EpFp4Ovl), the row flags' user.
constexpr bool EpCombinePushOvlAny(const EpCfg& c) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Risk: the host sizing predicate EpCombinePushOvlAny and the kernel predicate EpFp4Ovl are tied only by a comment. The row-flag area is sized only when EpCombinePushOvlAny holds, but the kernel reads and writes it under EpFp4Ovl. If someone adds a warp or world-size arm to EpFp4Ovl and forgets OvlAny, the flags land past the end of out_tok (into cross_device_barrier / out_scales): silent corruption on a peer. The old Python rule over-reserved and hid this class of drift. Please add a static_assert that EpFp4Ovl<kCfg>() implies EpCombinePushOvlAny(kCfg) for the instantiated cfgs.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added in EpCombine1250xBody, which is instantiated for every combine Cfg:

static_assert(!EpFp4Ovl<kCfg>() || EpCombinePushOvlAny(kCfg),
              "EpFp4Ovl must imply EpCombinePushOvlAny, which sizes its row flags");

Today the implication holds by construction, because EpFp4Ovl is written as EpCombinePushOvlAny(kCfg) && (...). The assert keeps it holding if that expression is ever rewritten.

h->plan.geom.sharedBytes, h->cfgKeyValues, \
h->cfgText, h->cacheDir); \
} \
std::string NAME##PlanDescribe(const ::mori::jit::v2::FieldBag& f) { \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Design: NAME##PlanDescribe re-implements part of NAME##PlanCreate (request, render, geometry, info) and does not run Prepare or the other checks create performs. The comment says describe "fails where create would, short of a compile error". If Prepare, CacheDirFor or a future Spec hook adds validation (e.g. an LDS or geometry limit), describe succeeds and create throws, after the SymmArena window has already been taken. Please share one helper that resolves the request and the info between create and describe.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done. Create and describe now resolve a request through one helper, NAME##PlanResolve. It produces the Cfg, the rendered Cfg, the info, the source and the geometry.

  • create then adds the cache dir and calls Prepare.
  • describe formats the info.

Prepare is the generic KernelSpec::Prepare (geometry plus compile), and no Spec overrides it. So describe now runs everything create runs except the compile. Any validation added to the request, render, info or geometry path applies to both.

While there, create now holds its handle in a unique_ptr until Prepare returns, so a compile error no longer leaks it.

@@ -147,7 +147,8 @@ def ep_staging_bytes(
) -> int:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maintainability: the Python mirrors (ep_staging_bytes, scale_stride_bytes, push_wire_nbytes, push_land_rows) still hold the same formulas as the new C++ source of truth. This works against the goal of a single source, and #843 (staging scale rows, agg_reserve) will make them drift. The push comparisons only run on gfx125x (they return early when sharedBytes is 0), so CI on gfx942/gfx950 will not catch it. Suggest describe-backed wrappers, or dropping the mirrors (the two push helpers are test-only now).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed. All four are now thin, lru_cached wrappers over describe(), so the formula lives only in C++.

I kept them as functions because aiter's MegaMoE calls all four. Their results now follow the plan:

  • ep_staging_bytes returns 0 where the dispatch does not stage.
  • push_wire_nbytes and push_land_rows raise off gfx125x, as the push combine does.

On gfx1250 the values are unchanged (12746752 / 4358144 / 50987008 / 5248 for staging, 3840 / 7424 for the push wire, the same landing rows), and the C++ tests still pin them. With MORI_JIT_ARCH set, the wrappers need no GPU.

The tests no longer compare a mirror with describe(). They pin the values on gfx125x, and on other arches they check that the push helpers raise.

return scale_stride_bytes(cls._scale_i32(cfg) * 4) // 4
return self._disp_infos[0]["scaleStride"]

def _regions(self, cfg):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maintainability: _regions() now has a side effect: it fills self._disp_infos / self._comb_infos, which are empty placeholders until it runs. Code that calls scale_stride_bytes() or push_landing() before _regions gets an IndexError from self._disp_infos[0] / self._comb_infos[0]. Also, _tokoff_wanted is always set before the gate now, so the getattr(self, "_tokoff_wanted", False) guard is dead code. Consider computing the infos in __init__ and passing them to a pure region builder.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done. The op now calls _describe(cfg) in __init__, right after the gate and before the arena is built. _regions only merges the infos it returns, so scale_stride_bytes() and push_landing() see the infos from construction on. The dead getattr(self, "_tokoff_wanted", False) is now a plain self._tokoff_wanted.

)
view = self._views.get("push_landing")
if view is None:
info = self._comb_infos[0]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor: push_landing reads self._comb_infos[0] and assumes every combine variant reports the push keys. If _combine_specs is empty (e.g. filtered by cfg.schedule), this raises a bare IndexError, and a mismatch between _PUSH_QUANT_TYPES and _plan_requests would raise KeyError. The quant_type guard checks the config, not the infos. A clear error message would help.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done. push_landing now takes the first combine info that reports pushLandRows. If none does, it raises with a message naming what is missing. The quant-type guard before it still rejects ops that are not push.

recv,
info["scaleBytes"],
info["maxTokPerRank"],
info["stagingBytes"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: info["stagingBytes"] is a pure function of worldSize, maxRecv, scaleBytes and maxTokPerRank, which the key already holds. Adding it is redundant state that can only split otherwise identical fallback buffers. Key on (device, stagingBytes) alone.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Dropped stagingBytes from the key.

I kept the four layout fields rather than keying on (device, stagingBytes) alone. With only the size in the key, two plans with different Cfgs but equal staging sizes would share one scratch buffer, which they do not today.

- C ABI: mori_jit_plan_describe and mori_jit_plan_create end with catch (...),
  like the other entries; an exception must not cross extern "C".
- create and describe resolve a request through one helper
  (NAME##PlanResolve); describe runs everything create does but the compile.
  create holds its handle in a unique_ptr until Prepare returns, so a compile
  error no longer leaks it.
- The combine body static_asserts that EpFp4Ovl implies EpCombinePushOvlAny,
  the predicate that sizes the row flags.
- scale_stride_bytes, ep_staging_bytes, push_wire_nbytes and push_land_rows
  are cached wrappers over describe() instead of copies of the C++ formulas.
  They follow the plan: staging is 0 where the dispatch does not stage, and the
  push sizes are gfx125x only, as the push combine is.
- The HIP op describes its plans in __init__, before the arena; _regions only
  merges the infos. push_landing names what is missing instead of raising
  IndexError.
- A staging tensor must be on the plan's device and is held only once the bind
  succeeds. The fallback staging key drops the redundant stagingBytes.
- A plan bound to an arena without size() warns (FutureWarning) that its
  regions go unchecked.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
jhchouuu added a commit to jhchouuu/aiter that referenced this pull request Oct 27, 2026
…m the recipe

On a mori with Plan.describe() (ROCm/mori#844), the mori stages ask it for
their arena regions and the dispatch's staging bytes -- the numbers mori's own
kernels and its bind-time size check use -- instead of keeping formulas that
mirror them. Each stage builds its plan request in one place (request()), which
both describe() and the plan take. describe() compiles nothing and resolves
against gfx1250 by name, so required_vmm_bytes stays off the GPU; the slot
word's kwargs stay out of it, since where that word lives sizes nothing and
asking would be collective. An older mori keeps the formulas.

SymmetricArena.size() lets a ROCm#844 plan check its regions at bind.

bench_mega_moe builds from a MegaMoERecipe and sizes its communicator with
required_vmm_bytes(recipe, geometry) instead of a fixed 16 GiB.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
jhchouuu added a commit to jhchouuu/aiter that referenced this pull request Oct 27, 2026
A mori with ROCm/mori#844 checks a staging tensor against the plan's
stagingBytes, device and alignment at bind, and holds it; an address is taken
on trust. An older mori reads the tensor's address at each launch, as it did
the int.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
jhchouuu added a commit to jhchouuu/aiter that referenced this pull request Oct 27, 2026
…m the recipe

On a mori with Plan.describe() (ROCm/mori#844), the mori stages ask it for
their arena regions and the dispatch's staging bytes -- the numbers mori's own
kernels and its bind-time size check use -- instead of keeping formulas that
mirror them. Each stage builds its plan request in one place (request()), which
both describe() and the plan take. describe() compiles nothing and resolves
against gfx1250 by name, so required_vmm_bytes stays off the GPU; the slot
word's kwargs stay out of it, since where that word lives sizes nothing and
asking would be collective. An older mori keeps the formulas.

SymmetricArena.size() lets a ROCm#844 plan check its regions at bind.

bench_mega_moe builds from a MegaMoERecipe and sizes its communicator with
required_vmm_bytes(recipe, geometry) instead of a fixed 16 GiB.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
jhchouuu added a commit to jhchouuu/aiter that referenced this pull request Oct 27, 2026
A mori with ROCm/mori#844 checks a staging tensor against the plan's
stagingBytes, device and alignment at bind, and holds it; an address is taken
on trust. An older mori reads the tensor's address at each launch, as it did
the int.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Resolves the conflicts with #768 (AsyncLL):
- AsyncLL, like internode, sizes its arena from its own formula
  (asyncll_regions), so the op describes no intranode plans for it.
- The TokOffExt decision, taken before the gate, also excludes AsyncLL.
- scale_stride_bytes() returns the packed row on AsyncLL, as on internode.
- tests/cpp/jit/test_jit_core.cpp keeps both the AsyncLL and the describe tests.
jhchouuu added a commit to jhchouuu/aiter that referenced this pull request Oct 28, 2026
…pe first

The recipe
- The expert GEMM's fields move into ExpertComputeConfig, nested as
  MegaMoERecipe.compute; the recipe's own fields are the transport's.
- Which pairings run is declared by the stages: a dispatch names the wires it
  carries and the BatchLayout it delivers (token-major or expert-grouped), a
  combine the layouts it accepts and the wires it offers. The recipe checks
  against those, and its errors name recipe fields (dispatch=, combine=,
  dispatch_wire=, combine_wires=). Each stage's geometry check (check()) runs
  from MegaMoEConfig.
- from_recipe is the entry point. The keyword constructor warns
  DeprecationWarning; the underscored members ATOM's Triton experts use are
  documented as kept for them. The facade reads geometry and compute fields
  through properties rather than copying them.

The stages
- DispatchStage and CombineStage (Protocols) say what each provides; every
  stage has regions(config, caps) and check(config), and is built as
  Stage(config, caps). The compact- and mori-only attributes are gone from the
  shared base.
- Each dispatch stage owns the stride its e8m0 rows arrive at (scale_stride),
  replacing MegaMoEConfig.dispatch_scale_dst_nbytes.
- The batch carries its layout explicitly, and an expert-grouped one an
  ExpertGrouping; the combine hands the grouped GEMM its dispatch context in
  the _ComputeTarget, so the expert GEMM does not branch on the layout.
- Whether the combine needs mori's aggregated reservation and whether the
  dispatch makes it are each stage's to say; the dispatcher refuses the pair
  before the arena exists.
- One schedule pick (_pick) serves both mori plans and the compact kernels;
  _quantize returns the scale rows' address instead of leaving it in state.
- _EpDispatcher has dispatch/prepare/combine/prefetch/warmup and the recv
  views, so forward() does not reach into the stages, and close() releases the
  rest even when one part raises.

mori
- _MoriCapabilities needs Plan.describe() (ROCm/mori#844). Regions, staging
  bytes and the scale stride come from there, so the copies of mori's formulas
  and the older-mori branches are gone; such a mori also overwrites
  total_recv in its dispatch, which is why nothing zeroes it.
- _XDB_FLAG_SLOTS, TokOffExt and the plan constructors are reached only
  through _MoriCapabilities.

Checks
- An out-of-range recv_token_bound (and next_recv_token_bound) raises on the
  compact dispatch as on mori's, in dispatch, prefetch and warmup.
- a1_scale on a quantizing dispatch wire raises ValueError (was an assert).
- The keyword form of required_vmm_bytes raises when no candidate recipe runs
  at the geometry, instead of returning 0.
- _MoriCombine.prepare documents why writing fused_moe's rows straight into
  comb_inp is safe: the next dispatch does not finish until every peer has
  dispatched, which each does only after its own combine.

Tests: the CPU test fakes mori from describe() alone and covers the stage
contract messages, the bound checks and the keyword-bound refusal; the
multi-GPU test builds through from_recipe and checks the deprecated keyword
constructor against it. bench_moe_gemm_a4w4_cudagraph builds through
from_recipe.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@jhchouuu
jhchouuu merged commit b853716 into main Oct 28, 2026
21 of 25 checks passed
@jhchouuu
jhchouuu deleted the jiahzhou/ep-v2-plan-sizes branch October 28, 2026 14:38
zhangfei829 added a commit that referenced this pull request Oct 29, 2026
Size the LL128 arena regions through #844's plan info: EpRegionOutTokBytes counts the LL128 landing rows, the LL128 dispatch reports its stage in region.tokOff, and a split op's ll_* regions come from its LL128 plans' describe(). Every dispatch variant (callTokMax) is described, so stagingBytes covers them all, and the fallback staging key carries callTokMax. Drop the tok_off_ext request and the TokOffExt gate main added; this branch removed both.
JiaoliangYu pushed a commit to ROCm/aiter that referenced this pull request Oct 30, 2026
…tches, mori combine path, current mori EPv2 (#6430)

* MegaMoE: stage1_fused/stage2_fused switches, mori combine path

* bench_mega_moe: fix kernel table on multi-stream graphs

* MegaMoE: follow mori tokoff-ext and selfFirst defaults

* bench_mega_moe: --fused_shared_experts as ATOM DP+EP runs them

* MegaMoE: follow mori#726 and size mori's fp4 combine flags

Four fixes to the mori dispatch/combine path (stage1_fused/stage2_fused
off), each from driving mori's plans without its op layer:

- dispatch: since ROCm/mori#726 the plan takes tok_off_ext and derives
  selfFirst itself; self_first_enabled() is gone, so importing it fails.
- tuning lookup: key it on the dispatch wire the way mori's op layer
  does ("fp4_disp_bf16_comb" for fp4). Under the hard-coded "bf16" key
  topk 9 matched no entry and both dispatch and the fp4 combine fell
  back to the single-shot default.
- comb_inp: add the overlapped fp4 combine's u64 flag per landing row
  (four ranks up). Its 24-warp geometries write them past the region,
  i.e. past the arena: a page fault at 16384 tokens a rank.
- close(): synchronize first, so a launch still in flight does not read
  a window that has been freed.

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

* MegaMoE: zero-copy hand-off from fused_moe to mori's combine

With stage2_fused off, fused_moe's rows went into a fresh tensor and then
into mori's staging rows (comb_inp): the bf16 combine copied them in its
own kernel, the fp4 one through a host-issued copy whenever the recv bound
was below max_recv -- every decode step under ATOM.

Have fused_moe write them there directly. fused_moe(output=) already
existed but the gfx1250 grouped path ignored it and copied at the end;
thread it down to the gather-reduce. mori's bf16 combine then sees its
input at the staging base and skips the copy, and the fp4 send reads the
staging rows in place.

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

* MegaMoE: follow mori#745/#746 on the mori dispatch/combine path

mori's gfx1250 dispatch now reserves its slots once per destination (the
aggregated reservation, ROCm/mori#745) and hands the push combine its landing
offsets through the dispatch. MegaMoE drives the plans directly, so it has to
size and pass what mori's op layer does:

- dest_pe_token_counter holds 2 * world_size ints: send counts, then per
  destination the reservation base and the push combine's landing offset.
  It held world_size; the dispatch wrote the second half into allocator
  padding.
- recv_num signals are 8 bytes a source. The region held 4 bytes a source;
  the arena's 256-byte alignment hid the overrun.
- The combine reads its landing offsets from dest_pe_token_counter, which
  MegaMoE did not pass, so the mxfp4 combine (stage2_fused=False) got a null
  pointer there.
- MORI_EP_TOKOFF_EXT=1 turns the aggregated reservation off, so a mori push
  combine is refused with it, as mori's op layer refuses it.
- The push landing rows come from mori's push_land_rows(): one per (token,
  destination rank), max_tokens * min(world_size, topk) rather than
  world_size * max_recv.
- The mori dispatch launcher drops total_recv.zero_(): gfx1250's dispatch
  overwrites the count (since ROCm/mori#599), and mori's op layer skips the
  same zero there.

Against a mori from before #745 the landing rows keep the old count and the
two larger buffers have unused tails.

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

* MegaMoE: bind mori's dispatch staging buffer (ROCm/mori#703)

mori#703 moves the gfx1250 dispatch's staging arrays out of each kernel
module's .bss into one buffer the caller allocates and binds as
staging_base; an unbound plan is refused on the host. MegaMoE drives
EpDispatchPlan directly, so it allocates ep_staging_bytes() once and binds
it to every dispatch plan (they never run at the same time), and drops it
after the plans on close(). A mori without ep_staging_bytes keeps the .bss
arrays and is left as is.

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

* MegaMoE: keep accepting dispatch_backend

stage1_fused now picks the dispatch, and the dispatch_backend argument and
config field went away with that. Callers still pass it (ATOM main passes
dispatch_backend="mori" on a quantizing wire; ROCm/ATOM#2384 passes
"flydsl" or "mori" alongside stage1_fused) and log
mega._config.dispatch_backend, so both would fail on this aiter.

Accept the argument again and check it against stage1_fused: "mori" is
stage1_fused=False, "flydsl" is the compact plan. A "flydsl" without
stage1_fused asked for the FlyDSL token-major dispatch, which no longer
exists, so it is refused rather than run on mori. MegaMoEConfig gets a
read-only dispatch_backend derived from stage1_fused.

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

* ci: run the MegaMoE bench on mori's dispatch

stage1_fused=false with stage2_fused=true is mori's fp4 dispatch with the
fused combine (the bench's auto wire is fp4 for a4w4_mxfp4), the
configuration DeepSeek-R1 serves with.

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

* MegaMoE: gfx1250 behaviour tests ahead of the refactor

test_mega_moe_gfx1250.py pins what a change to MegaMoEGfx1250's
dispatch/combine wiring must keep, through the constructor and members its
callers use today:

- every dispatch/combine pairing matches the fp32 reference, and a captured
  graph replays bit for bit what eager produced;
- the pairings MegaMoE rejects fail before the symmetric arena is allocated;
- mori's combine reads fused_moe's rows in place (zero-copy staging);
- close() releases the plans before the window, the window before its memory;
- the members ATOM's Triton experts reach (_dispatch, _combine, _arena, _config).

It spawns its own ranks and skips (exit 0) off gfx1250, below two GPUs or
without mori, so CI's MULTIGPU job can run it on gfx950.

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

* MegaMoE: build from a MegaMoERecipe and a MegaMoEGeometry

A caller now says what to run once, as a recipe, and MegaMoE builds it:

    recipe = MegaMoERecipe(dispatch=DispatchKind.MORI,
                           combine=CombineKind.FUSED_SCATTER,
                           dispatch_wire="fp4", combine_wires=("bf16", "fp4"),
                           activation=..., quant_type=...)
    geometry = MegaMoEGeometry(rank, world_size, model_dim, inter_dim,
                               experts, topk, max_tokens_per_rank)
    mega = MegaMoEGfx1250.from_recipe(recipe, geometry, communicator=comm)

- MegaMoERecipe holds the transport (dispatch and combine kind, dispatch wire,
  the combine wires to build) and the expert-GEMM recipe; frozen and hashable,
  so a caller can key its cache of instances on it. MegaMoEGeometry holds the
  model and EP shape.
- MegaMoERecipe.from_legacy is the one reader of stage1_fused, stage2_fused,
  dispatch_backend and the $MEGA_DISPATCH_WIRE / $MEGA_COMBINE_QUANT defaults.
  The keyword constructor goes through it, so both entries build the same thing.
- MegaMoEConfig is now that recipe resolved against a geometry: frozen, with
  the same properties as before (stage1_fused, stage2_fused and
  dispatch_backend included, for the callers that read them). The dispatch
  schedule it used to have written into it lives on the instance; the
  dispatch_block_num / dispatch_warp_num_per_block fallback it carried was
  never reached.
- forward() takes combine_wire= (bf16 | fp8 | fp4), the recipe's vocabulary,
  alongside combine_quant=.

Every check and its message is unchanged.

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

* MegaMoE: probe mori once, and decide everything before the arena exists

_MoriCapabilities gathers what MegaMoE needs to know about the installed mori --
the plan classes, the tuning lookup, and each helper a mori PR added
(scale_stride_bytes #593, push_wire_nbytes #719, push_land_rows #745,
ep_staging_bytes #703, TokOffExt.wanted #726, self_first_enabled) -- into one
cached probe, and the decisions that hang off them into its methods: the tuned
schedules, the landing-row sizes, the staging size, where the slot word lives.
The ImportError/hasattr branches are gone from the pipeline; the RuntimeError
messages for an mori that is too old are unchanged.

_plan_transport runs all of it, plus the fused reduce's tiles and mori combine's
block/epoch-slot check, before the symmetric arena is allocated. A
configuration that cannot run -- mori missing, MORI_EP_TOKOFF_EXT=1 with mori's
fp4 combine, no reduce tile, too many combine blocks -- now fails with nothing
allocated instead of leaking the arena. TokOffExt.wanted, collective when
MORI_EP_TOKOFF_EXT is on, moves ahead of the arena's own collective allocation
on every rank alike.

The compact dispatch with the fused combine still never loads mori's ops.

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

* MegaMoE: one arena layout, and required_vmm_bytes from it

The arena's regions now come from one formula, _arena_layout: the dispatch
says what it writes (_dispatch_regions: the routing both kinds share, then its
own rows), the combine what it stages through (_combine_regions), and
_ArenaLayout.merge lays them down in the order the pipeline always used, so
every pairing keeps the offsets it had. SymmetricArena takes the layout (or a
region list, as before) and frees its memory if the window registration fails.

MegaMoEGfx1250.required_vmm_bytes(recipe, geometry) reports the same layout,
rounded the way ccoMemAlloc rounds an allocation -- the per_rank_vmm a caller
needs for this MegaMoE, before any communicator exists, and exactly what the
constructor then allocates. It is MegaMoE's share only; a communicator that
also carries mori's own EP ops needs theirs on top.

required_vmm_bytes(world_size=, hidden_dim=, max_tokens_per_rank=, experts=,
topk=, stage1_fused=), the keyword form #6525 proposed and ATOM's
yanbo/mega already calls, still works: it names neither wires nor combine nor
inter_dim, so it returns the largest any recipe with that dispatch takes.

_compact_gemm_align_m reads activation, quant type and inter_dim off the
config instead of taking them separately.

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

* MegaMoE: dispatch and combine stages under one dispatcher; linear forward

The transport is now two stages the recipe picks, over one shared arena:

  _MoriDispatch / _CompactDispatch   tokens out to their experts' ranks
  _MoriCombine / _FusedScatterCombine   results back, summed per token

Each declares its arena regions (regions(), pure -- what _arena_layout and
required_vmm_bytes merge), plans in __init__ with nothing allocated, and
allocates in build(). They meet only through _EpResources (the arena, the
routing state both ends read, TokOffExt), the _DispatchBatch the dispatch hands
the expert GEMM, and the _ComputeTarget the combine has it write into.
_EpDispatcher picks the two from tables, runs every check before the arena is
allocated, and frees what was built when a later step fails -- the arena and
plans used to leak. close() goes: synchronize, combine plans, dispatch plans,
staging, arena, TokOffExt.

forward() is now: pick the step's combine wire, check the inputs, dispatch,
prepare, compute, finish. The compact plan's machinery -- slots, side stream,
per-step geometry (_CompactStep, now immutable) -- lives in _CompactDispatch,
and the next layer's plan launches at the end of its dispatch, the same place
on the GPU streams as before. The recv views are made once at build instead of
per step. The TDM dispatch keeps only its compact arm; the token-major arms
were unreachable once stage1_fused=False went through mori.

Kept for the callers that reach past forward(), ATOM's Triton experts among
them: _config, _arena, _dispatch() and its 5-tuple, _combine(),
_recv_dispatch_scales(), prefetch_compact_plan(), warmup_compact_plan().

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

* MegaMoE: size mori's regions from describe(); the bench sizes cco from the recipe

On a mori with Plan.describe() (ROCm/mori#844), the mori stages ask it for
their arena regions and the dispatch's staging bytes -- the numbers mori's own
kernels and its bind-time size check use -- instead of keeping formulas that
mirror them. Each stage builds its plan request in one place (request()), which
both describe() and the plan take. describe() compiles nothing and resolves
against gfx1250 by name, so required_vmm_bytes stays off the GPU; the slot
word's kwargs stay out of it, since where that word lives sizes nothing and
asking would be collective. An older mori keeps the formulas.

SymmetricArena.size() lets a #844 plan check its regions at bind.

bench_mega_moe builds from a MegaMoERecipe and sizes its communicator with
required_vmm_bytes(recipe, geometry) instead of a fixed 16 GiB.

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

* MegaMoE: CPU tests for the recipe and the arena it sizes

tests/test_mega_moe_gfx1250_recipe.py needs no GPU and skips where MegaMoE does
not import. It checks how the legacy flags map to a recipe and that the
rejections keep their wording, and lays the arena out over a grid of
geometries and every pairing against the region list #6430 built
inline -- through a fake mori both with and without Plan.describe(), the
describe one following mori's rules, which add no overlapped-reduce flags on a
wide EP. required_vmm_bytes is held to the layout as cco rounds it, and its
keyword form to at least that.

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

* MegaMoE: bind mori's dispatch staging as a tensor

A mori with ROCm/mori#844 checks a staging tensor against the plan's
stagingBytes, device and alignment at bind, and holds it; an address is taken
on trust. An older mori reads the tensor's address at each launch, as it did
the int.

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

* TEMP: grouped GEMM takes a strided scale view again (fixup for #6946)

#6946 flattens the grouped GEMM's scale arguments with .view(-1),
which a non-contiguous tensor cannot do. MegaMoE's compact rows hand over
exactly that -- each row's e8m0 scales sit inside its wire row -- so every
stage1_fused MegaMoE step raises. The kernel only takes the base address and
walks the rows by a_scale_row_stride_bytes, so a strided scale view becomes a
one-dimensional view over the same base, as it was before #6946.

Temporary: drop this commit once main fixes it.

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

* bench_mega_moe: take out the kernel-table and --fused_shared_experts changes

They are bench fixes rather than part of the MegaMoE recipe work, and move to
#7074. This reverts "bench_mega_moe: fix kernel table on
multi-stream graphs" and "bench_mega_moe: --fused_shared_experts as ATOM DP+EP
runs them".

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

* FlyDSL grouped GEMM: pass a strided scale view at its base address

Replaces the temporary workaround for the cached launcher (#6946), which
flattens the grouped GEMM's scale arguments with .view(-1). A non-contiguous
tensor cannot do that, and MegaMoE's expert-grouped dispatch hands over exactly
one: each row's e8m0 scales sit inside its wire row, read by
a_scale_row_stride_bytes.

The kernel reads these arguments only through their base pointer. tensor_shim
gains flat_arg(), beside ptr_arg(): a contiguous tensor is .view(-1), as
before, so no other caller changes; a strided one becomes the run of elements
from its first to its last, at the same base.

tests/test_grouped_gemm_strided_scales.py checks flat_arg and what the launcher
hands the compiled kernel, without a GPU.

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

* MegaMoE: stage contracts, mori sizing from describe() only, from_recipe first

The recipe
- The expert GEMM's fields move into ExpertComputeConfig, nested as
  MegaMoERecipe.compute; the recipe's own fields are the transport's.
- Which pairings run is declared by the stages: a dispatch names the wires it
  carries and the BatchLayout it delivers (token-major or expert-grouped), a
  combine the layouts it accepts and the wires it offers. The recipe checks
  against those, and its errors name recipe fields (dispatch=, combine=,
  dispatch_wire=, combine_wires=). Each stage's geometry check (check()) runs
  from MegaMoEConfig.
- from_recipe is the entry point. The keyword constructor warns
  DeprecationWarning; the underscored members ATOM's Triton experts use are
  documented as kept for them. The facade reads geometry and compute fields
  through properties rather than copying them.

The stages
- DispatchStage and CombineStage (Protocols) say what each provides; every
  stage has regions(config, caps) and check(config), and is built as
  Stage(config, caps). The compact- and mori-only attributes are gone from the
  shared base.
- Each dispatch stage owns the stride its e8m0 rows arrive at (scale_stride),
  replacing MegaMoEConfig.dispatch_scale_dst_nbytes.
- The batch carries its layout explicitly, and an expert-grouped one an
  ExpertGrouping; the combine hands the grouped GEMM its dispatch context in
  the _ComputeTarget, so the expert GEMM does not branch on the layout.
- Whether the combine needs mori's aggregated reservation and whether the
  dispatch makes it are each stage's to say; the dispatcher refuses the pair
  before the arena exists.
- One schedule pick (_pick) serves both mori plans and the compact kernels;
  _quantize returns the scale rows' address instead of leaving it in state.
- _EpDispatcher has dispatch/prepare/combine/prefetch/warmup and the recv
  views, so forward() does not reach into the stages, and close() releases the
  rest even when one part raises.

mori
- _MoriCapabilities needs Plan.describe() (ROCm/mori#844). Regions, staging
  bytes and the scale stride come from there, so the copies of mori's formulas
  and the older-mori branches are gone; such a mori also overwrites
  total_recv in its dispatch, which is why nothing zeroes it.
- _XDB_FLAG_SLOTS, TokOffExt and the plan constructors are reached only
  through _MoriCapabilities.

Checks
- An out-of-range recv_token_bound (and next_recv_token_bound) raises on the
  compact dispatch as on mori's, in dispatch, prefetch and warmup.
- a1_scale on a quantizing dispatch wire raises ValueError (was an assert).
- The keyword form of required_vmm_bytes raises when no candidate recipe runs
  at the geometry, instead of returning 0.
- _MoriCombine.prepare documents why writing fused_moe's rows straight into
  comb_inp is safe: the next dispatch does not finish until every peer has
  dispatched, which each does only after its own combine.

Tests: the CPU test fakes mori from describe() alone and covers the stage
contract messages, the bound checks and the keyword-bound refusal; the
multi-GPU test builds through from_recipe and checks the deprecated keyword
constructor against it. bench_moe_gemm_a4w4_cudagraph builds through
from_recipe.

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

* MegaMoE: split mega_moe.py into recipe, mori_caps, arena, stages, transport

A move, no change in behaviour: each block of mega_moe.py lands in one module
as it was, and mega_moe.py keeps only MegaMoEGfx1250.

- recipe.py: the wires, DispatchKind / CombineKind, ExpertComputeConfig,
  MegaMoERecipe, MegaMoEGeometry, MegaMoEConfig.
- mori_caps.py: _MoriCapabilities and mori's region names.
- arena.py: SymmetricArena, the region order, _ArenaLayout, cco's rounding.
- stages/base.py: DispatchStage / CombineStage and what the stages share
  (routing, resources, batch, compute target, schedule pick).
- stages/dispatch_mori.py, dispatch_compact.py, combine_fused.py,
  combine_mori.py: one stage each; stages/__init__.py maps each kind to its
  stage.
- transport.py: _EpDispatcher and the one arena layout.

The only edit: recipe.py looks the stages up when asked for (the stages
import recipe.py). mega_moe.py still exports the package's public names, and
Routing, which a bench imports from there. The CPU test imports the private
names it checks from the modules that define them.

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

* MegaMoE: compact dispatch bound and plan fixes, wire-picked GEMM A dtype

- Compact dispatch: with no recv_token_bound the step is sized for the
  arena's capacity; a plan started for another alignment is refused; the
  plan's segment and wave limits are checked before the arena exists; plans
  are compiled when created, ahead of any graph capture.
- A quantizing dispatch wire sets fused_moe's quant_dtype_a.
- bench_mega_moe runs on gfx1250 only.
- Tests: fp8 dispatch and fp8 combine cases, rank-local failures raised on
  every rank, CPU tests skip only without flydsl.

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

* MegaMoE CPU test: skip without mori as well

- The package's kernel modules import mori.cco, so the test skips when mori
  is not installed instead of failing collection.

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

---------

Co-authored-by: yanboshao <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
solinzby1 pushed a commit to ROCm/aiter that referenced this pull request Nov 2, 2026
…tches, mori combine path, current mori EPv2 (#6430)

* MegaMoE: stage1_fused/stage2_fused switches, mori combine path

* bench_mega_moe: fix kernel table on multi-stream graphs

* MegaMoE: follow mori tokoff-ext and selfFirst defaults

* bench_mega_moe: --fused_shared_experts as ATOM DP+EP runs them

* MegaMoE: follow mori#726 and size mori's fp4 combine flags

Four fixes to the mori dispatch/combine path (stage1_fused/stage2_fused
off), each from driving mori's plans without its op layer:

- dispatch: since ROCm/mori#726 the plan takes tok_off_ext and derives
  selfFirst itself; self_first_enabled() is gone, so importing it fails.
- tuning lookup: key it on the dispatch wire the way mori's op layer
  does ("fp4_disp_bf16_comb" for fp4). Under the hard-coded "bf16" key
  topk 9 matched no entry and both dispatch and the fp4 combine fell
  back to the single-shot default.
- comb_inp: add the overlapped fp4 combine's u64 flag per landing row
  (four ranks up). Its 24-warp geometries write them past the region,
  i.e. past the arena: a page fault at 16384 tokens a rank.
- close(): synchronize first, so a launch still in flight does not read
  a window that has been freed.

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

* MegaMoE: zero-copy hand-off from fused_moe to mori's combine

With stage2_fused off, fused_moe's rows went into a fresh tensor and then
into mori's staging rows (comb_inp): the bf16 combine copied them in its
own kernel, the fp4 one through a host-issued copy whenever the recv bound
was below max_recv -- every decode step under ATOM.

Have fused_moe write them there directly. fused_moe(output=) already
existed but the gfx1250 grouped path ignored it and copied at the end;
thread it down to the gather-reduce. mori's bf16 combine then sees its
input at the staging base and skips the copy, and the fp4 send reads the
staging rows in place.

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

* MegaMoE: follow mori#745/#746 on the mori dispatch/combine path

mori's gfx1250 dispatch now reserves its slots once per destination (the
aggregated reservation, ROCm/mori#745) and hands the push combine its landing
offsets through the dispatch. MegaMoE drives the plans directly, so it has to
size and pass what mori's op layer does:

- dest_pe_token_counter holds 2 * world_size ints: send counts, then per
  destination the reservation base and the push combine's landing offset.
  It held world_size; the dispatch wrote the second half into allocator
  padding.
- recv_num signals are 8 bytes a source. The region held 4 bytes a source;
  the arena's 256-byte alignment hid the overrun.
- The combine reads its landing offsets from dest_pe_token_counter, which
  MegaMoE did not pass, so the mxfp4 combine (stage2_fused=False) got a null
  pointer there.
- MORI_EP_TOKOFF_EXT=1 turns the aggregated reservation off, so a mori push
  combine is refused with it, as mori's op layer refuses it.
- The push landing rows come from mori's push_land_rows(): one per (token,
  destination rank), max_tokens * min(world_size, topk) rather than
  world_size * max_recv.
- The mori dispatch launcher drops total_recv.zero_(): gfx1250's dispatch
  overwrites the count (since ROCm/mori#599), and mori's op layer skips the
  same zero there.

Against a mori from before #745 the landing rows keep the old count and the
two larger buffers have unused tails.

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

* MegaMoE: bind mori's dispatch staging buffer (ROCm/mori#703)

mori#703 moves the gfx1250 dispatch's staging arrays out of each kernel
module's .bss into one buffer the caller allocates and binds as
staging_base; an unbound plan is refused on the host. MegaMoE drives
EpDispatchPlan directly, so it allocates ep_staging_bytes() once and binds
it to every dispatch plan (they never run at the same time), and drops it
after the plans on close(). A mori without ep_staging_bytes keeps the .bss
arrays and is left as is.

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

* MegaMoE: keep accepting dispatch_backend

stage1_fused now picks the dispatch, and the dispatch_backend argument and
config field went away with that. Callers still pass it (ATOM main passes
dispatch_backend="mori" on a quantizing wire; ROCm/ATOM#2384 passes
"flydsl" or "mori" alongside stage1_fused) and log
mega._config.dispatch_backend, so both would fail on this aiter.

Accept the argument again and check it against stage1_fused: "mori" is
stage1_fused=False, "flydsl" is the compact plan. A "flydsl" without
stage1_fused asked for the FlyDSL token-major dispatch, which no longer
exists, so it is refused rather than run on mori. MegaMoEConfig gets a
read-only dispatch_backend derived from stage1_fused.

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

* ci: run the MegaMoE bench on mori's dispatch

stage1_fused=false with stage2_fused=true is mori's fp4 dispatch with the
fused combine (the bench's auto wire is fp4 for a4w4_mxfp4), the
configuration DeepSeek-R1 serves with.

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

* MegaMoE: gfx1250 behaviour tests ahead of the refactor

test_mega_moe_gfx1250.py pins what a change to MegaMoEGfx1250's
dispatch/combine wiring must keep, through the constructor and members its
callers use today:

- every dispatch/combine pairing matches the fp32 reference, and a captured
  graph replays bit for bit what eager produced;
- the pairings MegaMoE rejects fail before the symmetric arena is allocated;
- mori's combine reads fused_moe's rows in place (zero-copy staging);
- close() releases the plans before the window, the window before its memory;
- the members ATOM's Triton experts reach (_dispatch, _combine, _arena, _config).

It spawns its own ranks and skips (exit 0) off gfx1250, below two GPUs or
without mori, so CI's MULTIGPU job can run it on gfx950.

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

* MegaMoE: build from a MegaMoERecipe and a MegaMoEGeometry

A caller now says what to run once, as a recipe, and MegaMoE builds it:

    recipe = MegaMoERecipe(dispatch=DispatchKind.MORI,
                           combine=CombineKind.FUSED_SCATTER,
                           dispatch_wire="fp4", combine_wires=("bf16", "fp4"),
                           activation=..., quant_type=...)
    geometry = MegaMoEGeometry(rank, world_size, model_dim, inter_dim,
                               experts, topk, max_tokens_per_rank)
    mega = MegaMoEGfx1250.from_recipe(recipe, geometry, communicator=comm)

- MegaMoERecipe holds the transport (dispatch and combine kind, dispatch wire,
  the combine wires to build) and the expert-GEMM recipe; frozen and hashable,
  so a caller can key its cache of instances on it. MegaMoEGeometry holds the
  model and EP shape.
- MegaMoERecipe.from_legacy is the one reader of stage1_fused, stage2_fused,
  dispatch_backend and the $MEGA_DISPATCH_WIRE / $MEGA_COMBINE_QUANT defaults.
  The keyword constructor goes through it, so both entries build the same thing.
- MegaMoEConfig is now that recipe resolved against a geometry: frozen, with
  the same properties as before (stage1_fused, stage2_fused and
  dispatch_backend included, for the callers that read them). The dispatch
  schedule it used to have written into it lives on the instance; the
  dispatch_block_num / dispatch_warp_num_per_block fallback it carried was
  never reached.
- forward() takes combine_wire= (bf16 | fp8 | fp4), the recipe's vocabulary,
  alongside combine_quant=.

Every check and its message is unchanged.

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

* MegaMoE: probe mori once, and decide everything before the arena exists

_MoriCapabilities gathers what MegaMoE needs to know about the installed mori --
the plan classes, the tuning lookup, and each helper a mori PR added
(scale_stride_bytes #593, push_wire_nbytes #719, push_land_rows #745,
ep_staging_bytes #703, TokOffExt.wanted #726, self_first_enabled) -- into one
cached probe, and the decisions that hang off them into its methods: the tuned
schedules, the landing-row sizes, the staging size, where the slot word lives.
The ImportError/hasattr branches are gone from the pipeline; the RuntimeError
messages for an mori that is too old are unchanged.

_plan_transport runs all of it, plus the fused reduce's tiles and mori combine's
block/epoch-slot check, before the symmetric arena is allocated. A
configuration that cannot run -- mori missing, MORI_EP_TOKOFF_EXT=1 with mori's
fp4 combine, no reduce tile, too many combine blocks -- now fails with nothing
allocated instead of leaking the arena. TokOffExt.wanted, collective when
MORI_EP_TOKOFF_EXT is on, moves ahead of the arena's own collective allocation
on every rank alike.

The compact dispatch with the fused combine still never loads mori's ops.

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

* MegaMoE: one arena layout, and required_vmm_bytes from it

The arena's regions now come from one formula, _arena_layout: the dispatch
says what it writes (_dispatch_regions: the routing both kinds share, then its
own rows), the combine what it stages through (_combine_regions), and
_ArenaLayout.merge lays them down in the order the pipeline always used, so
every pairing keeps the offsets it had. SymmetricArena takes the layout (or a
region list, as before) and frees its memory if the window registration fails.

MegaMoEGfx1250.required_vmm_bytes(recipe, geometry) reports the same layout,
rounded the way ccoMemAlloc rounds an allocation -- the per_rank_vmm a caller
needs for this MegaMoE, before any communicator exists, and exactly what the
constructor then allocates. It is MegaMoE's share only; a communicator that
also carries mori's own EP ops needs theirs on top.

required_vmm_bytes(world_size=, hidden_dim=, max_tokens_per_rank=, experts=,
topk=, stage1_fused=), the keyword form #6525 proposed and ATOM's
yanbo/mega already calls, still works: it names neither wires nor combine nor
inter_dim, so it returns the largest any recipe with that dispatch takes.

_compact_gemm_align_m reads activation, quant type and inter_dim off the
config instead of taking them separately.

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

* MegaMoE: dispatch and combine stages under one dispatcher; linear forward

The transport is now two stages the recipe picks, over one shared arena:

  _MoriDispatch / _CompactDispatch   tokens out to their experts' ranks
  _MoriCombine / _FusedScatterCombine   results back, summed per token

Each declares its arena regions (regions(), pure -- what _arena_layout and
required_vmm_bytes merge), plans in __init__ with nothing allocated, and
allocates in build(). They meet only through _EpResources (the arena, the
routing state both ends read, TokOffExt), the _DispatchBatch the dispatch hands
the expert GEMM, and the _ComputeTarget the combine has it write into.
_EpDispatcher picks the two from tables, runs every check before the arena is
allocated, and frees what was built when a later step fails -- the arena and
plans used to leak. close() goes: synchronize, combine plans, dispatch plans,
staging, arena, TokOffExt.

forward() is now: pick the step's combine wire, check the inputs, dispatch,
prepare, compute, finish. The compact plan's machinery -- slots, side stream,
per-step geometry (_CompactStep, now immutable) -- lives in _CompactDispatch,
and the next layer's plan launches at the end of its dispatch, the same place
on the GPU streams as before. The recv views are made once at build instead of
per step. The TDM dispatch keeps only its compact arm; the token-major arms
were unreachable once stage1_fused=False went through mori.

Kept for the callers that reach past forward(), ATOM's Triton experts among
them: _config, _arena, _dispatch() and its 5-tuple, _combine(),
_recv_dispatch_scales(), prefetch_compact_plan(), warmup_compact_plan().

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

* MegaMoE: size mori's regions from describe(); the bench sizes cco from the recipe

On a mori with Plan.describe() (ROCm/mori#844), the mori stages ask it for
their arena regions and the dispatch's staging bytes -- the numbers mori's own
kernels and its bind-time size check use -- instead of keeping formulas that
mirror them. Each stage builds its plan request in one place (request()), which
both describe() and the plan take. describe() compiles nothing and resolves
against gfx1250 by name, so required_vmm_bytes stays off the GPU; the slot
word's kwargs stay out of it, since where that word lives sizes nothing and
asking would be collective. An older mori keeps the formulas.

SymmetricArena.size() lets a #844 plan check its regions at bind.

bench_mega_moe builds from a MegaMoERecipe and sizes its communicator with
required_vmm_bytes(recipe, geometry) instead of a fixed 16 GiB.

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

* MegaMoE: CPU tests for the recipe and the arena it sizes

tests/test_mega_moe_gfx1250_recipe.py needs no GPU and skips where MegaMoE does
not import. It checks how the legacy flags map to a recipe and that the
rejections keep their wording, and lays the arena out over a grid of
geometries and every pairing against the region list #6430 built
inline -- through a fake mori both with and without Plan.describe(), the
describe one following mori's rules, which add no overlapped-reduce flags on a
wide EP. required_vmm_bytes is held to the layout as cco rounds it, and its
keyword form to at least that.

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

* MegaMoE: bind mori's dispatch staging as a tensor

A mori with ROCm/mori#844 checks a staging tensor against the plan's
stagingBytes, device and alignment at bind, and holds it; an address is taken
on trust. An older mori reads the tensor's address at each launch, as it did
the int.

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

* TEMP: grouped GEMM takes a strided scale view again (fixup for #6946)

#6946 flattens the grouped GEMM's scale arguments with .view(-1),
which a non-contiguous tensor cannot do. MegaMoE's compact rows hand over
exactly that -- each row's e8m0 scales sit inside its wire row -- so every
stage1_fused MegaMoE step raises. The kernel only takes the base address and
walks the rows by a_scale_row_stride_bytes, so a strided scale view becomes a
one-dimensional view over the same base, as it was before #6946.

Temporary: drop this commit once main fixes it.

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

* bench_mega_moe: take out the kernel-table and --fused_shared_experts changes

They are bench fixes rather than part of the MegaMoE recipe work, and move to
#7074. This reverts "bench_mega_moe: fix kernel table on
multi-stream graphs" and "bench_mega_moe: --fused_shared_experts as ATOM DP+EP
runs them".

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

* FlyDSL grouped GEMM: pass a strided scale view at its base address

Replaces the temporary workaround for the cached launcher (#6946), which
flattens the grouped GEMM's scale arguments with .view(-1). A non-contiguous
tensor cannot do that, and MegaMoE's expert-grouped dispatch hands over exactly
one: each row's e8m0 scales sit inside its wire row, read by
a_scale_row_stride_bytes.

The kernel reads these arguments only through their base pointer. tensor_shim
gains flat_arg(), beside ptr_arg(): a contiguous tensor is .view(-1), as
before, so no other caller changes; a strided one becomes the run of elements
from its first to its last, at the same base.

tests/test_grouped_gemm_strided_scales.py checks flat_arg and what the launcher
hands the compiled kernel, without a GPU.

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

* MegaMoE: stage contracts, mori sizing from describe() only, from_recipe first

The recipe
- The expert GEMM's fields move into ExpertComputeConfig, nested as
  MegaMoERecipe.compute; the recipe's own fields are the transport's.
- Which pairings run is declared by the stages: a dispatch names the wires it
  carries and the BatchLayout it delivers (token-major or expert-grouped), a
  combine the layouts it accepts and the wires it offers. The recipe checks
  against those, and its errors name recipe fields (dispatch=, combine=,
  dispatch_wire=, combine_wires=). Each stage's geometry check (check()) runs
  from MegaMoEConfig.
- from_recipe is the entry point. The keyword constructor warns
  DeprecationWarning; the underscored members ATOM's Triton experts use are
  documented as kept for them. The facade reads geometry and compute fields
  through properties rather than copying them.

The stages
- DispatchStage and CombineStage (Protocols) say what each provides; every
  stage has regions(config, caps) and check(config), and is built as
  Stage(config, caps). The compact- and mori-only attributes are gone from the
  shared base.
- Each dispatch stage owns the stride its e8m0 rows arrive at (scale_stride),
  replacing MegaMoEConfig.dispatch_scale_dst_nbytes.
- The batch carries its layout explicitly, and an expert-grouped one an
  ExpertGrouping; the combine hands the grouped GEMM its dispatch context in
  the _ComputeTarget, so the expert GEMM does not branch on the layout.
- Whether the combine needs mori's aggregated reservation and whether the
  dispatch makes it are each stage's to say; the dispatcher refuses the pair
  before the arena exists.
- One schedule pick (_pick) serves both mori plans and the compact kernels;
  _quantize returns the scale rows' address instead of leaving it in state.
- _EpDispatcher has dispatch/prepare/combine/prefetch/warmup and the recv
  views, so forward() does not reach into the stages, and close() releases the
  rest even when one part raises.

mori
- _MoriCapabilities needs Plan.describe() (ROCm/mori#844). Regions, staging
  bytes and the scale stride come from there, so the copies of mori's formulas
  and the older-mori branches are gone; such a mori also overwrites
  total_recv in its dispatch, which is why nothing zeroes it.
- _XDB_FLAG_SLOTS, TokOffExt and the plan constructors are reached only
  through _MoriCapabilities.

Checks
- An out-of-range recv_token_bound (and next_recv_token_bound) raises on the
  compact dispatch as on mori's, in dispatch, prefetch and warmup.
- a1_scale on a quantizing dispatch wire raises ValueError (was an assert).
- The keyword form of required_vmm_bytes raises when no candidate recipe runs
  at the geometry, instead of returning 0.
- _MoriCombine.prepare documents why writing fused_moe's rows straight into
  comb_inp is safe: the next dispatch does not finish until every peer has
  dispatched, which each does only after its own combine.

Tests: the CPU test fakes mori from describe() alone and covers the stage
contract messages, the bound checks and the keyword-bound refusal; the
multi-GPU test builds through from_recipe and checks the deprecated keyword
constructor against it. bench_moe_gemm_a4w4_cudagraph builds through
from_recipe.

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

* MegaMoE: split mega_moe.py into recipe, mori_caps, arena, stages, transport

A move, no change in behaviour: each block of mega_moe.py lands in one module
as it was, and mega_moe.py keeps only MegaMoEGfx1250.

- recipe.py: the wires, DispatchKind / CombineKind, ExpertComputeConfig,
  MegaMoERecipe, MegaMoEGeometry, MegaMoEConfig.
- mori_caps.py: _MoriCapabilities and mori's region names.
- arena.py: SymmetricArena, the region order, _ArenaLayout, cco's rounding.
- stages/base.py: DispatchStage / CombineStage and what the stages share
  (routing, resources, batch, compute target, schedule pick).
- stages/dispatch_mori.py, dispatch_compact.py, combine_fused.py,
  combine_mori.py: one stage each; stages/__init__.py maps each kind to its
  stage.
- transport.py: _EpDispatcher and the one arena layout.

The only edit: recipe.py looks the stages up when asked for (the stages
import recipe.py). mega_moe.py still exports the package's public names, and
Routing, which a bench imports from there. The CPU test imports the private
names it checks from the modules that define them.

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

* MegaMoE: compact dispatch bound and plan fixes, wire-picked GEMM A dtype

- Compact dispatch: with no recv_token_bound the step is sized for the
  arena's capacity; a plan started for another alignment is refused; the
  plan's segment and wave limits are checked before the arena exists; plans
  are compiled when created, ahead of any graph capture.
- A quantizing dispatch wire sets fused_moe's quant_dtype_a.
- bench_mega_moe runs on gfx1250 only.
- Tests: fp8 dispatch and fp8 combine cases, rank-local failures raised on
  every rank, CPU tests skip only without flydsl.

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

* MegaMoE CPU test: skip without mori as well

- The package's kernel modules import mori.cco, so the test skips when mori
  is not installed instead of failing collection.

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

---------

Co-authored-by: yanboshao <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
QizhouZhang97 added a commit that referenced this pull request Nov 2, 2026
Brings in AsyncLL (#768) and plan-reported arena/staging sizes (#844).

Conflicts, resolved by keeping both sides:
- EpInterNodeRequest carries combineLoadFirst and asyncLlMode (20 fields).
- hip_backend: the internode path keeps the resolve_schedule KernelConfig
  specs; main's geometry-bucket helpers stay removed. The schedule is now
  resolved in __init__ so _describe() sizes the arena from the same variants
  that are built. AsyncLL is a one-entry schedule, requests every allocated
  QP with no drain count, and rejects packed fp4 and the active-QP knobs.
- internode test: AsyncLL weight handling alongside the active-QP switching;
  _family_that_ran reads kernel_config().

Co-authored-by: Cursor <[email protected]>
shantipriya-amd pushed a commit to shantipriya-amd/aiter that referenced this pull request Nov 18, 2026
…tches, mori combine path, current mori EPv2 (ROCm#6430)

* MegaMoE: stage1_fused/stage2_fused switches, mori combine path

* bench_mega_moe: fix kernel table on multi-stream graphs

* MegaMoE: follow mori tokoff-ext and selfFirst defaults

* bench_mega_moe: --fused_shared_experts as ATOM DP+EP runs them

* MegaMoE: follow mori#726 and size mori's fp4 combine flags

Four fixes to the mori dispatch/combine path (stage1_fused/stage2_fused
off), each from driving mori's plans without its op layer:

- dispatch: since ROCm/mori#726 the plan takes tok_off_ext and derives
  selfFirst itself; self_first_enabled() is gone, so importing it fails.
- tuning lookup: key it on the dispatch wire the way mori's op layer
  does ("fp4_disp_bf16_comb" for fp4). Under the hard-coded "bf16" key
  topk 9 matched no entry and both dispatch and the fp4 combine fell
  back to the single-shot default.
- comb_inp: add the overlapped fp4 combine's u64 flag per landing row
  (four ranks up). Its 24-warp geometries write them past the region,
  i.e. past the arena: a page fault at 16384 tokens a rank.
- close(): synchronize first, so a launch still in flight does not read
  a window that has been freed.

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

* MegaMoE: zero-copy hand-off from fused_moe to mori's combine

With stage2_fused off, fused_moe's rows went into a fresh tensor and then
into mori's staging rows (comb_inp): the bf16 combine copied them in its
own kernel, the fp4 one through a host-issued copy whenever the recv bound
was below max_recv -- every decode step under ATOM.

Have fused_moe write them there directly. fused_moe(output=) already
existed but the gfx1250 grouped path ignored it and copied at the end;
thread it down to the gather-reduce. mori's bf16 combine then sees its
input at the staging base and skips the copy, and the fp4 send reads the
staging rows in place.

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

* MegaMoE: follow mori#745/ROCm#746 on the mori dispatch/combine path

mori's gfx1250 dispatch now reserves its slots once per destination (the
aggregated reservation, ROCm/mori#745) and hands the push combine its landing
offsets through the dispatch. MegaMoE drives the plans directly, so it has to
size and pass what mori's op layer does:

- dest_pe_token_counter holds 2 * world_size ints: send counts, then per
  destination the reservation base and the push combine's landing offset.
  It held world_size; the dispatch wrote the second half into allocator
  padding.
- recv_num signals are 8 bytes a source. The region held 4 bytes a source;
  the arena's 256-byte alignment hid the overrun.
- The combine reads its landing offsets from dest_pe_token_counter, which
  MegaMoE did not pass, so the mxfp4 combine (stage2_fused=False) got a null
  pointer there.
- MORI_EP_TOKOFF_EXT=1 turns the aggregated reservation off, so a mori push
  combine is refused with it, as mori's op layer refuses it.
- The push landing rows come from mori's push_land_rows(): one per (token,
  destination rank), max_tokens * min(world_size, topk) rather than
  world_size * max_recv.
- The mori dispatch launcher drops total_recv.zero_(): gfx1250's dispatch
  overwrites the count (since ROCm/mori#599), and mori's op layer skips the
  same zero there.

Against a mori from before ROCm#745 the landing rows keep the old count and the
two larger buffers have unused tails.

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

* MegaMoE: bind mori's dispatch staging buffer (ROCm/mori#703)

mori#703 moves the gfx1250 dispatch's staging arrays out of each kernel
module's .bss into one buffer the caller allocates and binds as
staging_base; an unbound plan is refused on the host. MegaMoE drives
EpDispatchPlan directly, so it allocates ep_staging_bytes() once and binds
it to every dispatch plan (they never run at the same time), and drops it
after the plans on close(). A mori without ep_staging_bytes keeps the .bss
arrays and is left as is.

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

* MegaMoE: keep accepting dispatch_backend

stage1_fused now picks the dispatch, and the dispatch_backend argument and
config field went away with that. Callers still pass it (ATOM main passes
dispatch_backend="mori" on a quantizing wire; ROCm/ATOM#2384 passes
"flydsl" or "mori" alongside stage1_fused) and log
mega._config.dispatch_backend, so both would fail on this aiter.

Accept the argument again and check it against stage1_fused: "mori" is
stage1_fused=False, "flydsl" is the compact plan. A "flydsl" without
stage1_fused asked for the FlyDSL token-major dispatch, which no longer
exists, so it is refused rather than run on mori. MegaMoEConfig gets a
read-only dispatch_backend derived from stage1_fused.

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

* ci: run the MegaMoE bench on mori's dispatch

stage1_fused=false with stage2_fused=true is mori's fp4 dispatch with the
fused combine (the bench's auto wire is fp4 for a4w4_mxfp4), the
configuration DeepSeek-R1 serves with.

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

* MegaMoE: gfx1250 behaviour tests ahead of the refactor

test_mega_moe_gfx1250.py pins what a change to MegaMoEGfx1250's
dispatch/combine wiring must keep, through the constructor and members its
callers use today:

- every dispatch/combine pairing matches the fp32 reference, and a captured
  graph replays bit for bit what eager produced;
- the pairings MegaMoE rejects fail before the symmetric arena is allocated;
- mori's combine reads fused_moe's rows in place (zero-copy staging);
- close() releases the plans before the window, the window before its memory;
- the members ATOM's Triton experts reach (_dispatch, _combine, _arena, _config).

It spawns its own ranks and skips (exit 0) off gfx1250, below two GPUs or
without mori, so CI's MULTIGPU job can run it on gfx950.

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

* MegaMoE: build from a MegaMoERecipe and a MegaMoEGeometry

A caller now says what to run once, as a recipe, and MegaMoE builds it:

    recipe = MegaMoERecipe(dispatch=DispatchKind.MORI,
                           combine=CombineKind.FUSED_SCATTER,
                           dispatch_wire="fp4", combine_wires=("bf16", "fp4"),
                           activation=..., quant_type=...)
    geometry = MegaMoEGeometry(rank, world_size, model_dim, inter_dim,
                               experts, topk, max_tokens_per_rank)
    mega = MegaMoEGfx1250.from_recipe(recipe, geometry, communicator=comm)

- MegaMoERecipe holds the transport (dispatch and combine kind, dispatch wire,
  the combine wires to build) and the expert-GEMM recipe; frozen and hashable,
  so a caller can key its cache of instances on it. MegaMoEGeometry holds the
  model and EP shape.
- MegaMoERecipe.from_legacy is the one reader of stage1_fused, stage2_fused,
  dispatch_backend and the $MEGA_DISPATCH_WIRE / $MEGA_COMBINE_QUANT defaults.
  The keyword constructor goes through it, so both entries build the same thing.
- MegaMoEConfig is now that recipe resolved against a geometry: frozen, with
  the same properties as before (stage1_fused, stage2_fused and
  dispatch_backend included, for the callers that read them). The dispatch
  schedule it used to have written into it lives on the instance; the
  dispatch_block_num / dispatch_warp_num_per_block fallback it carried was
  never reached.
- forward() takes combine_wire= (bf16 | fp8 | fp4), the recipe's vocabulary,
  alongside combine_quant=.

Every check and its message is unchanged.

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

* MegaMoE: probe mori once, and decide everything before the arena exists

_MoriCapabilities gathers what MegaMoE needs to know about the installed mori --
the plan classes, the tuning lookup, and each helper a mori PR added
(scale_stride_bytes ROCm#593, push_wire_nbytes ROCm#719, push_land_rows ROCm#745,
ep_staging_bytes ROCm#703, TokOffExt.wanted ROCm#726, self_first_enabled) -- into one
cached probe, and the decisions that hang off them into its methods: the tuned
schedules, the landing-row sizes, the staging size, where the slot word lives.
The ImportError/hasattr branches are gone from the pipeline; the RuntimeError
messages for an mori that is too old are unchanged.

_plan_transport runs all of it, plus the fused reduce's tiles and mori combine's
block/epoch-slot check, before the symmetric arena is allocated. A
configuration that cannot run -- mori missing, MORI_EP_TOKOFF_EXT=1 with mori's
fp4 combine, no reduce tile, too many combine blocks -- now fails with nothing
allocated instead of leaking the arena. TokOffExt.wanted, collective when
MORI_EP_TOKOFF_EXT is on, moves ahead of the arena's own collective allocation
on every rank alike.

The compact dispatch with the fused combine still never loads mori's ops.

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

* MegaMoE: one arena layout, and required_vmm_bytes from it

The arena's regions now come from one formula, _arena_layout: the dispatch
says what it writes (_dispatch_regions: the routing both kinds share, then its
own rows), the combine what it stages through (_combine_regions), and
_ArenaLayout.merge lays them down in the order the pipeline always used, so
every pairing keeps the offsets it had. SymmetricArena takes the layout (or a
region list, as before) and frees its memory if the window registration fails.

MegaMoEGfx1250.required_vmm_bytes(recipe, geometry) reports the same layout,
rounded the way ccoMemAlloc rounds an allocation -- the per_rank_vmm a caller
needs for this MegaMoE, before any communicator exists, and exactly what the
constructor then allocates. It is MegaMoE's share only; a communicator that
also carries mori's own EP ops needs theirs on top.

required_vmm_bytes(world_size=, hidden_dim=, max_tokens_per_rank=, experts=,
topk=, stage1_fused=), the keyword form ROCm#6525 proposed and ATOM's
yanbo/mega already calls, still works: it names neither wires nor combine nor
inter_dim, so it returns the largest any recipe with that dispatch takes.

_compact_gemm_align_m reads activation, quant type and inter_dim off the
config instead of taking them separately.

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

* MegaMoE: dispatch and combine stages under one dispatcher; linear forward

The transport is now two stages the recipe picks, over one shared arena:

  _MoriDispatch / _CompactDispatch   tokens out to their experts' ranks
  _MoriCombine / _FusedScatterCombine   results back, summed per token

Each declares its arena regions (regions(), pure -- what _arena_layout and
required_vmm_bytes merge), plans in __init__ with nothing allocated, and
allocates in build(). They meet only through _EpResources (the arena, the
routing state both ends read, TokOffExt), the _DispatchBatch the dispatch hands
the expert GEMM, and the _ComputeTarget the combine has it write into.
_EpDispatcher picks the two from tables, runs every check before the arena is
allocated, and frees what was built when a later step fails -- the arena and
plans used to leak. close() goes: synchronize, combine plans, dispatch plans,
staging, arena, TokOffExt.

forward() is now: pick the step's combine wire, check the inputs, dispatch,
prepare, compute, finish. The compact plan's machinery -- slots, side stream,
per-step geometry (_CompactStep, now immutable) -- lives in _CompactDispatch,
and the next layer's plan launches at the end of its dispatch, the same place
on the GPU streams as before. The recv views are made once at build instead of
per step. The TDM dispatch keeps only its compact arm; the token-major arms
were unreachable once stage1_fused=False went through mori.

Kept for the callers that reach past forward(), ATOM's Triton experts among
them: _config, _arena, _dispatch() and its 5-tuple, _combine(),
_recv_dispatch_scales(), prefetch_compact_plan(), warmup_compact_plan().

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

* MegaMoE: size mori's regions from describe(); the bench sizes cco from the recipe

On a mori with Plan.describe() (ROCm/mori#844), the mori stages ask it for
their arena regions and the dispatch's staging bytes -- the numbers mori's own
kernels and its bind-time size check use -- instead of keeping formulas that
mirror them. Each stage builds its plan request in one place (request()), which
both describe() and the plan take. describe() compiles nothing and resolves
against gfx1250 by name, so required_vmm_bytes stays off the GPU; the slot
word's kwargs stay out of it, since where that word lives sizes nothing and
asking would be collective. An older mori keeps the formulas.

SymmetricArena.size() lets a ROCm#844 plan check its regions at bind.

bench_mega_moe builds from a MegaMoERecipe and sizes its communicator with
required_vmm_bytes(recipe, geometry) instead of a fixed 16 GiB.

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

* MegaMoE: CPU tests for the recipe and the arena it sizes

tests/test_mega_moe_gfx1250_recipe.py needs no GPU and skips where MegaMoE does
not import. It checks how the legacy flags map to a recipe and that the
rejections keep their wording, and lays the arena out over a grid of
geometries and every pairing against the region list ROCm#6430 built
inline -- through a fake mori both with and without Plan.describe(), the
describe one following mori's rules, which add no overlapped-reduce flags on a
wide EP. required_vmm_bytes is held to the layout as cco rounds it, and its
keyword form to at least that.

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

* MegaMoE: bind mori's dispatch staging as a tensor

A mori with ROCm/mori#844 checks a staging tensor against the plan's
stagingBytes, device and alignment at bind, and holds it; an address is taken
on trust. An older mori reads the tensor's address at each launch, as it did
the int.

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

* TEMP: grouped GEMM takes a strided scale view again (fixup for ROCm#6946)

ROCm#6946 flattens the grouped GEMM's scale arguments with .view(-1),
which a non-contiguous tensor cannot do. MegaMoE's compact rows hand over
exactly that -- each row's e8m0 scales sit inside its wire row -- so every
stage1_fused MegaMoE step raises. The kernel only takes the base address and
walks the rows by a_scale_row_stride_bytes, so a strided scale view becomes a
one-dimensional view over the same base, as it was before ROCm#6946.

Temporary: drop this commit once main fixes it.

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

* bench_mega_moe: take out the kernel-table and --fused_shared_experts changes

They are bench fixes rather than part of the MegaMoE recipe work, and move to
ROCm#7074. This reverts "bench_mega_moe: fix kernel table on
multi-stream graphs" and "bench_mega_moe: --fused_shared_experts as ATOM DP+EP
runs them".

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

* FlyDSL grouped GEMM: pass a strided scale view at its base address

Replaces the temporary workaround for the cached launcher (ROCm#6946), which
flattens the grouped GEMM's scale arguments with .view(-1). A non-contiguous
tensor cannot do that, and MegaMoE's expert-grouped dispatch hands over exactly
one: each row's e8m0 scales sit inside its wire row, read by
a_scale_row_stride_bytes.

The kernel reads these arguments only through their base pointer. tensor_shim
gains flat_arg(), beside ptr_arg(): a contiguous tensor is .view(-1), as
before, so no other caller changes; a strided one becomes the run of elements
from its first to its last, at the same base.

tests/test_grouped_gemm_strided_scales.py checks flat_arg and what the launcher
hands the compiled kernel, without a GPU.

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

* MegaMoE: stage contracts, mori sizing from describe() only, from_recipe first

The recipe
- The expert GEMM's fields move into ExpertComputeConfig, nested as
  MegaMoERecipe.compute; the recipe's own fields are the transport's.
- Which pairings run is declared by the stages: a dispatch names the wires it
  carries and the BatchLayout it delivers (token-major or expert-grouped), a
  combine the layouts it accepts and the wires it offers. The recipe checks
  against those, and its errors name recipe fields (dispatch=, combine=,
  dispatch_wire=, combine_wires=). Each stage's geometry check (check()) runs
  from MegaMoEConfig.
- from_recipe is the entry point. The keyword constructor warns
  DeprecationWarning; the underscored members ATOM's Triton experts use are
  documented as kept for them. The facade reads geometry and compute fields
  through properties rather than copying them.

The stages
- DispatchStage and CombineStage (Protocols) say what each provides; every
  stage has regions(config, caps) and check(config), and is built as
  Stage(config, caps). The compact- and mori-only attributes are gone from the
  shared base.
- Each dispatch stage owns the stride its e8m0 rows arrive at (scale_stride),
  replacing MegaMoEConfig.dispatch_scale_dst_nbytes.
- The batch carries its layout explicitly, and an expert-grouped one an
  ExpertGrouping; the combine hands the grouped GEMM its dispatch context in
  the _ComputeTarget, so the expert GEMM does not branch on the layout.
- Whether the combine needs mori's aggregated reservation and whether the
  dispatch makes it are each stage's to say; the dispatcher refuses the pair
  before the arena exists.
- One schedule pick (_pick) serves both mori plans and the compact kernels;
  _quantize returns the scale rows' address instead of leaving it in state.
- _EpDispatcher has dispatch/prepare/combine/prefetch/warmup and the recv
  views, so forward() does not reach into the stages, and close() releases the
  rest even when one part raises.

mori
- _MoriCapabilities needs Plan.describe() (ROCm/mori#844). Regions, staging
  bytes and the scale stride come from there, so the copies of mori's formulas
  and the older-mori branches are gone; such a mori also overwrites
  total_recv in its dispatch, which is why nothing zeroes it.
- _XDB_FLAG_SLOTS, TokOffExt and the plan constructors are reached only
  through _MoriCapabilities.

Checks
- An out-of-range recv_token_bound (and next_recv_token_bound) raises on the
  compact dispatch as on mori's, in dispatch, prefetch and warmup.
- a1_scale on a quantizing dispatch wire raises ValueError (was an assert).
- The keyword form of required_vmm_bytes raises when no candidate recipe runs
  at the geometry, instead of returning 0.
- _MoriCombine.prepare documents why writing fused_moe's rows straight into
  comb_inp is safe: the next dispatch does not finish until every peer has
  dispatched, which each does only after its own combine.

Tests: the CPU test fakes mori from describe() alone and covers the stage
contract messages, the bound checks and the keyword-bound refusal; the
multi-GPU test builds through from_recipe and checks the deprecated keyword
constructor against it. bench_moe_gemm_a4w4_cudagraph builds through
from_recipe.

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

* MegaMoE: split mega_moe.py into recipe, mori_caps, arena, stages, transport

A move, no change in behaviour: each block of mega_moe.py lands in one module
as it was, and mega_moe.py keeps only MegaMoEGfx1250.

- recipe.py: the wires, DispatchKind / CombineKind, ExpertComputeConfig,
  MegaMoERecipe, MegaMoEGeometry, MegaMoEConfig.
- mori_caps.py: _MoriCapabilities and mori's region names.
- arena.py: SymmetricArena, the region order, _ArenaLayout, cco's rounding.
- stages/base.py: DispatchStage / CombineStage and what the stages share
  (routing, resources, batch, compute target, schedule pick).
- stages/dispatch_mori.py, dispatch_compact.py, combine_fused.py,
  combine_mori.py: one stage each; stages/__init__.py maps each kind to its
  stage.
- transport.py: _EpDispatcher and the one arena layout.

The only edit: recipe.py looks the stages up when asked for (the stages
import recipe.py). mega_moe.py still exports the package's public names, and
Routing, which a bench imports from there. The CPU test imports the private
names it checks from the modules that define them.

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

* MegaMoE: compact dispatch bound and plan fixes, wire-picked GEMM A dtype

- Compact dispatch: with no recv_token_bound the step is sized for the
  arena's capacity; a plan started for another alignment is refused; the
  plan's segment and wave limits are checked before the arena exists; plans
  are compiled when created, ahead of any graph capture.
- A quantizing dispatch wire sets fused_moe's quant_dtype_a.
- bench_mega_moe runs on gfx1250 only.
- Tests: fp8 dispatch and fp8 combine cases, rank-local failures raised on
  every rank, CPU tests skip only without flydsl.

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

* MegaMoE CPU test: skip without mori as well

- The package's kernel modules import mori.cco, so the test skips when mori
  is not installed instead of failing collection.

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

---------

Co-authored-by: yanboshao <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
charlieguo1106 added a commit to ROCm/aiter that referenced this pull request Dec 1, 2026
…naive GEMM + mori), conclusions and TODO

- MEGAMOE_GFX1250.md: current conclusions and TODO; the 97-expert table measured
  against #5899 (before 94cb8f5 / after 2f81baa / current cguo/gfx1250);
  the part of #5899's other tables measured so far (EP4 96 experts, EP2 tpr 8-1024);
  the separated recipe needs ROCm/mori#844, run on an in-place mori build;
  naive MegaMoE step 0: design, run commands, tpr 256 kernel breakdown against
  production's separated and full MegaMoE, all-tpr table, next steps.
- naive_mega_moe.py: naive_moe_experts (route map, naive GEMM1, SiLU*mul + MXFP4,
  naive GEMM2, weighted gather-reduce), NaiveMegaMoE (MegaMoEGfx1250 with only
  _compute replaced), naive_expert_weights, naive_tiles (production's CSV row).
- bench_naive_mega_moe.py: bench_mega_moe.py with the naive pipeline swapped in.
- test_naive_mega_moe.py: single-GPU check of naive_moe_experts against fp32.
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.

2 participants