Skip to content

feat(hygon): add native Clover diffusion and sparse MoE operators - #1015

Open
Ringssss wants to merge 25 commits into
InfiniTensor:masterfrom
Ringssss:feat/hygon-clover-operators
Open

Ringssss wants to merge 25 commits into
InfiniTensor:masterfrom
Ringssss:feat/hygon-clover-operators

Conversation

@Ringssss

Copy link
Copy Markdown

Summary

  • Add Hygon native/Triton providers for Clover preview convolution, bidirectional GDN, FP32 causal state commit, block coreset, live-row routing/cache merge, and packed dense MoE.
  • Enable Hygon Triton JIT module loading using the InfiniRT driver interface; retain gfx architecture and wave-size metadata.
  • Add missing Hygon causal-convolution/gating, layout and rotary providers needed by the model.
  • Add explicit public-API declaration selection for downstream model registries whose unused operators have no provider on this backend.

Motivation

Clover's noisy-block previews must preserve committed recurrent state and read a bidirectional block. The existing Hygon providers cannot execute that model. The companion InfiniLM integration uses these kernels directly from C++, with optional expert budgeting/live-row reuse during preview and full causal replay for commit.

Dependency: InfiniTensor/InfiniRT#52. The build was also checked against the installed Hygon SDK.

Type of Change

  • feat — new operators / backend capabilities
  • build — installed API generation
  • test — numerical/state and JIT metadata checks

Platforms Affected

  • Hygon (WITH_HYGON, added to this template)
  • Build system / CMake
  • Python bindings / user-facing API
  • CPU and NVIDIA: shared JIT/header-generation tooling; their kernel implementations are unchanged

Smoke Test Result

Hygon BW/gfx936, DTK 26.04, Torch 2.10.0, Triton 3.5.0, BF16 data and FP32 recurrent state:

Preview convolution/GDN: widths 1/8/32, batches 1/3; reference checks passed;
clean state remained bitwise unchanged.
Fused MoE: 1/32/64 tokens; independent Torch reference checks passed.
Causal GDN: packed lengths 4/7 and separate slots; output/state checks passed.
Coreset: widths 1/8/32, batches 1/4; routing masks matched exactly.
Live mask, inactive-route omission and cached output merge: passed.

The rebased build passed 62 wrapper/JIT/public-header and Clover tests. The required CPU/Hygon smoke selection passed: 121 passed, 43 skipped (inactive providers), 9485 deselected. Build, tooling and checked-in tests are documented in docs/clover-hygon.md. tests/native/clover_workspace_smoke.cpp exercises workspace-bearing providers through the native public API. Missing workspaces are rejected before launch. The original unguarded Python functional invocation failed; that failed prototype is not included as a passing result.

Test Results on Supported Platforms

Platform Affected Build / Smoke Result Full Result / Notes
Hygon Yes Full library build and numerical/state smoke passed Full-model TP2 generation and HTTP campaign passed; not the entire unrelated operator matrix
CPU API generation Wrapper, public-header and JIT unit tests passed Hygon build also includes CPU providers
NVIDIA Shared JIT metadata handling Unit tests cover CUDA and HIP metadata No NVIDIA hardware available for GPU validation
Iluvatar / MetaX / Moore / Cambricon / Ascend Shared opt-in declaration generator Existing default behavior retained Hardware unavailable; platform CI remains for maintainers

Benchmark / Performance Impact

The companion native InfiniLM campaign uses real Clover-35B-A3B-Preview weights, BF16 TP2, 32 short prompts repeated three times, concurrency one and a common OpenAI chat client. All 96 requests per lane completed. Visible output tokens are retokenized consistently; padded diffusion usage counters are excluded.

Measured integration throughput after upstream sync: native baseline 28.57 tok/s; frontier stride 38.47; expert budget/live reuse 28.70; joint 39.92; local SGLang Clover port 5.88. These are end-to-end integration results, not isolated operator speedups. The measurement record retains all requests, failures, warmups and rejected candidates. Final smoke repairs also cover strided casts and preserving the vendor HIP driver during autotuning.

Separate traces contain GPU events on both TP devices. Live-row kernels occur only in the joint path; summed routed-MoE GPU duration decreases from 1339 ms to 721 ms in the representative profiled request. Profiling time is excluded from throughput and summed device durations are not wall time.

Notes for Reviewers

Preview state is read-only. Causal replay remains exact to the specified recurrent equations; live-row reuse is an opt-in approximation controlled by the LM. The H100 DP/EP sequence-parallel communication pipeline is not ported here.

INFINI_OPS_DECLARATIONS exposes unsupported APIs for compilation/capability queries; it does not create fallback providers. Preserve explicit workspace lifetime and same-stream ordering. The code-generation comment-default issue found during bring-up was already fixed upstream; the branch keeps the upstream implementation.

Source provenance, API alignment, supported layouts and licenses are recorded in the operator guide and THIRD_PARTY.txt. Cross-platform accelerator CI is still needed for the shared tooling changes.

The clover* Triton operators and MoeFusedDense were registered only for
a single device backend (Hygon), which made the whole Clover diffusion
path unbuildable and unrunnable on any other Triton-capable platform.

Refactor the seven clover operators following the established pattern
used by shared operators such as Add:

- Extract the device-specific inline Operator specializations into
  template <Device::Type kDev> implementation classes under
  infini::ops::triton::jit, with Launch<kDev> parameterization.
- Register thin Operator<Op, kNvidia/kHygon, 10> shells for BOTH
  Triton-capable backends. Hygon behavior is unchanged.
- moe_fused_dense already had a templated implementation but only a
  Hygon shell; add the kNvidia shell.
- block_conv1d / local_memory / recurrent_gdn already templated with a
  kNvidia shell; add the missing kHygon shell for symmetry.

Also fix a CMake glob bug in the WITH_NVIDIA branch: NVIDIA_PATTERNS
uses GLOB_RECURSE with a top-level 'native/cuda/*.cu' pattern that also
matches sibling vendor subtrees (hygon/iluvatar/metax/moore/...), so
their kernels were compiled twice and failed to link with multiple
definition errors when both backends' sources were present. Add the
symmetric exclusion that the WITH_HYGON branch already has.

Verified on NVIDIA A100 (CUDA 13.1, sm80) with Clover-35B-A3B-Preview
under InfiniLM PR InfiniTensor#604: TP2 block-diffusion generation produces
byte-identical outputs and per-block iteration counts before and after
this refactor.
Absorb 136 upstream files (cambricon topk provider, wrapper-generator
and conftest updates, pinned deps) so the branch merges cleanly into
master. Auto-merge; the only remaining deltas versus master are this
PR's clover operators, the multi-device Triton shells, and the NVIDIA
CMake vendor-exclusion fix.
@Ringssss
Ringssss marked this pull request as ready for review November 19, 2026 07:36
@Ringssss
Ringssss requested a review from a team November 19, 2026 07:36
namespace infini::ops {

template <>
class Operator<MoeAlignBlockSize, Device::Type::kHygon, 0>

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.

这个算子是不是可以把具体实现放到cuda下面,然后这里继承啊?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

已处理(fe0043a1):实现移到 native/cuda/ops/moe_align_block_size,以 runtime backend 为模板参数;NVIDIA 和 Hygon 的注册改为薄继承,原先两份逐字相同的 .cu/.cuh 拷贝删除。设备切换用各后端 Runtime 的 GetDevice/SetDevice,与 layer_norm 等共享实现的写法一致。

Comment thread scripts/generate_wrappers.py Outdated
Comment on lines +2301 to +2306
parser.add_argument(
"--declarations",
nargs="*",
default=[],
help="Also emit operator APIs with no active provider.",
)

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.

应该可以通过构建自己的ops.json实现类似的功能,举例:https://github.com/InfiniTensor/InfiniOps/blob/master/scripts/configs/infiniops_ops_nvidia_dense_sampling_torch_free_no_marlin.json#L52-L54
编译方式添加DINFINI_OPS_OPS参数

cmake -S submodules/InfiniOps -B build/InfiniOps \
  -DWITH_TORCH=ON \
  -DWITH_LINKED=ON \
  -DINFINI_OPS_OPS=/workspace/ops.json \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT"

这个修改应该不是必要的

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

同意,已删除(578a4428):INFINI_OPS_DECLARATIONS 和生成器的 --declarations 都去掉了,三个文件恢复上游原状。选择清单按你给的样式放到了 scripts/configs/(infiniops_ops_hygon_infinilm.json / infiniops_ops_nvidia_infinilm.json),有 provider 的用 implementations、没有的用 public_api_only——nvidia 那份保留是因为 upsample_bicubic2d 在任何后端旗标下都没有 NVIDIA provider,与现有 torch-free 配置的处理一致。海光的构建配方见 docs/build-hygon-inference.md。

namespace infini::ops::triton::jit {

template <Device::Type kDev>
class CloverBlockConv1d : public ::infini::ops::CloverBlockConv1d {

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.

海光triton实现的算子能帮忙加个单测覆盖一下不?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

已补(509cd2ec)。排查时发现一个更根本的问题:原测试查询的是 "nvidia" 的实现索引,在海光上全部被跳过、实际一个都没执行过。现在测试按当前设备查询,原生(0)和 Triton(10)两条路径都与各自的参考实现比对;moe_fused_dense 也通过 Python 绑定补上了 Clover 形状的用例。最终在海光上:smoke 96 通过、相关模块 175 通过无失败。

Move the clover operator family from Triton-only to the repository's
standard native layout: SIMT kernels in native/cuda/ops/ (one source
compiled by every CUDA-compatible toolchain) with generic host wrappers
(CudaX<Runtime<kDev>>), plus thin registration shells for NVIDIA and
Hygon. The Triton providers stay registered at implementation index 10
and become automatic fallbacks.

Operators:
- clover_live_mask / clover_mask_routes / clover_merge_moe: elementwise
  metadata kernels mirroring the clover_live_rows Triton stages.
- clover_coreset: three-stage block-routing whitelist. The mass stage
  uses one thread per expert with a rank-count top-8 test (deterministic,
  no atomics); the allow stage keeps experts until the normalized
  cumulative probability reaches top_p, mirroring the Triton reference
  (the reference's keep-OR-expert-0 operates in sorted coordinates,
  i.e. it pins the highest-mass expert, not expert id 0).
- clover_block_conv1d: 4-tap history + 3-tap symmetric block convolution
  with silu, dead-slot guards and per-row validity.
- clover_local_memory: read-only BD-GDN preview attention with the
  gate-decayed clean-state history bucket (L2-normalized q/k, per-head
  scalars, validity-aware softmax).
- clover_recurrent_gdn: sequential GDN state update with delta rule,
  final-state writeback and dead-slot/empty-range guards.

All kernels dispatch on the runtime dtype (bf16/fp16 data, fp32 state
and gates, int32/int64 indices where the interface allows both) — the
routing logits in the real model path are bf16, so fp32-only kernels
would silently corrupt them.

Tests (29 cases, all green on NVIDIA A100): torch golden models plus
Triton cross-checks per operator, covering block sizes 1..32, dead
slots, scattered validity masks, head-count mappings and empty ranges.
clover_coreset is exercised through tests/native/clover_native_adapter
(workspace-taking providers need an explicit Handle workspace).

End-to-end: Clover-35B-A3B-Preview TP2 on A100 — 'What is the capital
of France?' reproduces the Triton baseline token-for-token; the frontier
+ expert-budget paragraph stays semantically identical with ulp-level
numeric-path divergence only (greedy decoding is chaotic at that scale).
The five headers specialize `Operator` for `Device::Type::kHYGON`, which
`InfiniRT` names `kHygon`, so a `WITH_HYGON=ON` build fails to compile.
The native target lookup is cached per thread and runs before the kernel
cache is consulted, so callers that launch from several threads at once,
such as tensor parallel ranks, initialize the Triton driver concurrently on
their first launch. This was observed to hang inside `triton.runtime.driver`.

A module lock serializes `get_hygon_target`, `get_compilation_fingerprint`,
`compile_kernel` and `auto_tune`.
Comment thread src/native/cuda/hygon/ops/cast/kernel.h Outdated
} // namespace hygon_cast_detail

template <>
class Operator<Cast, Device::Type::kHygon> : public Cast {

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.

hygon文件夹下面的算子请优先继承cuda算子文件夹里面算子的实现

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

剩下四个(cast、causal_conv1d、fused_gated_delta_net_gating、moe_align_block_size)已全部提到 native/cuda/ops 共享、两边薄继承(fe0043a1)。cast 有一点说明:共享实现加了 kStridedLayouts 开关,NVIDIA 保持只接受连续布局(tests/test_cast.py 有用例断言这一行为),海光为 Clover 的 strided 投影打开非连续支持。

The Hygon provider now runs three native kernels for the fused MoE expert
computation where h and i are multiples of 8: the gate/up projections
fused with SiLU, the down projection scaled by the routing weight, and the
weighted sum over the routes of a token. One wavefront streams two 16-row
weight bands of an expert block, reading 256 contiguous bytes per row and
load instruction, through LDS into the register layout of
v_mmac_f32_16x16x16. With the routes spread over the experts this is
3.5-4.3x faster than the Triton kernels on Clover-35B shapes; with them
concentrated by the block coreset of the model both take the same time.

The kernels are built for HYGON_ARCH=gfx936. Other shapes and
architectures keep the Triton JIT kernels through the same provider, and
INFINI_OPS_HYGON_MOE_TRITON=1 forces them on gfx936 as well.
`check_moe_fused_dense_hygon.py` compares the operator with float32 torch
references on both paths, each with its own rounding, for spread and
concentrated routing. `bench_moe_fused_dense_hygon.py` times the two. The
workspace adapter takes an implementation index, asks the operator for the
workspace it needs, and tells whether the native kernels are in use.
Comment thread tests/native/build_clover_workspace.py Outdated
@@ -0,0 +1,37 @@
"""Build the native workspace test adapter against an installed InfiniOps SDK."""

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.

这个文件夹下面的四个文件,如果是编译应该不用测, 如果是算子测试是不是可以在测算子的时候一起测?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

同意,整个目录已删除(9c303bfd + 509cd2e):数值检查并入了 tests/test_clover_*.py 和 tests/test_moe_fused_dense.py,随算子一起跑。前提是补了 workspace 回退:相关 provider 在调用方未提供 workspace 时改用算子自有的缓冲(CudaMoeFusedDense/CudaChunkGatedDeltaRule 的既有模式),Python 绑定从此可达这些路径,coreset 也改走纯绑定。

Comment thread docs/clover-hygon.md Outdated
@@ -0,0 +1,77 @@
# Hygon Clover operators

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.

这个文档如果不是必要的,可以不放在代码库里面

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

已删除(c3d4ec18):每个算子的契约写进各自基类头文件的注释。海光栈的构建说明以 docs/build-hygon-inference.md 的形式保留(746e613c,对照 build-nvidia-inference.md 的角色);集成侧内容在 InfiniLM 仓库的指南里。

Comment thread src/base/clover_recurrent_gdn.h Outdated

namespace infini::ops {

class CloverRecurrentGdn : public Operator<CloverRecurrentGdn> {

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.

这个算子做的是因果 GDN 递推。现有 RecurrentGatedDeltaRule 已经能表达初始和最终状态槽位,这次新增的主要需求是 packed cu_seqlens 和独立的 FP32 状态。优先给现有接口增加兼容重载。无论用哪个接口,都要明确初始槽与最终槽不同时是否保留初始槽,以及不同请求能否共用状态槽。现在一个 Tensor state 加两组索引,调用者看不出完整的读写契约。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

已按此重构(a2a51e00):CloverRecurrentGdn 移除,packed + FP32 状态的形式成为 RecurrentGatedDeltaRule 的第二个重载(cu_seqlens + initial_slots/final_slots)。基类现在写明了两种形式的槽位契约:初始槽只读、与最终槽不同时保持不变(请求是“分叉”状态而非移动它);同一调用内各最终槽两两不同且不与其他请求的初始槽重叠;不可用槽位将该请求输出清零;区间非法则输出不动。两点说明:a) 该重载要求 head dim 128(两个实现如此),基类构造即拒绝其他值;b) Python 绑定调用此重载需用关键字参数(batch 重载的可选位置也接受张量),C++ 无影响。你们后来 push 的 warp-cooperative 布局(每 warp 一个 value 行、K 轴拆 32 lane、k 向量暂存共享内存)完整保留在这个重载里。


namespace infini::ops {

class CloverLiveMask : public Operator<CloverLiveMask> {

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.

CloverLiveMask、CloverMaskRoutes 和 CloverMergeMoe 目前共同服务于 Clover 的 MoE 缓存复用。能否把这套流程封装到 InfiniLM 的 Clover 模块里,由模型层负责标记需要重算的行、屏蔽路由和更新缓存?有可用的通用算子时可以直接组合。对于当前海光路径,也可以考虑把已有 kernel 编进 InfiniLM 的私有构建目标。如果需要继续通过 InfiniOps SDK 跨仓库调用,建议将这几个入口明确为 Clover 专用的 C++ 接口,并写清状态更新、无效专家 ID 和允许的原地调用方式。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

暂留 InfiniOps 并按你给的第二种方式处理(c3d4ec18):三个基类头文件均写明是 Clover 专用、经 C++ API 使用的接口,并明确了状态更新(previous 快照被覆写、cache 更新为本次选择)、无效专家 ID(越界哨兵 num_experts,对齐阶段会丢弃该路由)与允许的别名(out 可与 ids/fresh/cache 别名,fresh 与 cache 不可互为别名)。没有挪进 InfiniLM 的原因:InfiniLM 目前完全不编译设备代码,海光也缺少可直接组合的 eq/where 类通用算子。

Absorb the five upstream commits after f52af91: FM9G70 paged serving
on Ascend (InfiniTensor#1041), the Cambricon TopK Softmax link fix (InfiniTensor#1051), the
generic BLAS-based MoE, GDN, quantization and attention operators for
MetaX (InfiniTensor#1033), and two CI changes (InfiniTensor#1052, InfiniTensor#1053). Auto-merge without
conflicts; generate_wrappers.py, src/CMakeLists.txt and
tests/test_generate_wrappers.py changed on both sides.
recurrent_gdn (11.6x slower -> 0.88x, now faster than Triton): one
warp owns one value row of the [128,128] state; lanes split the K axis
so every dot product becomes a fixed-order warp shuffle reduction and
the normalized k vector is staged in shared memory once per token.
Determinism preserved (verified byte-identical across repeated runs).

clover_coreset (12.1x -> 1.4x): split into two stages. Stage A runs
one thread block per routing row and finds the row's top-8 experts
with eight fixed-order block argmax rounds, staging (expert id,
normalized probability) pairs in the workspace; stage B accumulates
mass per expert in fixed row order. The allow stage replaces the
serial per-round selection with a deterministic bitonic sort over
(mass, id) pairs followed by a prefix-sum cut, mirroring the Triton
reference's sort+cumsum structure. Workspace grows by a [tokens,16]
fp32 staging buffer; tests updated accordingly.

local_memory: a warp-cooperative rewrite was attempted (3.5x -> 1.5x)
but introduced a hard-to-isolate numeric divergence; it is reverted
to the per-thread version pending a careful redo. Bench (A100, real
Clover shapes, median of 200 CUDA-event timed iterations):
  live_mask 0.80x  mask_routes 0.79x  merge_moe 0.89x  block_conv1d 0.98x
  coreset 1.40x    local_memory 3.93x  recurrent_gdn 0.88x
(lower is faster; five of seven providers now match or beat Triton).

All 29 unit tests pass; end-to-end Clover-35B TP2 output unchanged.
clover_local_memory (3.93x slower than Triton at call level -> 0.86x).
The earlier warp-cooperative rewrite diverged numerically. On sm_80 and
later the NVIDIA provider now mirrors the Triton kernel operation for
operation in one tensor-core kernel: the same m16n8k16 MMA with the
gated history as the initial accumulator, exp2 on a scaled argument,
the same rounding points for q, k, state and weights, and the history
bucket as one mask token against a full 32-token block. Over 2160
random cases (bf16/fp16, 1..16 requests, dead slots, inactive rows)
99.98% of the output is bit-identical with Triton and the rest is
within two units of the element type; repeated runs are byte-identical.
Kernel time at one request is 0.95x of Triton's; from two requests on
the kernel is bandwidth bound and takes 1.02x..1.24x of it.

Every layout that kernel cannot read (fp32 per-head scalars, rows that
are not whole 16-byte vectors, head sharing ratios that are not a power
of two, other vendors) takes the shared SIMT kernel, rewritten as the
warp-cooperative version whose reductions now associate like the
reference's: 99.99% of its output is bit-identical with Triton.

The test golden model computed the history term against the untransposed
state, so a broken history passed within the tolerance. It is fixed and
the state has unit magnitude. The tests cover every tiling the launcher
picks, the fallback layouts, bit-level agreement with Triton and
determinism, at a tolerance of one unit of the element type.
clover_coreset ran four launches and a workspace. The three Triton
stages now run in one launch with one thread block per routing block
and no workspace: a warp per row for the softmax and its top-8 experts,
eight warps for the sort, every intermediate value in shared memory.

Every fp32 reduction keeps the reference's association (row sums, mass
per expert, block total, the scan over the sorted experts), so the
allow list and the output are bit-identical with Triton over 51
configurations (bf16/fp16/fp32, block sizes 1..32, top_p 0.05..1.0,
ties). Only the masses differ, by an ulp where the reference's
approximate division rounds differently.

A warp issues a shuffle only every few dozen cycles on the GPUs this
was tuned on, so lanes exchange through shared memory. A row's top-8 is
a merge tree in registers: each lane's eight keys sorted, then five
merge levels pairing the lanes that still hold candidates. The sort
ranks an expert by counting the keys ahead of it in its own warp and
binary-searching the other seven sorted runs. The row maximum and sum
are one lane's tree over the 32 lane partials. Warp barriers only stand
in code the whole warp reaches; where a compiler cannot see that, it
reconverges the warp by hand, which cost more than the work between the
barriers.

An fp32 logit does not fit a 32-bit key together with its expert id.
The tree runs on a key without the low 8 mantissa bits, and the kernel
checks whether a logit outside the top-8 could have overtaken the
eighth one on those bits; only then do eight rounds of argmax on the
exact key decide.

The coreset test moves from test_clover_live_mask.py to
test_clover_coreset.py and now covers every block size and element type
against a torch golden model and Triton, ties (including -0.0 against
+0.0), the fp32 near-ties, unaligned tensors and determinism.
Kernel time against Triton on an A100, one call at a time: block_conv1d
1.76x -> 0.88x, merge_moe 1.27x -> 0.78x, mask_routes 1.17x -> 1.03x.
Back to back on a busy GPU they take 0.81x, 0.70x and 1.01x. live_mask
stays at the launch floor (1.03x).

block_conv1d computed token by token, each with the loads it happened
to need, which strung several memory latencies one after another. A
thread now loads what its tile of four tokens reads in one batch: the
block's rows from three tokens before the tile to three after it, their
validity flags, the weights and the request's slot. Only the state row
waits for a second load. A request whose slot is past the pool no
longer reads it.

merge_moe went element by element with a 64-bit division to find its
row, and read fresh or cache only after the row's flag had arrived. A
block now covers columns of one row, a thread moves 16 bytes when the
width and the tensors allow, and only a live row's cache entry is
written back: a dead row's already holds the value it keeps.

mask_routes and live_mask read their inputs before the row's flag
selects; a load that waited for the flag cost a second latency.

The tests of these three ops compare exactly and cover the power-of-two
and the division path, int64 ids, the 16-byte and the element path of
merge_moe for every element type, and unaligned tensors.

Bench (A100, real Clover shapes, CUDA events, native/Triton):
  live_mask 0.78x  mask_routes 0.79x  merge_moe 0.79x  coreset 0.39x
  block_conv1d 0.83x  local_memory 0.86x  recurrent_gdn 0.88x
All 83 unit tests pass (2 skipped: Hygon only). End to end, Clover-35B
with TP2 answers the 32-case diffusion workload (15 of 16 literal
checks; the miss is `H₂O` against the check string `H2O`).
The vectorized rewrite put the tensor's rows on the grid's y axis,
which stops at 65535 blocks; the Triton reference and the earlier
kernel use a flat 1-D grid and take any row count. Rows move to the x
axis (2^31 blocks) and the column tiles to y, with a test that runs
65600 rows.

Also carry the `data_type.h` include in the three rewritten metadata
kernel headers that name `Device::Type`: they compiled only through the
include order of their launchers.
The Hygon providers of cast, causal_conv1d, fused_gated_delta_net_gating
and moe_align_block_size were copies of the NVIDIA ones. Move the
implementations into native/cuda/ops as templates on the runtime backend
and let both providers inherit them, as the Clover operators already do.

The shared cast takes a `kStridedLayouts` flag: Hygon enables it for the
strided projections of Clover, while NVIDIA keeps rejecting strided
operands, which tests/test_cast.py relies on. The launch error checks of
the NVIDIA copies (cudaPeekAtLastError, cudaGetLastError) are dropped,
as in the other shared providers.
The Triton coreset and fused-MoE kernels and the native fused-MoE path
of the Hygon provider threw without a workspace. The Python bindings
call operators without one, so these providers were not reachable from
the test suite. Follow CudaMoeFusedDense and CudaChunkGatedDeltaRule:
use the caller's workspace when it is large enough, else a buffer owned
by the operator that is allocated once and reused.

The native coreset no longer appears here: its single-launch rewrite
keeps the masses and the allow list in shared memory and needs no
workspace at all.
…ed MoE

The provider tests looked up the implementations of "nvidia", so they
were skipped on Hygon. They now use the device under test and check both
the native and the Triton implementation against the references on every
CUDA-like backend, including the read-only state of the preview
operators. test_clover_preview.py duplicated them with a reference that
mirrored the rounding of one implementation; it is removed.

Coreset goes through the Python bindings instead of the native adapter,
and the fused MoE gains the Clover shapes with routes produced by
moe_align_block_size: spread or concentrated routing, fp16, dropped
routes and rows or k steps that end inside a tile, for the native gfx936
kernels and the Triton kernels each against its own rounding. The tiny
upstream case is skipped on Hygon, whose provider takes block size 16
only.

The NVIDIA-side test additions (merge_moe launch limits and unaligned
stores, the coreset suite) are adopted; their Triton coreset path moves
onto the plain bindings with the operator-owned workspace, so
tests/native (adapter, build script, checks and benchmark) is removed.
…eltaRule

CloverRecurrentGdn ran the causal GDN recurrence of Clover over packed
sequences with an FP32 state pool. RecurrentGatedDeltaRule already owns
the gated delta rule over a state pool, so the packed form becomes its
second overload instead of a separate operator:

    RecurrentGatedDeltaRule(q, k, v, g, beta, state, cu_seqlens,
                            initial_slots, final_slots, out, use_qk_l2norm)

The packed form requires a head dim of 128, the head dim of the
Clover model and of both providers; the base rejects any other head
dim in every build, not only in its debug asserts.

The base class now states the state-slot contract of both forms: the
initial slot is only read and stays unchanged when it differs from the
final slot, final slots must be pairwise distinct and disjoint from the
initial slots of the same call, and a request with an unusable slot
zeroes its output.

The former native CloverRecurrentGdn kernel updated the initial slot in
place and so overwrote it when the slots differed, unlike the Triton
kernels and the batched form, and left the output untouched for an
unusable slot. It now keeps the state of a value tile in shared memory,
writes the final slot only and zeroes the output like the batched form.
The kernel keeps the warp-cooperative layout of the NVIDIA-side
optimization of the former operator: one warp per value row, the K
axis split over 32 lanes with fixed-order shuffle reductions, and the
normalized k vector staged in shared memory once per token.

The Triton reference moves to triton/ops/recurrent_gated_delta_rule.

The shared CUDA provider implements the overload for NVIDIA and Hygon;
providers that do not implement it keep a default that throws. In Python
the packed form has to be called with keyword arguments, since the
batched form also accepts tensors in its optional positions.

BREAKING CHANGE: CloverRecurrentGdn is removed; call the packed overload
of RecurrentGatedDeltaRule instead.
INFINI_OPS_DECLARATIONS and the generator's --declarations option added
public APIs for operators without a provider. An ops.json passed through
INFINI_OPS_OPS does the same with "public_api_only": true, so the extra
option is dropped and the three files return to their upstream state.

The selection for the InfiniLM build ships in scripts/configs/ as
infiniops_ops_hygon_infinilm.json and
infiniops_ops_nvidia_infinilm.json, beside the existing build profiles:
they list every operator the InfiniLM model registry references, with
the providers of the platform or as public_api_only where there are
none. The NVIDIA profile is needed because upsample_bicubic2d has no
NVIDIA provider under any backend flag, as in the existing torch-free
profiles. The Hygon recipe in docs/build-hygon-inference.md builds the
stack with them.

BREAKING CHANGE: INFINI_OPS_DECLARATIONS is removed; pass
-DINFINI_OPS_OPS=<ops.json> with "public_api_only" entries instead.
docs/clover-hygon.md mixed build instructions, operator contracts and
measurements that belong to the InfiniLM guide. Remove it: every
contract now sits in the base header of its operator, and the three
live-row operators are described as Clover-specific interfaces with
their state updates, the invalid expert ID and the allowed aliasing.
Source provenance stays in THIRD_PARTY.txt.
Model the NVIDIA recipe: DTK prerequisites, InfiniRT with the Hygon
driver interface, InfiniOps with the InfiniLM operator profile of
scripts/configs, InfiniCCL, and the coverage notes. Integration-level
documentation stays in the InfiniLM repository.
The single-launch coreset and the warp-per-row local-memory kernel are
validated on NVIDIA; on gfx936 they misbehaved in three distinct ways,
each pinned to its cause with a standalone probe and fixed here.

Coreset: DTK's __syncwarp does not order shared-memory stores between
the lanes of a warp - a value lane 0 publishes for the warp (the row
maximum, the eighth-key tie bits, the denominator) reads back stale in
the other lanes, the softmax weights overflow to inf, the masses tie at
inf and the sort breaks the tie by expert id, keeping the wrong expert.
A micro-probe shows 49600 stale reads out of 51200 possible;
__syncthreads shows zero. Every barrier of the kernel stands in code the
whole block reaches, so they all become __syncthreads - correct on
NVIDIA as well.

Local memory, launch bounds: a 512-thread block of this static-shared
size without __launch_bounds__ is compiled to a 256-thread cap on DTK,
and the threads past the cap silently run with wrapped indices - half of
every request's rows came out garbage. The kernel now declares its block
size.

Local memory, inactive requests: the zero-fill loop of the inactive-
request path wrote rows 0..15 of every row tile instead of the tile's
own rows, so the rows of the second tile were never written. The loop
now offsets by the tile's first row. On NVIDIA the tensor-core kernel
serves these calls, so the shared kernel's path was only ever exercised
with active requests.

The bit-level native-versus-Triton comparison is gated to the tensor-
core path it was calibrated on: the SIMT kernel sums in a different
order and agrees with the reference to its tolerance, not bit for bit.
With the fixes, the whole Clover suite passes on gfx936: the single-
launch coreset and the warp-per-row local-memory kernel now serve Hygon
too.
Port the tensor-core path of CloverLocalMemory to the MMAC matrix
instructions of gfx936, so the Hygon provider keeps up with the NVIDIA
one instead of falling back to the much slower shared SIMT kernel.

The kernel mirrors the Triton reference at the points that decide the
result - the normalized q/k rows, the state tile and the softmax weights
are rounded to the element type before the products, all three products
accumulate in fp32, exp() is the exp2f expansion, and the history term
enters the value product as its initial accumulator. On the suite it
agrees with the Triton kernel bit for bit away from the summation-order
noise (the bit-level comparison the NVIDIA kernel is calibrated with now
runs on Hygon too).

Layout: one workgroup serves kCols value columns of one (request, value
head); a wave (64 lanes) owns one 16 x 16 output tile in a (row half,
column tile) grid, with the column tile 0 waves computing their row
half's scores and softmax while the state tile is staged. Fragments are
8-byte reads of padded k-contiguous rows; the MMAC register mappings
were verified with a standalone probe. The staging barrier doubles as
the valid-count reduction (__syncthreads_count), so no lane reads a
shared value another lane of its wave is still writing.

A measured matrix (1 .. 128 requests, 16/32/64 columns per block) picked
two tilings: one or two requests, the preview's shape, take the
32-column one and run at parity to 15% ahead of Triton; larger batches
take the 64-column one - parity again at 128+ requests, about 0.7x
Triton at the mid sizes 8 .. 64 where the block's two barriers serialize
phases, and 3.5x the previous native SIMT path at 32 requests. The host
eligibility mirrors the NVIDIA one (element-typed scalars, 16-byte
aligned contiguous rows and state columns, power-of-two head sharing);
every other layout keeps the shared SIMT kernel, and the fp32-scalar
fallback case of the layout test stays calibrated for that kernel's
rounding.
…y header

nvidia/ops/clover_local_memory/kernel.h names Caster<kNvidia> and
TypeMapType<kNvidia, ...> in its own class body, but relied on another
header of its translation unit to include native/cuda/nvidia/caster.cuh.
With the dispatch split into shards by ops.json, this header can be the
first NVIDIA header of its shard (578a442), and the build fails with
`incomplete type TypeMap<kNvidia, kFloat16>`.

Include the caster explicitly, as the Hygon counterpart already does.
The NVIDIA runtime header brings neither the caster nor the type map.
The InfiniLM main branch now references fused_qk_norm,
fused_qk_rms_norm, matmul_weight_nz and trans_matmul_weight_nz in its
shared layers, so the InfiniLM operator profiles are extended with those
four: with implementations on the platforms that have providers, as
public_api_only on Hygon, which has none of them. A build against the
updated profile compiles the complete InfiniLM tree again.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants