Skip to content

perf(EPv2): update gfx1250 tune config + optimize kernel impl - #530

Merged
kawhil-amd merged 6 commits into
mainfrom
epv2_opt2
Aug 7, 2026
Merged

kawhil-amd merged 6 commits into
mainfrom
epv2_opt2

Conversation

@kawhil-amd

@kawhil-amd kawhil-amd commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Kernel-level optimizations for EPv2 intranode dispatch and combine, targeting memory-level parallelism, synchronization overhead, and architecture-adaptive tuning.

Changes

  • Combine gather: per-block flag entry barrier, exit barrier removed. Replace comb_bar atomic sync with per-block monotonic flag counters — each block owns a private counter (single writer, no atomic). Exit barrier deleted entirely (was the dominant latency source).
  • Dispatch load unroll num update.

@kawhil-amd
kawhil-amd requested a review from jhchouuu August 6, 2026 12:47
kawhil-amd and others added 2 commits August 6, 2026 13:18
…r contention

Replace the combine gather cross-block sync (comb_bar) with per-block private
flag counters. Each block owns xdb_flag[bid] (all in lockstep == call count),
bumps only its own (single writer, no atomic), and independently polls the
shared local xdb slots; block 0 still does the npes cross-device pushes.

- Delete the exit barrier: the former (block_num-1)-way contended atomic_add on
  comb_bar was the dominant combine latency, especially at small token counts.
- Poll with >= (spin_until_ge_i64) not ==: every block reads the slot, so a
  faster peer can lap and overwrite its monotonic push before a slow rank's late
  blocks read it; >= stays deadlock-free (peer-ahead is the safe direction).
- No acquire fence after the poll: gather reads peer out_tok via non-temporal
  (cache-bypassing) loads and the spin is a control dependency, so observing the
  flag already implies the data is ready.
- cross_device_flag grows to max(combine block_num) i64s; the last block fills
  the unused tail so counters stay synced across calls with different block_num.

EP4 hidden=7168 topk=6 bf16 gather combine (GRAPH), same geometry:
  256: 342->129us  1024: 351->140us  4096: 465->239us  8192: 663->377us
  8192 @ 256x8w peaks at ~1022 GB/s (vs 855 GB/s at the old 256x4w default).

Co-authored-by: Cursor <[email protected]>
kawhil-amd and others added 2 commits August 6, 2026 15:00
The >4096 bucket was tuned for the load-once/store-many dispatch kernel,
which is not in tree; with the in-tree kernel warp 8 loses ~55% of
dispatch bandwidth. EP4 bf16 topk6 sweep at 8192 tok/rank (comb 256x16):

  disp 256x8  = 1180 us / 327 GB/s   <- was scheduled
  disp 256x32 =  530 us / 728 GB/s
  disp 192x32 =  619 us / 623 GB/s

16384 tok/rank: 256x32 = 810 GB/s vs 256x8 = 359 GB/s. Combine is
unchanged (256x16 is optimal: 1037 GB/s @8192, 1211 @16384).

256x32 now matches the <=4096 bucket, so the two merge. End-to-end
disp+comb at 8192 tok/rank: 1541 us -> 894 us. Correctness PASS at
4096 / 8192 / 16384.

@jhchouuu jhchouuu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Some redundant comments can be deleted.

@kawhil-amd kawhil-amd changed the title perf(EPv2): update gfx1250 tune config perf(EPv2): update gfx1250 tune config + optimize kernel impl Aug 7, 2026
@kawhil-amd
kawhil-amd merged commit cfe7ed3 into main Aug 7, 2026
10 checks passed
kawhil-amd added a commit that referenced this pull request Aug 10, 2026
On flydsl 0.3.0 the buffer_ops submodule is gone, so the compat layer
emulates buffer_load/buffer_store with an i32-typed pointer plus
ptr_load/ptr_store(rsrc + offset). LLVM pointer arithmetic steps by the
i32 pointee (4 bytes), but 0.2.x buffer_ops take the offset in ELEMENTS
and scale it to bytes by the element width. For i32 the two agree; for
the i64 per-block xdb flag counters added in #530 they diverge: block bid
read/wrote byte bid*4 instead of bid*8, splicing two adjacent i64 slots.

With the all-ones flag init, block 1 reads slot0.hi|slot1.lo = 0x1_0000_0000
and spins forever waiting for a peer to push >= that (peers push 1), so any
combine with block_num >= 2 hangs on the very first call. Scale the offset
by element_bytes/4 (i32 -> 1, i64 -> 2) to match 0.2.x element semantics.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
kawhil-amd added a commit that referenced this pull request Aug 10, 2026
On flydsl 0.3.0 the buffer_ops submodule is gone, so the compat layer
emulates buffer_load/buffer_store with an i32-typed pointer plus
ptr_load/ptr_store(rsrc + offset). LLVM pointer arithmetic steps by the
i32 pointee (4 bytes), but 0.2.x buffer_ops take the offset in ELEMENTS
and scale it to bytes by the element width. For i32 the two agree; for
the i64 per-block xdb flag counters added in #530 they diverge: block bid
read/wrote byte bid*4 instead of bid*8, splicing two adjacent i64 slots.

With the all-ones flag init, block 1 reads slot0.hi|slot1.lo = 0x1_0000_0000
and spins forever waiting for a peer to push >= that (peers push 1), so any
combine with block_num >= 2 hangs on the very first call. Scale the offset
by element_bytes/4 (i32 -> 1, i64 -> 2) to match 0.2.x element semantics.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
jhchouuu added a commit that referenced this pull request Aug 11, 2026
A second kernel backend for python/mori/ops/dispatch_combine_v2/, behind the same
op class as the existing FlyDSL one. Callers keep writing

    op = EpDispatchCombineOp(cfg, comm)

and get whichever backend cfg.kernel_backend (or MORI_V2_KERNEL_BACKEND) names,
defaulting to flydsl. The two agree element-for-element at 8 ranks.

Why
---
debug-aa's kernels carry 69 environment gates and 323 `#if` sites, and the cache
key is reassembled by hand in cache.py. That is how NOQUANT once failed to reach
the key and an A/B measurement silently reused the fully-enabled binary. The JIT
here removes the class of bug rather than the instance: the Cfg struct IS the
specialisation, its rendered text IS the source, and that text IS the cache key,
so a config cannot reach hipcc without reaching the key.

Rebased onto main (PR #532)
---------------------------
The FlyDSL dispatch/combine landed on main via #532 (cleaned up) plus #529
(FlyDSL 0.3) and #530 (retune), and became a real package. This backend is
re-applied on top of that: main's FlyDSL files (intranode_kernels, tuning_configs,
flydsl_prims, flydsl_compat) are kept verbatim, and the seam is split out of
main's op rather than the older debug-aa copy. The whole submodule now uses
relative imports; __init__ exports the base from ep_op_base, so importing the
package -- and running the HIP backend -- needs no FlyDSL installed.

Layout
------
    include/mori/jit/v2/         render (+field-count guard) util toolchain compiler spec
    src/jit/v2/                  plan_api  (namespace mori::jit::v2) -> libmori_jit.so, pure CXX
    .../dispatch_combine_v2/     ep_cfg.hpp     Cfg + Args, HIP-free, both sides
                                 ep_spec.hpp    Request + the two Specs
    src/.../dispatch_combine_v2/ ep_intranode_kernel.hpp  DEVICE-ONLY, Cfg as NTTP
                                 ep_spec.cpp    -> libmori_ops_v2.so
    python/mori/jit/v2/          plan_api.py    ctypes binding to the plan_api C
                                                ABI (generic, op-agnostic)
    python/.../dispatch_combine_v2/
                                 dispatch_combine_op.py  config + op base + selector (entry)
                                 flydsl_backend.py       FlyDSL subclass
                                 hip_backend.py          HIP subclass
                                 ep_plans.py    loads libmori_ops_v2.so, exposes the EP plans

Adding a kernel is three files (Cfg, body, Spec) and one registration macro; the
Python binding needs no edit, because the Plan class is derived from schemas C++
publishes and its args struct size is asserted against C++'s own sizeof.

The kernels are ported from origin/main's intranode MoE kernel. That port is
mechanical because v1's entire symmetric-memory surface is two things:
SymmMemObjPtr::GetAs<T*>(pe) -- a two-dependent-load table lookup, 30 call sites
-- and three Shmem*WaitUntil* spin loops that carry no shmem state. So

    memObj->GetAs<T*>(pe)  ->  ccoGetLsaPeerPtr(win, pe, args.offRegion)

and 13 SymmMemObjPtr fields collapse to one window handle plus eight offsets. The
generated TU never includes mori/shmem, so it carries no device globals and needs
no per-module init.

One op, two backends
--------------------
The base owns the op: dispatch(), combine(), _pick(), the views, the routing
handle, the lifecycle. A subclass supplies three things -- _regions(cfg),
_build_kernels(cfg, arena), _unsupported(cfg). Behavioural differences are DATA
on the KernelSet (stages_in_kernel, self_resets_counters, capabilities), not
methods to override; the calling convention is the one thing that could not
become data, so each backend wraps its own in _build_kernels and the base calls
everything through one named signature.

The feature surface is strict inclusion, not overlap: the HIP backend does
bf16/fp32 gather and nothing else. So the capability gate runs at CONSTRUCTION,
before the arena is allocated -- asking it for fp8 names every missing feature
instead of producing wrong numbers at launch. Selecting a backend imports only
that backend, so the HIP path runs where FlyDSL is not installed.

Measured (8x MI355, gfx950, EP8 hidden=7168 topk=8, us at 128/512/4096 tok/rank)
-------------------------------------------------------------------------------
    dispatch   hip 47.5 / 128.8 / 857.4   flydsl 76.0 / 127.8 / 857.5
    combine    hip 57.8 / 124.4 / 781.8   flydsl 82.7 / 133.6 / 888.8

The combine gap at 4096 is the staging copy: FlyDSL issues a separate 311 MB
torch copy before the kernel, the HIP kernel does it inside and overlaps it with
the barrier wait -- ~1 us instead of ~104.

Single-instance compile is 1.6 s against 115 s for debug-aa's whole file (90
kernels, gfx1250), which is what makes compile-on-demand viable at all.

Decisions worth recording
-------------------------
* Arena offsets and rank are LAUNCH arguments, not Cfg fields. As Cfg they were
  in the key, so every arena layout and every rank compiled its own copy of an
  identical kernel. Measured: 48.0/131.3 us as runtime args vs 49.5/130.6 as
  constants -- inside noise, against 16 binaries per 8-rank run instead of 2.
  The gfx942 micro-benchmark that suggested the constant form was actively worse
  (VGPR 9 -> 22, the compiler loses "the base is uniform") is not contradicted.
* Cfg as a single C++20 structural NTTP, not positional template parameters.
  DeepEP and CK both use all-int positional expansion, where swapping two
  arguments still compiles and silently produces the wrong kernel.
* FieldCount<T>() makes a field missing from VisitFields a compile error. It
  needs C++20: under C++17 both gcc and clang treat "too many initialisers" as a
  hard error rather than a substitution failure.
* Host stays free of hipcc. Shared arithmetic is attribute-free constexpr, never
  __host__ __device__ -- the latter drags every host TU through hipcc. Guarded in
  CI by tools/jit_v2/check_host_device_split.sh.

Bugs found and fixed on the way, two of them pre-existing
---------------------------------------------------------
* The combine barrier needs a release fence in every block, not just the
  publisher: every block stages tokens some other block gathers. Half the tokens
  came back wrong at 80 blocks. origin/main has the same hole.
* cco left hipErrorNotSupported (801) latched in the HIP runtime's sticky error
  slot; torch's next launch reported it as its own. That is the whole of the
  long-standing "cco breaks torch GPU kernels" symptom -- one-shot rather than
  intermittent, because reading the flag also clears it. Cleared at the
  Communicator.init boundary; the real fix is to stop latching it.
* The flat (pe, slot) stride must be the recv capacity, and the null sentinel
  must use the same stride, or a deduped slot decodes to a real peer.
* DefaultSourceDeps listed src/ops/dispatch_combine, which is a SIBLING of
  src/ops/dispatch_combine_v2 -- the v2 kernel bodies were not in the cache key,
  so editing one reloaded a stale hsaco.

Verified
--------
On top of main (ae9635f): C++ test_jit_core 24/24 and the host/device split
guard pass from a clean host build against main's headers. On 8x MI355 (gfx950):
package imports flydsl-free, both backends resolve lazily; test_op.py passes
under both backends (LEC capability-gated off for hip); backend parity is
element-for-element with 0 failures at ct=8/64/512 and exit 0. The kernel sources
are unchanged from the pre-rebase branch, so the measured numbers above still
hold. FlyDSL's scatter, fp8_blockwise, StdMoE, per-token-scales and lifecycle
paths are untouched. gfx1250 compile-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@QizhouZhang97
QizhouZhang97 deleted the epv2_opt2 branch November 10, 2026 13:18
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