Repository navigation
The router logits GEMM was staging sixteen columns at a time, and the pin that would have fixed the rest costs 189% of a span - #125
Merged
Conversation
…ery ops entry point declares its block
…cost 189% of one span
…d budget, and the rope join goes back
feitreim
added a commit
that referenced
this pull request
Aug 7, 2026
The coarsened walk (0.81x) and the register tile (0.63x) both bought bytes in flight and both lost, which says the kernel was never short of them. What separates the forward from the backward beside it is fixed per-thread cost, and #125 already named it: two 64-bit divisions by a runtime value.
feitreim
added a commit
that referenced
this pull request
Aug 7, 2026
The coarsened walk (0.81x) and the register tile (0.63x) both bought bytes in flight and both lost, which says the kernel was never short of them. What separates the forward from the backward beside it is fixed per-thread cost, and #125 already named it: two 64-bit divisions by a runtime value.
feitreim
added a commit
that referenced
this pull request
Aug 7, 2026
…ction shape
**Item 1.** `moe_bin_assign_parallel`'s contract was never the thing holding it
back. Capacity slots are first-come-first-served in flattened `(token, rank)`
order — routing semantics, not numerics, since the order decides *which* tokens
the capacity drops — but that order is a prefix sum, and a prefix sum has as
much parallelism as its memory system will give it. The kernel had none: `E`
blocks is 2048 threads on 148 SMs and a scalar walk at a runtime trip count is
four bytes a lane, so the entire launch had 8 KiB in flight. It now walks
`QUAD_LANES` vectors, `MOE_ASSIGN_FLIGHT` of them at once, and scans with warp
shuffles behind one barrier where a 256-lane Hillis-Steele tree needed sixteen.
Bit-identical slots and counts, gated against the serial oracle.
`moe_bin_assign_atomic` is the full relaxation — one atomic per pair,
first-arrival order — measured as the ceiling and **not launched by anything**.
**Item 2.** The gate is loosened, the conversion still loses, and the kernel is
unchanged. `swiglu_{forward,backward}_interleaved_tile` and the toleranced
`check_swiglu_interleaved_tile` that gates them are in the tree because what
they establish is the result: reaching `exp2_approx` on this family means
reaching it through a `RegTile`, and a `RegTile` costs more here than the
transcendental saves. The one thing that did land is #125's own open lead — the
row split's two runtime divisions are 32-bit now, at no register cost.
feitreim
added a commit
that referenced
this pull request
Aug 7, 2026
…ction shape
**Item 1.** `moe_bin_assign_parallel`'s contract was never the thing holding it
back. Capacity slots are first-come-first-served in flattened `(token, rank)`
order — routing semantics, not numerics, since the order decides *which* tokens
the capacity drops — but that order is a prefix sum, and a prefix sum has as
much parallelism as its memory system will give it. The kernel had none: `E`
blocks is 2048 threads on 148 SMs and a scalar walk at a runtime trip count is
four bytes a lane, so the entire launch had 8 KiB in flight. It now walks
`QUAD_LANES` vectors, `MOE_ASSIGN_FLIGHT` of them at once, and scans with warp
shuffles behind one barrier where a 256-lane Hillis-Steele tree needed sixteen.
Bit-identical slots and counts, gated against the serial oracle.
`moe_bin_assign_atomic` is the full relaxation — one atomic per pair,
first-arrival order — measured as the ceiling and **not launched by anything**.
**Item 2.** The gate is loosened, the conversion still loses, and the kernel is
unchanged. `swiglu_{forward,backward}_interleaved_tile` and the toleranced
`check_swiglu_interleaved_tile` that gates them are in the tree because what
they establish is the result: reaching `exp2_approx` on this family means
reaching it through a `RegTile`, and a `RegTile` costs more here than the
transcendental saves. The one thing that did land is #125's own open lead — the
row split's two runtime divisions are 32-bit now, at no register cost.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Pass two of the
gpu/opsrewrite campaign, on #124's method: compute achievedGB/s and threads/SM from the shape before touching anything, convert only where
the rewrite changes bytes, geometry or load pipelining, and measure both arms in
one container. Three kernels converted, one converted and reverted with the
numbers,
#[launch_bounds]on 42 of the 43 entry points — and the 43rd isitself one of the largest measured results in here.
Every kernel in
lib.rsnow has a verdict.The headline:
router_logits_bf16, −44.9%#124 left it as the standout — 4.228 ms at 431 GB/s, 6% of peak, worst in the
hot set by a factor of three — and guessed it was a blocking problem. It was,
and the blocking constant is
ROUTER_GEMM_BK = 16.At 16 a lane stages two
xelements into shared memory, waits on a barrier,does sixteen FMAs and waits again — 192 times over for
dim = 3072. Eightbytes in flight per lane, 384 barriers a block. Little's law on that is about a
terabyte a second before any of the compute or barrier time, and the kernel
measures 431.
What ships keeps the thread mapping — one lane per output element is the only
one that fills the device, because the output is
N * EandEis 8, so a laneper token leaves an SM 166 threads and anything coarser needs a cross-lane
reduction of the
dimaxis — and changes everything else about the tile:ROUTER_LOGITS_BK = 128. Sixteen elements a lane as fourQUAD_LANESvectors, 48 barriers a block instead of 384.
f32, the weight transposed.xwidens once per blockon the way in rather than once per lane that reads it, and a lane's expert
column becomes contiguous, so both operands of the inner product are one
16-byte shared load instead of a scalar one.
QUAD_LANESpad on both row strides. The four token rows a warp spansand the eight expert columns it spans would otherwise all land on the same
four banks; one vector of pad rotates each successive row by four banks and
both reads become conflict-free.
is selected, so the four of them issue back to back instead of down a chain of
branches — The router weight gradient's loads share a basic block, and 64 partitions buy what 256 did #111's medicine.
The reference twin keeps
ROUTER_GEMM_BK = 16and its own simple blocking.Shared memory goes 2.5 KiB → 20.6 KiB and the allocation to 52 registers, which
is 4 resident blocks an SM — and the grid is 768 blocks on 148 SMs, so 5.2
blocks' worth of work runs in two waves of four. That is where the rest of it is:
at 833 GB/s the kernel is still 10% of peak. This is −45% on a kernel that
has another 3x in it, and the next lever is the occupancy, not the tile.
fused_classifier_forward_bf16−10.3%,..._backward_in_place_bf16−8.3%Both walk a padded-vocabulary row
pair += CLASSIFIER_THREADSwith a runtimetrip count NVVM will not unroll, and the online
(max, sum)is a serialdependence across the whole row — so a lane has exactly one four-byte access
outstanding, for the whole 100 KiB row. 2048 threads/SM × 4 B is 8 KiB in flight
an SM, which is the 1.43 TB/s the forward measures, arithmetically.
Both now walk a
QUAD_LANESvector at a time. The scalar walk stays beside it asthe tail, and as the whole of the row when the stride is not a whole number of
vectors — a row base is
row * stride_words, so an odd stride puts every otherrow off a 16-byte boundary, and
classifier_row_quadsis where that is decidedrather than in a per-row head alignment.
The backward pays for it: 26 regs / 8 blocks → 44 regs / 48 B frame / 5 blocks.
It wins anyway, which is worth recording next to #124's revert — this is a
kernel where four times the bytes in flight beat five-eighths of the threads.
The reverted one: a
QUAD_LANESjoin_group3_rope_bf16The arithmetic that motivated it is real and is still in the source as a note:
the index math is five runtime 64-bit divisions —
rope_angle's three andthe kernel's own row split — for twelve bytes of output, and four pairs a thread
pays each of them once for four while widening every access from eight bytes to
sixteen.
What it cost is the register file. Six vectors of gradient and three of packed
output live at once: 40 registers against 32, 176 bytes of local frame, six
resident blocks an SM against eight. At 2.97 TB/s over 1.36 GB a launch the
kernel is latency-bound with the same bytes either way, so the threads hiding
that latency were worth more than the divisions saved — ferro-kittens#222's
occupancy pole, reached without a tile in sight.
backward.qkv_proj.joinmainReverted. The lead still open is the divisions themselves: they are
usizeandevery operand fits
u32, which is about a third of the instructions at noregister cost at all — the one shape of this fix that does not trade
occupancy.
#[launch_bounds]ongpu/ops(#122) — and what the pin costsgpu/opsdeclared none, so every entry point let the driver's JIT derive.maxntidfrom whatever allocation it chose. Measured onmain: all forty-threederive 1024, which is safe today only by accident, and #123 records what a
derived block narrower than the launch turns into (
701).Pass two's second result is that the pin is not free, and the block width
alone is not the pin. A declared
.maxntidis an input to ptxas' heuristics,not only the register budget's divisor.
A bare
#[launch_bounds(256)]hands ptxas a 255-register budget where thederived 1024 gave it 64, and the allocator spends it:
#[launch_bounds(256)]backward.router.weightrouter_backward_weight_split_bf16And a resident-block target that is too tight buys a local frame.
(256, 8)caps the budget at the 32 registers the derived allocation alreadyused, and three kernels still acquired one — the harder unrolling a declared 256
buys has to go somewhere:
(256, 8)router_backward_weight_split_bf16backward.router.weight+189%join_group3_rope_bf16fused_classifier_backward_in_place_bf16What ships is
(threads, 65536 / (threads * 64))—(256, 4),(1024, 1),(128, 6)— the resident-block count that hands ptxas back the 64-registerbudget the derived
.maxntidgave it. Under it every kernel keeps itsmainallocation, with one exception.
The exception:
router_backward_weight_split_bf16declares nothingIt is the kernel whose own note (#111) says the
.localdepot is supposed tobe there, L1-resident, and that the registers it saves are what keep the warps
hiding the loads. Declaring the block moves that balance, and every target a
256-thread block has moves it the wrong way — same container, against
main'sderived allocation, both passes of each run:
backward.router.weight(256)(256, 4)(256, 6)(256, 8)Four targets, four losses, and the two that keep the occupancy are the two that
pay for it in frame. What #122 buys here — a declared block instead of a derived
one — is not worth 8% of the span, and a derived 1024 is in no danger of being
narrower than the 256 this kernel launches in. 42 of 43 pinned, and the
43rd carries the table.
The survey: every kernel in
lib.rshas a verdictBaseline
2eb1359,./run.sh model profileon B200, B=12 T=2048 D=3072 FF=4096E=8 K=2 L=12; full step 296.858 ms. GB/s from the shapes each span launches,
% peakagainst 8 TB/s.threads/SMisbin/profile's new report (below).Converted in pass two
forward.router.logitsrouter_logits_bf16backward.loss.fused_classifierfused_classifier_backward_in_place_bf16forward.loss.fused_classifierfused_classifier_forward_bf16backward.qkv_proj.joinjoin_group3_rope_bf16Carried from #124
backward.ffn_norm/backward.attention_normrms_norm_backward_fused_tile_bf16backward.experts.swigluswiglu_backward_interleaved_packedforward.experts.swigluswiglu_forward_interleaved_packedbackward.router.weightrouter_backward_weight_split_bf16forward.router.scattermoe_scatter_packed_quadbackward.router.gather_dxmoe_gather_dx_add_quadforward.router.gathermoe_gather_combine_add_quad_packedbackward.router.scatter_dymoe_scatter_dy_packedforward.attention_residual_normrms_norm_forward_residual_bf16backward.router.inputrouter_backward_inputmainand on this branch — see belowforward.attention_norm/forward.final_normrms_norm_forward_fast_bf16New verdicts in pass two
forward.router.assignmoe_bin_assign_parallelE= 8 blocks, 5% of the device. The deterministic-ordering contract is what pins it, not the memory.backward.embeddingembedding_backward_scatterbackward.final_norm.inputrms_norm_backward_x_fast_bf16backward.router.weight_mergerouter_backward_weight_mergeforward.router.zero_bins/backward.router.zero_dead_binsmoe_zero_dead_bins_bf16forward.router.aux_termsmoe_aux_termsE= 8 blocks again, 0.08% of the stepbackward.router.softmaxrouter_backwardforward.embedding_normembedding_forward_norm_bf16backward.final_norm.weightrms_norm_backward_weight_fast_bf16forward.router.topkrouter_softmax_topkk * eserial scan a token; 0.05%forward.loss.meanloss_mean_with_auxNot on the step's path — pinned only
rms_norm_backward_fused_bf16(the arm a shape that does not divide the tiletakes),
swiglu_forward_interleaved,swiglu_backward_interleaved,split_group3,join_group3_rope,moe_scatter_packed_wide,moe_gather_combine_add_bf16,moe_gather_combine_add_quad_bf16,moe_scatter_dy,moe_zero_dead_bins,moe_gather_dx_add,rope_forward,attention_probabilities,attention_output,attention_backward_q,attention_backward_k,attention_backward_v— each is either the fp32 orunpacked arm the training shape does not take, or is launched only by the
gpu/opsgate. All carry the declaration; none carry a conversion.The instrument:
bin/profilereports all ofgpu/opsreport_norm_kernelsbecamereport_dense_kernels: registers, frame, thedeclared
.maxntid, blocks/SM andthreads/SMfor every kernel the steplaunches, at the block its call site builds. It is what produced the whole
launch_boundssection above, andmaxntidis the column that makes #122legible —
1024in that column is a block the tree never asked for.It also surfaced a pre-existing finding pass one did not have the instrument to
see:
router_backward_inputcarries a 128-byte local frame onmain, at 62registers and 4 blocks/SM. Unchanged here, reported not fixed.
Parity
router_logits_bf16was among thelib.rskernels the gate never compared —check_moe_routingbuilds its logits withreference.router_logits, so theshipped kernel's only coverage was whole-model parity.
check_router_logits_bf16now compares it against that reference at5e-6 / 5e-6: both arms see the same bf16-rounded values and sum them in thesame ascending
dimorder, so what is left to differ is the tiling. Two shapes —whole tiles, then one ragged on every axis the kernel walks (token rows past the
last full band, a
dimtail shorter than a reduction tile, fewer experts thanthe tile is wide).
check_classifier_bf16gets a third case whose row stride is not a wholenumber of
QUAD_LANESvectors — the arm that puts the whole row on the scalarwalk, which nothing else reaches.
check_ropeis now two shapes:HD = 4as before, andHD = 8, a head that isa whole number of vectors — the shape the training run has, and the one the
reverted arm needed. It stays after the revert because it was covered by nothing.
Nothing was loosened.
./run.sh ops(15 checks) is green.The composed A/B
Three same-container
BASELINE_REF=main ./run.sh model profileruns, eachreporting its build-and-run pass (A) and its measured pass (C). The
three converted spans hold their sign and their magnitude in all six:
forward.router.logitsforward.loss.fused_classifierbackward.loss.fused_classifier¹ run 3 is a plain
./run.sh model profileagainst the2eb1359baseline in adifferent container, so its column carries that container's +2.4% drift; the
three spans are −46%, −11% and −8% relative to it.
At the shipping operating point (
./run.sh model profile, full step296.858 ms), the three spans go 9.314 ms → 6.830 ms, which is
−2.48 ms, −0.84% of the step.
compare_profile's own full-step number is not that, and #124 already recordedwhy: its binary compiles the tcgen05 GEMMs at a 4224-byte-spill operating point
the shipping binary never reaches, so its step is 718 ms rather than 297 and a
2.5 ms saving is 0.35% of it — inside the ±0.7% the untouched spans move on
their own. Its pairs are what this branch is quoted from; its total is not.
bin/train.rs, B=12, one container, back to back:main92,748.4 tok/s(MFU 41.18%), this branch 93,230.6 tok/s (MFU 41.40%) — +0.52%, which
is what a −0.84% step predicts. That is
compare_train's warmup pair ratherthan its measured rounds. The rounds are the one measurement in this PR that
did not land: the two-round run was started three times — once beside a
concurrent profile run, twice alone — and every time the Modal container stopped
producing output partway through. It stalls in
/tmp/train-baseline, runningmain's own binary with none of this branch in it, so what it is not is a hangthis diff introduced. The pair above is reported as what it is, and the rounds
are worth re-running when the harness is producing output again.
Nulls, with the number
join_group3_rope_bf16's vector arm — above. Two measurements, bothnon-negative, register-file mechanism,
u32index math is the open lead.fused_classifier_*on tiles. The fused RMSNorm backward on register tiles, and the forward that measured worse #124 named this "the clearest tile shapeleft", and the API is all there —
RegTile::row_max,sub_row,exp2,online_rescale,right_fillare exactly the online softmax over a paddedrow. It is not an API gap that stopped it: block-per-row holds 8 blocks of
256 here and the natural tile shape holds 8 of 128, which is The fused RMSNorm backward on register tiles, and the forward that measured worse #124's reverted
forward exactly, on a kernel whose diagnosed problem was bytes in flight rather
than barriers. The vector walk buys the same four times the bytes without
paying the thread shape for it.
router_logits_bf16on tiles. The output is[N, 8]; the expert width ishalf a
RegTile's minimumN, the operands are mixed dtype (packed bf16xagainst an fp32 router weight that is fp32 by design), and the only mapping
with enough threads is one lane per output element — which is not a tile at
all. Recorded, not attempted.
No ferro-kittens issue is filed by this pass. Neither shape that could have
gone to tiles was blocked by the library: one has the whole API it needs and lost
on occupancy, which is #222 already, and the other has no tile shape to begin
with. The one genuinely new mechanism found here — that
.maxntidis an input toptxas' heuristics and not only a divisor, so declaring it can cost a kernel
half its occupancy — is a
cuda-oxide/ptxas fact and belongs in this tree's#[launch_bounds]notes, which is where it now is.Part of #70's campaign; the
#[launch_bounds]half closes thegpu/opsside of#122.