← Back to Pull requests

perf(k3.1): route the decode MoE rows in the latent gather on gfx950 #3496

Merged
Yu-Zhewen merged 9 files (1360 lines) on Nov 18, 2026 02:43 UTC
View on GitHub
Yu-Zhewen Yu-Zhewen commented on Nov 16, 2026 10:49 UTC
Author

Stacked on #3495.

Summary

Through 16 replicated decode rows, the latent gather's launch now also routes each row, replacing the separate sorted routing launch and its wait for the gather.

  • Every rank's latent input GEMV already projects all 896 router columns. The gather's router program sums their split-K partials, takes the top 16 experts with a bitonic sort and places the routes in the block-aligned expert sort, while the programs waiting on the shared SiTU input write the shared experts' down projection.

  • The router logits, top-k ids and expert sort match the separate launches bit for bit, and the top-k weights and shared down projection match them to rounding.

  • Past 16 rows the gather and the separate routing launch are kept.
  • Results

    One MoE layer on 8x MI355X, averaged over 92 layers, CUDA graph:

    | Rows | Before | After |
    |---:|---:|---:|
    | 8 | 23.44 µs | 19.55 µs |
    | 12 | 23.63 µs | 20.44 µs |

    InferenceX AgentX at concurrency 1 on 8x MI355X, against its parent, averaged over two same-node pairs (each pair runs both builds for an hour on one node): interactivity +2.7%, throughput +1.1%. Runs of one build agree within about 0.6% in interactivity.

    Test Plan

    On gfx950:

  • test_iris_moe_latent_gather.py on 8 GPUs: the routed gather against the gather plus the separate routing launch at 2–16 rows, eagerly and in a captured graph with a late rank, interleaved with the MoE all-reduce on the shared mailboxes; it declines 17 rows.

  • test_kimi_k3_config.py: the MoE block hands the gather's routes, expert sort and quantized latent to the experts, and falls back where the gather declines.

  • Kernel, Iris and K3.1 runtime suites on one MI355X node. Ten FlashInfer sampling cases fail on main as well; FlashInfer has no ROCm kernels.

  • The AgentX runs above.

  • Not run on NVIDIA; this path is gfx950 only and needs the Iris backend.
  • Diff: 1360 lines (+1308 / -52) across 9 files Reviewer: antiagainst Review duration: 2394m
    All Vouch review confidence checks passed
    Residual risk 0.11 = Change Risk (0.55) × (1 − Review Confidence (0.80)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.55 · 1360 lines diff across 9 files
    0.55
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.74 · 5 substantive comment(s)
    0.74
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    80%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    26 items
    claude[bot] claude[bot] commented on code on Nov 16, 2026 11:13 UTC
    Code Review
    python/tokenspeed/runtime/models/kimi_k3.py:1
    @@ -2843,6 +2843,74 @@ def _latent_input_projections(
             )
             return router_logits, routed_input, shared_output
     
    +    def _routed_latent_inputs(
    +        self,
    +        hidden_states: torch.Tensor,
    +        shared_out: torch.Tensor | None,
    +        precompute_topk: bool,
    +    ) -> tuple[torch.Tensor, StandardTopKOutput, torch.Tensor] | None:
    +        """Project, gather and route replicated rows and run the shared down
    +        projection in the gather's launch.
    +
    +        The routes and their expert sort are those of the separate sorted
    +        routing launch, bit for bit. Returns ``(routed_input, topk_output,
    +        shared_partial)``, or ``None`` before launching anything when the
    +        Iris state's routed gather does not serve these rows.
    +        """
    +        if (
    +            self._fused_routing_scratch is None
    +            or not precompute_topk
    +            or self.topk.simulate_routing
    +            or hidden_states.shape[0] not in self.experts.sorted_route_rows
    +            or self.packed_input_projection_weight is None
    +            or self.routed_expert_down_proj.narrowed
    +        ):
    +            return None
    +        from tokenspeed_kernel.ops.communication._iris.kimi_k3 import K3MoeRouting
    +
    +        topk_config = self.topk.topk_config
    +        routing = K3MoeRouting(
    +            topk_config.correction_bias.float(),
    +            float(topk_config.routed_scaling_factor),
    +            topk_config.renormalize,
    +            self.experts.sorted_route_block_size,
    +            self._fused_routing_scratch,
    +        )
    +        down_weight = self.shared_experts.down_proj.weight
    +        if not self.iris_state.can_latent_input_gather_routed(
    +            hidden_states,
    +            self.packed_input_projection_weight,
    +            routing,
    +            down_weight,
    +            shared_out,
    +        ):
    +            return None
    +        # A8W4 reuses the gathered FP8 latent.
    +        quantize = (
    +            self.experts.plan.get("apply_kernel_name")
    +            == "gluon_mxfp4_a8w4_situ_precomputed_moe_apply"

    🟡 Nit: This duplicates the A8W4 apply-kernel-name check from _latent_input_projections (line 2811). If the apply kernel is ever renamed or a second FP8-consuming apply is added, the two sites can drift and the routed path would silently stop handing over the gathered FP8 latent (the apply would re-quantize, costing a launch and potentially differing bits). Consider hoisting the name into a module constant or a small _reuses_gathered_fp8() helper shared by both call sites.

    claude[bot] claude[bot] commented on code on Nov 16, 2026 11:13 UTC
    Code Review
    tokenspeed-kernel/python/tokenspeed_kernel/ops/communication/_iris/kimi_k3/latent_gather.py:1
    @@ -552,3 +581,181 @@ def iris_k3moe_latent_input_gather(
                 HAS_LINEAR_BETA,
                 NUM_WARPS,
             )
    +
    +
    +@gluon.jit(do_not_specialize=("tokens", "split_stride", "down_out_stride"))
    +def iris_k3moe_latent_input_gather_routed(

    🟡 Nit: test_latent_input_gather_codegen guards the non-routed kernel against VGPR spills and verifies the poll cycles re-read their words and vote with one lane mask, but there is no codegen guard for this kernel. The routed variant packs the register-hungry bitonic router sort and the MFMA down projection into the same launch as the Lamport polls, which is exactly where a spill or a mis-compiled poll loop would appear first — and it would regress silently since the hardware test only checks bits, not the assembly. Consider extending the codegen test to compile iris_k3moe_latent_input_gather_routed with the same assertions.

    claude[bot] claude[bot] commented on Nov 16, 2026 11:14 UTC
    Reviewer

    Review summary

    Reviewed this PR's own commit (1a2a008df) against its stacked base zhewenyu/k31-c1-kda-boundary: the routed latent-input gather kernel, its host wrapper and guard, the model-side early-return path, and the tests.

    Findings: 0 🔴 Important, 2 🟡 Nit, 0 🟣 Pre-existing.

    Verified in detail:

  • _k3_route_row reproduces the separate routing launch: same split-order FP32 partial sums with the publisher's negative-zero sanitization, the same packed-key tie break (lower expert first), the same normalization/scaling, and the same self-sort placement and padding as _kimi3_self_sorted_routes. The scratch offsets (K3_ROUTE_SELF_MASKS, parity mask buffers, counters, epoch) match _kimi3_sigmoid_bias_topk_sorted_kernel exactly, so stream-ordered sharing of one scratch is sound, including alternation with the >32-row helper-sort path, which uses the other scratch region.

  • The SKIP_ROUTER Lamport change is safe to alternate with the non-routed gather: router slots are left in the cleared state across routed launches (never published, never polled), so a later non-routed launch at the same stage finds them empty; stages are read from memory at kernel runtime, so mixing CUDA graphs of different row counts is also safe.

  • The down_sync arrival/departure counters self-reset within the launch with no lost-wakeup window (all SiTU adds complete before any down tile passes its await; all down tiles pass before the last one zeroes), and the dispatch order keeps every waiter behind its signalers except the mutually-waiting route programs, which stay within the first ~176 workgroups, matching the existing ≤32-row self-sort pattern.

  • Host/grid math agrees with the kernel (PER_ROW, 112 down tiles, sorted-capacity formula identical to kimi3_sigmoid_bias_topk_sorted), tokens/split_stride/down_out_stride are do_not_specialize, and the graph test wraps capture in assert_no_triton_compile. Offsets stay well under int32 at the routed row cap.

  • Model side: _situ_sorted_routes/_situ_input_fp8 are consume-once in the apply and reset on every fallback path, the routed early return matches the fallback's (routed, shared_partial) contract, and _topk_ready record/wait are both fork-gated so skipping them is consistent.
  • The hardware test is strong: bit-level comparison against the separate launches at 2–16 rows, ties forced via zero rows and a coarse bias, interleaving with the mailbox-sharing all-reduce, scratch shared with the separate routing kernel, captured-graph replays with one rank late, and the 17-row decline.

    claude[bot] claude[bot] commented on Nov 16, 2026 14:18 UTC
    Reviewer

    Incremental review summary

    Reviewed this push's commit (b5c807db5), which responds to both earlier review comments:

  • The duplicated A8W4 apply-kernel-name check is hoisted into KimiLinearMoE._apply_reads_gathered_fp8() and shared by both latent gather call sites — resolves the earlier nit on kimi_k3.py.

  • test_latent_input_gather_codegen is now parametrized over routed and compiles iris_k3moe_latent_input_gather_routed with the same VGPR-spill and poll-cycle (word re-read + single lane-mask vote) assertions — resolves the earlier nit on latent_gather.py. Scoping the whole-word store assertion to the unrouted kernel is correct, since the routed kernel intentionally writes the SiTU input through in BF16.
  • Checked the new test's constexpr list and signature map against the routed kernel's full argument list: all five routed-only constexprs are supplied and every pointer/scalar arg resolves to the right type.

    Findings: 0 🔴 Important, 0 🟡 Nit, 0 🟣 Pre-existing. No new issues introduced by this push.

    lightseek-bot lightseek-bot commented on Nov 16, 2026 14:37 UTC
    Bot

    <!-- lightseek-pr-description -->
    Description checked against the current changes (7a21be5f9457).

    Further updates to this PR will refresh its description and this comment.

    lightseek-bot lightseek-bot commented on Nov 16, 2026 15:08 UTC
    Reviewer

    <!-- lightseek-pr-style-review -->
    <!-- style-review-revision:b22d0906daeb0106b934943865ff44ada484a650d4369811f015b3fe6b179164 -->
    <!-- style-review-content:a4ad096b84c67b625a52e3a78b6ee85d711880a79df5157ee1246401324bd197 -->
    Style LGTM.

    lightseek-bot lightseek-bot commented on Nov 16, 2026 16:20 UTC
    Reviewer

    <!-- lightseek-pr-style-review -->
    <!-- style-review-revision:56901414e085465ec1ed1b9c6c972a577d89bb500cefc4dce300b6c174d8735f -->
    <!-- style-review-content:837e13d548597df51e8f7a8dda45cdce8f8410cebcc2968f5e6cfa82f0f733e0 -->
    Style LGTM.

    lightseek-bot lightseek-bot commented on code on Nov 16, 2026 22:51 UTC
    Code Review
    python/tokenspeed/runtime/models/kimi_k3.py:1
    @@ -2796,6 +2796,14 @@ def pack_input_projection_weights(self) -> None:
                 )
                 offset += rows
     
    +    def _apply_reads_gathered_fp8(self) -> bool:

    <!-- lightseek-pr-style-review -->
    The new private helper \_apply\_reads\_gathered\_fp8 has no docstring, although it carries an explanatory comment about how the gathered FP8 reads are applied, which shows its logic is not obvious. A docstring is mandatory for a function with non-obvious logic or nontrivial size, and the neighboring private helpers in this class all document themselves with docstrings. Turn the existing explanatory comment into a docstring as the first statement of \_apply\_reads\_gathered\_fp8, briefly describing what the helper does with the gathered FP8 reads, and keep any purely implementation-facing remarks as inline comments.

    lightseek-bot lightseek-bot commented on Nov 16, 2026 22:51 UTC
    Reviewer

    <!-- lightseek-pr-style-review -->
    <!-- style-review-revision:34c2bc1e50537dc861a6fc166d471eabe605f4ae28f23b71fcb6649e0234bd72 -->
    <!-- style-review-content:3f59c410f2efcad94d60011aebcc6ec9c3e035f8f1a169167797ee774fa33537 -->
    3 style findings. See inline comments.

    lightseek-bot lightseek-bot commented on code on Nov 16, 2026 22:51 UTC
    Code Review
    tokenspeed-kernel/python/tokenspeed_kernel/ops/communication/_iris/kimi_k3/__init__.py:1
    @@ -793,34 +900,152 @@ def latent_input_gather(
                 SPLIT_K=split_k,
                 NUM_WARPS=_K3_LATENT_GEMM_NUM_WARPS,
                 WARPS_M=warps_m,
    -            REGION0_START=rank * router_local,
    +            REGION0_START=router_start,
                 REGION0_TILES=gemm_router_tiles,
                 REGION1_START=_K3_ROUTER + rank * latent_local,
                 REGION1_TILES=gemm_latent_tiles,
                 REGION2_START=_K3_ROUTER + _K3_LATENT,
                 REGION2_TILES=gemm_shared_tiles,
                 num_warps=_K3_LATENT_GEMM_NUM_WARPS,
             )
    +        return partials, split_k, split_stride
    +
    +    def can_latent_input_gather_routed(
    +        self,
    +        hidden_states: torch.Tensor,
    +        packed_weight: torch.Tensor,
    +        routing: K3MoeRouting,
    +        down_weight: torch.Tensor,
    +        down_out: torch.Tensor | None,
    +    ) -> bool:
    +        """Whether ``latent_input_gather_routed`` serves these decode rows."""
    +        from tokenspeed_kernel.ops.communication._iris.kimi_k3.latent_route import (
    +            K3_ROUTE_SCRATCH_WORDS,
    +        )
    +
    +        if not self.can_latent_input_gather(hidden_states, packed_weight):
    +            return False
    +        rows = hidden_states.shape[0]
    +        device = hidden_states.device
    +        block_size = routing.block_size
    +        return (
    +            rows <= _K3_LATENT_ROUTED_MAX_ROWS
    +            and block_size > 0
    +            and not block_size & (block_size - 1)
    +            and all(
    +                t.shape == shape
    +                and t.dtype == dtype
    +                and t.is_contiguous()
    +                and t.device == device
    +                for t, shape, dtype in (
    +                    (routing.correction_bias, (_K3_ROUTER,), torch.float32),
    +                    (routing.scratch, (K3_ROUTE_SCRATCH_WORDS,), torch.int32),
    +                    (down_weight, (_K3_HIDDEN, _K3_SHARED), torch.bfloat16),
    +                )
    +            )
    +            and (
    +                down_out is None
    +                or (
    +                    down_out.shape == (rows, _K3_HIDDEN)
    +                    and down_out.dtype == torch.bfloat16

    <!-- lightseek-pr-style-review -->
    This docstring summary line is 89 characters long. Docstring summary lines must remain within the line-length limit, and this line exceeds both the guide's 80-character rule and the 88-column width used by the repository's formatter; a docstring summary is not reflowed automatically, so it must be shortened by hand. Shorten the summary so the line fits, for example: """\\latent\_input\_gather\\ that also routes rows and projects the shared experts.

    lightseek-bot lightseek-bot commented on code on Nov 16, 2026 22:51 UTC
    Code Review
    tokenspeed-kernel/python/tokenspeed_kernel/ops/communication/_iris/kimi_k3/latent_gather.py:1
    @@ -552,3 +581,181 @@ def iris_k3moe_latent_input_gather(
                 HAS_LINEAR_BETA,
                 NUM_WARPS,
             )
    +
    +
    +@gluon.jit(do_not_specialize=("tokens", "split_stride", "down_out_stride"))
    +def iris_k3moe_latent_input_gather_routed(
    +    partial_ptr,
    +    shared_ptr,
    +    router_ptr,
    +    routed_ptr,
    +    fp8_ptr,
    +    sync_ptr,
    +    scale_ptr,
    +    region,
    +    epochs,
    +    regions,
    +    beta,
    +    linear_beta,
    +    tokens,
    +    split_stride,
    +    bias_ptr,
    +    topk_ids,
    +    topk_weights,
    +    sorted_ids,
    +    sorted_weights,
    +    sorted_expert_ids,
    +    num_valid_ids,
    +    route_scratch,
    +    down_weight_ptr,
    +    down_out_ptr,
    +    down_out_stride,
    +    down_sync,
    +    RANK: gl.constexpr,
    +    WORLD_SIZE: gl.constexpr,

    <!-- lightseek-pr-style-review -->
    This docstring summary line is 91 characters long. Docstring summary lines must remain within the line-length limit, and this line exceeds both the guide's 80-character rule and the 88-column width used by the repository's formatter; a docstring summary is not reflowed automatically, so it must be shortened by hand. Shorten the summary so the line fits, for example: """\\iris\_k3moe\_latent\_input\_gather\\ that also routes and projects shared experts.

    lightseek-bot lightseek-bot commented on Nov 17, 2026 09:25 UTC
    Reviewer

    <!-- lightseek-pr-style-review -->
    <!-- style-review-revision:0b2e5b2ddcd66325403094af9f921c37dcccbc578a3d8a6f32da8d605fa15fc2 -->
    <!-- style-review-content:a79564f65d072d7941d7bc049f278fac841dafe93af2ff1eca34eecbce9ab303 -->
    1 style finding. See inline comments.

    lightseek-bot lightseek-bot commented on code on Nov 17, 2026 09:25 UTC
    Code Review
    python/tokenspeed/runtime/models/kimi_k3.py:1
    @@ -2867,6 +2872,70 @@ def _latent_input_projections(
             )
             return router_logits, routed_input, shared_output
     
    +    def _routed_latent_inputs(
    +        self,
    +        hidden_states: torch.Tensor,
    +        shared_out: torch.Tensor | None,
    +        precompute_topk: bool,
    +    ) -> tuple[torch.Tensor, StandardTopKOutput, torch.Tensor] | None:
    +        """Project, gather and route replicated rows and run the shared down
    +        projection in the gather's launch.
    +
    +        The routes and their expert sort are those of the separate sorted

    <!-- lightseek-pr-style-review -->
    The docstring says the routes and their expert sort are those of the separate sorted routing launch, bit for bit. The change's own eight-GPU test compares this fused path against latent\_input\_gather followed by kimi3\_sigmoid\_bias\_topk\_sorted and checks the top-k ids, the sort counts and the sort order exactly, but the top-k weights and the sorted weights only with rtol=2e-7, so the float weights can differ in their last bits between the two launches. Because the routes include those weights, the unqualified bit-for-bit claim overstates the guarantee for a caller choosing between the fused and separate launches. Qualify the claim, for example: the route ids and their expert sort match the separate sorted routing launch bit for bit, while the float weights agree up to float rounding; or drop bit for bit and say the routes and their expert sort match that launch.

    lightseek-bot lightseek-bot commented on code on Nov 17, 2026 23:07 UTC
    Code Review
    tokenspeed-kernel/python/tokenspeed_kernel/ops/communication/_iris/kimi_k3/latent_route.py:1
    @@ -0,0 +1,354 @@
    +# Copyright (c) 2026 LightSeek Foundation
    +#
    +# Permission is hereby granted, free of charge, to any person obtaining a copy
    +# of this software and associated documentation files (the "Software"), to deal
    +# in the Software without restriction, including without limitation the rights
    +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    +# copies of the Software, and to permit persons to whom the Software is
    +# furnished to do so, subject to the following conditions:
    +#
    +# The above copyright notice and this permission notice shall be included in
    +# all copies or substantial portions of the Software.
    +#
    +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    +# SOFTWARE.
    +
    +"""Route K3 decode MoE rows and project the shared experts inside the gather.
    +
    +The latent-input gather's programs mostly wait for peer words. When every rank
    +projects all router columns, the router program of each row routes it there,
    +exactly as ``kimi3_sigmoid_bias_topk_sorted`` does through 32 rows (the same
    +scratch protocol, so the two may alternate on one scratch), and programs
    +waiting on the shared SiTU input write the shared experts' down projection.
    +"""
    +
    +from tokenspeed_kernel._triton import gl, gluon
    +from tokenspeed_kernel.ops.communication._iris.synchronization import wait_vmem
    +
    +K3_ROUTE_EXPERTS = gl.constexpr(896)
    +K3_ROUTE_TOPK = gl.constexpr(16)
    +# kimi3_sigmoid_bias_topk_sorted's scratch: [896 * 8] arrival masks and 16
    +# counters, then the self-sorting launches' two [896] mask buffers, their two
    +# arrival counters and the launch epoch.
    +K3_ROUTE_SELF_MASKS = gl.constexpr(896 * 8 + 16)
    +K3_ROUTE_SCRATCH_WORDS = 896 * 8 + 16 + 2 * 896 + 16
    +
    +
    +@gluon.jit
    +def _k3_add(a, b):
    +    return a + b
    +
    +
    +@gluon.jit
    +def _k3_max_pair(key_a, index_a, key_b, index_b):
    +    return gl.maximum(key_a, key_b), gl.maximum(index_a, index_b)
    +
    +
    +@gluon.jit
    +def _k3_order_pairs(keys, index, flip, AXIS: gl.constexpr, DIMS: gl.constexpr):
    +    """Order the pairs of hypercube ``keys`` along its ``AXIS``-th inner axis.
    +
    +    ``triton.language.standard._compare_and_swap``: a pair's left key becomes
    +    the larger where ``flip`` holds and the smaller elsewhere. Bit
    +    ``AXIS + 2`` of ``index`` is a key's position along the axis.
    +    """
    +    bits = keys.to(gl.int64, bitcast=True)
    +    partner = bits ^ gl.xor_sum(bits, DIMS - 1 - AXIS, keep_dims=True)
    +    partner = partner.to(gl.uint64, bitcast=True)
    +    right = ((index >> (AXIS + 2)) & 1) != 0
    +    return gl.where((keys > partner) != (flip ^ right), partner, keys)
    +
    +
    +@gluon.jit
    +def _k3_top16(keys, index):
    +    """Return the 16 largest of 1024 distinct ``keys``, in descending order.
    +
    +    ``triton.language.standard.sort_impl``'s bitonic top-k on a hypercube of
    +    ``keys``, which hold their position ``index`` four to a thread. The
    +    runs of 16 lie along lane bits 0-3 (``index`` bits 2-5), so pairs meet
    +    by lane swizzles, and the first two halvings fold a thread's registers,
    +    so it holds one key from then on. Flips and sides are bits of ``index``.
    +    """
    +    cube = gl.permute(gl.reshape(keys, [2] * 10), [0, 1, 2, 3, 8, 9, 4, 5, 6, 7])
    +    index = gl.permute(gl.reshape(index, [2] * 10), [0, 1, 2, 3, 8, 9, 4, 5, 6, 7])
    +    # Sort runs of 16, alternately ascending and descending; the flip of
    +    # stage 4 is the first halved axis, ``index`` bit 0.
    +    for stage in gl.static_range(1, 5):
    +        flip = ((index >> ((stage + 2) * (stage < 4))) & 1) != 0
    +        for i in gl.static_range(stage):
    +            cube = _k3_order_pairs(cube, index, flip, stage - 1 - i, 10)
    +    # The larger halves of two opposite runs form a run holding their top 16.
    +    # Halvings take ``index`` bits 0, 1, 6, 7, 8 and 9 in turn.
    +    for i in gl.static_range(5, 11):
    +        cube, index = gl.reduce((cube, index), 10 - i, _k3_max_pair)
    +        if i < 10:
    +            flip = ((index >> (i - 4 + 4 * (i >= 6))) & 1) != 0
    +        else:
    +            flip = True
    +        for j in gl.static_range(4):
    +            cube = _k3_order_pairs(cube, index, flip, 3 - j, 14 - i)
    +    return gl.reshape(cube, [16])
    +
    +
    +@gluon.jit
    +def _k3_sleep():
    +    gl.inline_asm_elementwise(
    +        asm="s_sleep 2",
    +        constraints="=r,~{memory}",
    +        args=[],
    +        dtype=gl.int32,
    +        is_pure=False,
    +        pack=1,
    +    )
    +
    +
    +@gluon.jit
    +def _k3_await_count(counter, target):
    +    """Wait until ``counter`` reaches ``target``, then acquire once.
    +
    +    The polls are relaxed so they do not invalidate this CU's caches for the
    +    other programs; the final acquire does, and the barrier keeps every
    +    subgroup's loads after it.
    +    """
    +    arrived = gl.atomic_add(counter, 0, sem="relaxed", scope="gpu")
    +    while arrived < target:
    +        _k3_sleep()
    +        arrived = gl.atomic_add(counter, 0, sem="relaxed", scope="gpu")
    +    gl.atomic_add(counter, 0, sem="acquire", scope="gpu")
    +    gl.barrier()
    +
    +
    +@gluon.jit
    +def _k3_ordered_key(value):

    <!-- lightseek-pr-style-review -->
    The new helper \_k3\_ordered\_key has no docstring even though its body is a non-obvious bit trick: it maps float bits onto an orderable unsigned key \(fully inverting negative patterns, flipping only the sign bit otherwise\) so the packed score keys that \_k3\_top16 sorts compare correctly. Style guide section 3.8.3 makes a docstring mandatory for every function with non-obvious logic, and every other nontrivial helper in this new file \(\_k3\_order\_pairs, \_k3\_top16, \_k3\_await\_count, \_k3\_route\_row, \_k3\_shared\_down\_tile\) has one; only the self-evident one-liners \(\_k3\_add, \_k3\_max\_pair, \_k3\_sleep\) go without. Add a short docstring, e.g. one line stating that the function maps FP32 bits to a monotonically ordered uint32 key \(negatives fully inverted, non-negatives sign-flipped\) for the bitonic top-k in \_k3\_route\_row.

    lightseek-bot lightseek-bot commented on Nov 17, 2026 23:07 UTC
    Reviewer

    <!-- lightseek-pr-style-review -->
    <!-- style-review-revision:d3020c5afadb27f5f3b89c7458ad5cc4fad3d430aa662ef32fd9ae5d75ff9f9a -->
    <!-- style-review-content:40001ad9fe0b2a9ab97baf42e80f457b57fa90bf38313196c4bba4b5e94629d2 -->
    2 style findings. See inline comments.

    lightseek-bot lightseek-bot commented on code on Nov 17, 2026 23:07 UTC
    Code Review
    tokenspeed-kernel/python/tokenspeed_kernel/ops/communication/_iris/kimi_k3/latent_route.py:1
    @@ -0,0 +1,354 @@
    +# Copyright (c) 2026 LightSeek Foundation
    +#
    +# Permission is hereby granted, free of charge, to any person obtaining a copy
    +# of this software and associated documentation files (the "Software"), to deal
    +# in the Software without restriction, including without limitation the rights
    +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    +# copies of the Software, and to permit persons to whom the Software is
    +# furnished to do so, subject to the following conditions:
    +#
    +# The above copyright notice and this permission notice shall be included in
    +# all copies or substantial portions of the Software.
    +#
    +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    +# SOFTWARE.
    +
    +"""Route K3 decode MoE rows and project the shared experts inside the gather.
    +
    +The latent-input gather's programs mostly wait for peer words. When every rank
    +projects all router columns, the router program of each row routes it there,
    +exactly as ``kimi3_sigmoid_bias_topk_sorted`` does through 32 rows (the same
    +scratch protocol, so the two may alternate on one scratch), and programs
    +waiting on the shared SiTU input write the shared experts' down projection.
    +"""
    +
    +from tokenspeed_kernel._triton import gl, gluon
    +from tokenspeed_kernel.ops.communication._iris.synchronization import wait_vmem
    +
    +K3_ROUTE_EXPERTS = gl.constexpr(896)
    +K3_ROUTE_TOPK = gl.constexpr(16)
    +# kimi3_sigmoid_bias_topk_sorted's scratch: [896 * 8] arrival masks and 16
    +# counters, then the self-sorting launches' two [896] mask buffers, their two
    +# arrival counters and the launch epoch.
    +K3_ROUTE_SELF_MASKS = gl.constexpr(896 * 8 + 16)
    +K3_ROUTE_SCRATCH_WORDS = 896 * 8 + 16 + 2 * 896 + 16
    +
    +
    +@gluon.jit
    +def _k3_add(a, b):
    +    return a + b
    +
    +
    +@gluon.jit
    +def _k3_max_pair(key_a, index_a, key_b, index_b):
    +    return gl.maximum(key_a, key_b), gl.maximum(index_a, index_b)
    +
    +
    +@gluon.jit
    +def _k3_order_pairs(keys, index, flip, AXIS: gl.constexpr, DIMS: gl.constexpr):
    +    """Order the pairs of hypercube ``keys`` along its ``AXIS``-th inner axis.
    +
    +    ``triton.language.standard._compare_and_swap``: a pair's left key becomes
    +    the larger where ``flip`` holds and the smaller elsewhere. Bit
    +    ``AXIS + 2`` of ``index`` is a key's position along the axis.
    +    """
    +    bits = keys.to(gl.int64, bitcast=True)
    +    partner = bits ^ gl.xor_sum(bits, DIMS - 1 - AXIS, keep_dims=True)
    +    partner = partner.to(gl.uint64, bitcast=True)
    +    right = ((index >> (AXIS + 2)) & 1) != 0
    +    return gl.where((keys > partner) != (flip ^ right), partner, keys)
    +
    +
    +@gluon.jit
    +def _k3_top16(keys, index):
    +    """Return the 16 largest of 1024 distinct ``keys``, in descending order.
    +
    +    ``triton.language.standard.sort_impl``'s bitonic top-k on a hypercube of
    +    ``keys``, which hold their position ``index`` four to a thread. The
    +    runs of 16 lie along lane bits 0-3 (``index`` bits 2-5), so pairs meet
    +    by lane swizzles, and the first two halvings fold a thread's registers,
    +    so it holds one key from then on. Flips and sides are bits of ``index``.
    +    """
    +    cube = gl.permute(gl.reshape(keys, [2] * 10), [0, 1, 2, 3, 8, 9, 4, 5, 6, 7])
    +    index = gl.permute(gl.reshape(index, [2] * 10), [0, 1, 2, 3, 8, 9, 4, 5, 6, 7])
    +    # Sort runs of 16, alternately ascending and descending; the flip of
    +    # stage 4 is the first halved axis, ``index`` bit 0.
    +    for stage in gl.static_range(1, 5):
    +        flip = ((index >> ((stage + 2) * (stage < 4))) & 1) != 0
    +        for i in gl.static_range(stage):
    +            cube = _k3_order_pairs(cube, index, flip, stage - 1 - i, 10)
    +    # The larger halves of two opposite runs form a run holding their top 16.
    +    # Halvings take ``index`` bits 0, 1, 6, 7, 8 and 9 in turn.
    +    for i in gl.static_range(5, 11):
    +        cube, index = gl.reduce((cube, index), 10 - i, _k3_max_pair)
    +        if i < 10:
    +            flip = ((index >> (i - 4 + 4 * (i >= 6))) & 1) != 0
    +        else:
    +            flip = True
    +        for j in gl.static_range(4):
    +            cube = _k3_order_pairs(cube, index, flip, 3 - j, 14 - i)
    +    return gl.reshape(cube, [16])
    +
    +
    +@gluon.jit
    +def _k3_sleep():
    +    gl.inline_asm_elementwise(
    +        asm="s_sleep 2",
    +        constraints="=r,~{memory}",
    +        args=[],
    +        dtype=gl.int32,
    +        is_pure=False,
    +        pack=1,
    +    )
    +
    +
    +@gluon.jit
    +def _k3_await_count(counter, target):
    +    """Wait until ``counter`` reaches ``target``, then acquire once.
    +
    +    The polls are relaxed so they do not invalidate this CU's caches for the
    +    other programs; the final acquire does, and the barrier keeps every
    +    subgroup's loads after it.
    +    """
    +    arrived = gl.atomic_add(counter, 0, sem="relaxed", scope="gpu")
    +    while arrived < target:
    +        _k3_sleep()
    +        arrived = gl.atomic_add(counter, 0, sem="relaxed", scope="gpu")
    +    gl.atomic_add(counter, 0, sem="acquire", scope="gpu")
    +    gl.barrier()
    +
    +
    +@gluon.jit
    +def _k3_ordered_key(value):
    +    bits = value.to(gl.uint32, bitcast=True)
    +    sign = gl.full_like(bits, 0x80000000)
    +    return bits ^ gl.where((bits & sign) != 0, gl.full_like(bits, 0xFFFFFFFF), sign)
    +
    +
    +@gluon.jit
    +def _k3_popcount(words):

    <!-- lightseek-pr-style-review -->
    The new helper \_k3\_popcount has no docstring even though its five-line SWAR population count over the expert-arrival masks \(magic constants 0x55555555, 0x33333333, 0x0F0F0F0F, 0x01010101\) is non-obvious logic that a reader must decode before trusting the route-offset arithmetic in \_k3\_route\_row. Style guide section 3.8.3 makes a docstring mandatory for every function with non-obvious logic, and the comparable nontrivial helpers in this file are all documented. Add a short docstring, e.g. one line stating that the function returns the per-word set-bit count of the uint32 mask lanes as int32, matching the neighboring documented helpers.

    lightseek-bot lightseek-bot commented on Nov 18, 2026 00:08 UTC
    Reviewer

    <!-- lightseek-pr-style-review -->
    <!-- style-review-revision:d8dd043d35de0e3485681ac7bb19d0a36543715f99a91396e300d8f027ec45eb -->
    <!-- style-review-content:98b3a004f8ecb2965f338fe8edb9809d107c3afd6c1ed4f3007abda4d5d81fea -->
    Style LGTM.

    Max191 Max191 commented on code on Nov 18, 2026 00:12 UTC
    Code Review
    tokenspeed-kernel/python/tokenspeed_kernel/ops/communication/_iris/kimi_k3/latent_route.py:1
    @@ -0,0 +1,357 @@
    +# Copyright (c) 2026 LightSeek Foundation
    +#
    +# Permission is hereby granted, free of charge, to any person obtaining a copy
    +# of this software and associated documentation files (the "Software"), to deal
    +# in the Software without restriction, including without limitation the rights
    +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    +# copies of the Software, and to permit persons to whom the Software is
    +# furnished to do so, subject to the following conditions:
    +#
    +# The above copyright notice and this permission notice shall be included in
    +# all copies or substantial portions of the Software.
    +#
    +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    +# SOFTWARE.
    +
    +"""Route K3 decode MoE rows and project the shared experts inside the gather.
    +
    +The latent-input gather's programs mostly wait for peer words. When every rank
    +projects all router columns, the router program of each row routes it there,
    +exactly as ``kimi3_sigmoid_bias_topk_sorted`` does through 32 rows (the same
    +scratch protocol, so the two may alternate on one scratch), and programs
    +waiting on the shared SiTU input write the shared experts' down projection.
    +"""
    +
    +from tokenspeed_kernel._triton import gl, gluon
    +from tokenspeed_kernel.ops.communication._iris.synchronization import wait_vmem
    +
    +K3_ROUTE_EXPERTS = gl.constexpr(896)
    +K3_ROUTE_TOPK = gl.constexpr(16)
    +# kimi3_sigmoid_bias_topk_sorted's scratch: [896 * 8] arrival masks and 16
    +# counters, then the self-sorting launches' two [896] mask buffers, their two
    +# arrival counters and the launch epoch.
    +K3_ROUTE_SELF_MASKS = gl.constexpr(896 * 8 + 16)
    +K3_ROUTE_SCRATCH_WORDS = 896 * 8 + 16 + 2 * 896 + 16
    +
    +
    +@gluon.jit
    +def _k3_add(a, b):
    +    return a + b
    +
    +
    +@gluon.jit
    +def _k3_max_pair(key_a, index_a, key_b, index_b):
    +    return gl.maximum(key_a, key_b), gl.maximum(index_a, index_b)
    +
    +
    +@gluon.jit
    +def _k3_order_pairs(keys, index, flip, AXIS: gl.constexpr, DIMS: gl.constexpr):
    +    """Order the pairs of hypercube ``keys`` along its ``AXIS``-th inner axis.
    +
    +    ``triton.language.standard._compare_and_swap``: a pair's left key becomes
    +    the larger where ``flip`` holds and the smaller elsewhere. Bit
    +    ``AXIS + 2`` of ``index`` is a key's position along the axis.
    +    """
    +    bits = keys.to(gl.int64, bitcast=True)
    +    partner = bits ^ gl.xor_sum(bits, DIMS - 1 - AXIS, keep_dims=True)
    +    partner = partner.to(gl.uint64, bitcast=True)
    +    right = ((index >> (AXIS + 2)) & 1) != 0
    +    return gl.where((keys > partner) != (flip ^ right), partner, keys)
    +
    +
    +@gluon.jit
    +def _k3_top16(keys, index):
    +    """Return the 16 largest of 1024 distinct ``keys``, in descending order.
    +
    +    ``triton.language.standard.sort_impl``'s bitonic top-k on a hypercube of
    +    ``keys``, which hold their position ``index`` four to a thread. The
    +    runs of 16 lie along lane bits 0-3 (``index`` bits 2-5), so pairs meet
    +    by lane swizzles, and the first two halvings fold a thread's registers,
    +    so it holds one key from then on. Flips and sides are bits of ``index``.
    +    """
    +    cube = gl.permute(gl.reshape(keys, [2] * 10), [0, 1, 2, 3, 8, 9, 4, 5, 6, 7])
    +    index = gl.permute(gl.reshape(index, [2] * 10), [0, 1, 2, 3, 8, 9, 4, 5, 6, 7])
    +    # Sort runs of 16, alternately ascending and descending; the flip of
    +    # stage 4 is the first halved axis, ``index`` bit 0.
    +    for stage in gl.static_range(1, 5):
    +        flip = ((index >> ((stage + 2) * (stage < 4))) & 1) != 0
    +        for i in gl.static_range(stage):
    +            cube = _k3_order_pairs(cube, index, flip, stage - 1 - i, 10)
    +    # The larger halves of two opposite runs form a run holding their top 16.
    +    # Halvings take ``index`` bits 0, 1, 6, 7, 8 and 9 in turn.
    +    for i in gl.static_range(5, 11):
    +        cube, index = gl.reduce((cube, index), 10 - i, _k3_max_pair)
    +        if i < 10:
    +            flip = ((index >> (i - 4 + 4 * (i >= 6))) & 1) != 0
    +        else:
    +            flip = True
    +        for j in gl.static_range(4):
    +            cube = _k3_order_pairs(cube, index, flip, 3 - j, 14 - i)
    +    return gl.reshape(cube, [16])
    +
    +
    +@gluon.jit
    +def _k3_sleep():
    +    gl.inline_asm_elementwise(
    +        asm="s_sleep 2",
    +        constraints="=r,~{memory}",
    +        args=[],
    +        dtype=gl.int32,
    +        is_pure=False,
    +        pack=1,
    +    )
    +
    +
    +@gluon.jit
    +def _k3_await_count(counter, target):
    +    """Wait until ``counter`` reaches ``target``, then acquire once.
    +
    +    The polls are relaxed so they do not invalidate this CU's caches for the
    +    other programs; the final acquire does, and the barrier keeps every
    +    subgroup's loads after it.
    +    """
    +    arrived = gl.atomic_add(counter, 0, sem="relaxed", scope="gpu")
    +    while arrived < target:
    +        _k3_sleep()
    +        arrived = gl.atomic_add(counter, 0, sem="relaxed", scope="gpu")
    +    gl.atomic_add(counter, 0, sem="acquire", scope="gpu")
    +    gl.barrier()
    +
    +
    +@gluon.jit
    +def _k3_ordered_key(value):
    +    """Map FP32 ``value`` to a uint32 key in the same order (negative patterns
    +    fully inverted, others sign-flipped) for ``_k3_top16``'s packed keys."""
    +    bits = value.to(gl.uint32, bitcast=True)
    +    sign = gl.full_like(bits, 0x80000000)
    +    return bits ^ gl.where((bits & sign) != 0, gl.full_like(bits, 0xFFFFFFFF), sign)
    +
    +
    +@gluon.jit
    +def _k3_popcount(words):
    +    """Set bits in each 32-bit lane of the expert arrival ``words``, as int32."""

    Can we add docs to explain the fancy bitwise arithmetic here?

    Max191 Max191 commented on code on Nov 18, 2026 00:15 UTC
    Code Review
    python/tokenspeed/runtime/models/kimi_k3.py:1
    @@ -2796,6 +2796,14 @@ def pack_input_projection_weights(self) -> None:
                 )
                 offset += rows
     
    +    def _apply_reads_gathered_fp8(self) -> bool:
    +        """Whether the A8W4 apply takes the FP8 latent the gather quantizes
    +        instead of quantizing the BF16 latent itself."""
    +        return (
    +            self.experts.plan.get("apply_kernel_name")
    +            == "gluon_mxfp4_a8w4_situ_precomputed_moe_apply"

    Can we use something other than the kernel registration name? Maybe add a new attribute to the plan?

    claude[bot] claude[bot] commented on code on Nov 18, 2026 00:33 UTC
    Code Review
    python/tokenspeed/runtime/models/kimi_k3.py:1
    @@ -2796,6 +2796,11 @@ def pack_input_projection_weights(self) -> None:
                 )
                 offset += rows
     
    +    def _apply_reads_gathered_fp8(self) -> bool:
    +        """Whether the apply takes the FP8 latent the gather quantizes instead
    +        of quantizing the BF16 latent itself."""
    +        return self.experts.plan.get("supports_fp8_per_tensor_input", False)

    🟡 Nit: The False default is a defensive fallback: moe_plan always emits supports_fp8_per_tensor_input, so a missing key can only mean a plan that didn't come from moe_plan or a renamed/misspelled key — and the default would silently drop the FP8 handoff (the apply re-quantizes the BF16 latent), a hidden performance regression rather than an error. The established pattern for this trait family is a direct-indexing property on the experts layer, like supports_prequantized_input (python/tokenspeed/runtime/layers/moe/expert.py:727), which fails loudly on a missing key. Consider self.experts.plan["supports_fp8_per_tensor_input"], ideally as a supports_fp8_per_tensor_input property next to its sibling.

    claude[bot] claude[bot] commented on code on Nov 18, 2026 00:33 UTC
    Code Review
    tokenspeed-kernel/python/tokenspeed_kernel/ops/moe/__init__.py:1
    @@ -2239,6 +2239,9 @@ def moe_plan(
         supports_prequantized_input = True in apply_spec.traits.get(
             "supports_prequantized_input", frozenset({False})
         )
    +    supports_fp8_per_tensor_input = True in apply_spec.traits.get(
    +        "supports_fp8_per_tensor_input", frozenset({False})
    +    )

    🟡 Nit: No test covers this trait end to end: the runtime tests in test_kimi_k3_config.py set plan["supports_fp8_per_tensor_input"] by hand, so if the frozenset({True}) declaration in ops/moe/gluon.py or this extraction were dropped (or the key misspelled on either side), nothing fails — the gather just stops handing over the FP8 latent and the apply silently re-quantizes, the fallback-hides-perf-regression case AGENTS.md calls out. test_kimi3_mxfp4_situ_selection_on_cdna4 (tokenspeed-kernel/test/test_kernel_api_selection.py:4374) already builds the real plan for both A8W4 situ kernels and asserts per-kernel route-sort traits; one more line there, assert plan["supports_fp8_per_tensor_input"] is (ep_size == 1), would guard the declaration and this extraction together.

    lightseek-bot lightseek-bot commented on code on Nov 18, 2026 00:49 UTC
    Code Review
    tokenspeed-kernel/python/tokenspeed_kernel/ops/communication/_iris/kimi_k3/__init__.py:1
    @@ -793,34 +900,152 @@ def latent_input_gather(
                 SPLIT_K=split_k,
                 NUM_WARPS=_K3_LATENT_GEMM_NUM_WARPS,
                 WARPS_M=warps_m,
    -            REGION0_START=rank * router_local,
    +            REGION0_START=router_start,
                 REGION0_TILES=gemm_router_tiles,
                 REGION1_START=_K3_ROUTER + rank * latent_local,
                 REGION1_TILES=gemm_latent_tiles,
                 REGION2_START=_K3_ROUTER + _K3_LATENT,
                 REGION2_TILES=gemm_shared_tiles,
                 num_warps=_K3_LATENT_GEMM_NUM_WARPS,
             )
    +        return partials, split_k, split_stride
    +
    +    def can_latent_input_gather_routed(
    +        self,
    +        hidden_states: torch.Tensor,
    +        packed_weight: torch.Tensor,
    +        routing: K3MoeRouting,
    +        down_weight: torch.Tensor,
    +        down_out: torch.Tensor | None,
    +    ) -> bool:
    +        """Whether ``latent_input_gather_routed`` serves these decode rows."""
    +        from tokenspeed_kernel.ops.communication._iris.kimi_k3.latent_route import (
    +            K3_ROUTE_SCRATCH_WORDS,
    +        )
    +
    +        if not self.can_latent_input_gather(hidden_states, packed_weight):
    +            return False
    +        rows = hidden_states.shape[0]
    +        device = hidden_states.device
    +        block_size = routing.block_size
    +        return (
    +            rows <= _K3_LATENT_ROUTED_MAX_ROWS
    +            and block_size > 0
    +            and not block_size & (block_size - 1)
    +            and all(
    +                t.shape == shape
    +                and t.dtype == dtype
    +                and t.is_contiguous()
    +                and t.device == device
    +                for t, shape, dtype in (
    +                    (routing.correction_bias, (_K3_ROUTER,), torch.float32),
    +                    (routing.scratch, (K3_ROUTE_SCRATCH_WORDS,), torch.int32),
    +                    (down_weight, (_K3_HIDDEN, _K3_SHARED), torch.bfloat16),
    +                )
    +            )
    +            and (
    +                down_out is None
    +                or (
    +                    down_out.shape == (rows, _K3_HIDDEN)
    +                    and down_out.dtype == torch.bfloat16
    +                    and down_out.device == device
    +                    and down_out.stride(1) == 1
    +                    and down_out.stride(0) >= _K3_HIDDEN
    +                )
    +            )
    +        )
    +
    +    def latent_input_gather_routed(
    +        self,
    +        hidden_states: torch.Tensor,
    +        packed_weight: torch.Tensor,
    +        *,
    +        beta: float,
    +        linear_beta: float | None,
    +        routing: K3MoeRouting,
    +        down_weight: torch.Tensor,
    +        down_out: torch.Tensor | None = None,
    +        quantize: bool = False,
    +    ) -> tuple:

    <!-- lightseek-pr-style-review -->
    latent\_input\_gather\_routed is annotated as returning a bare tuple, but it always returns the same fixed five-element tuple of heterogeneous values, \(router\_logits, routed\_input, routes, shared\_partial, routed\_fp8\), as its own docstring spells out. A fixed number of elements with different types is exactly the case typed tuples cover, and the neighboring \_latent\_input\_partials added in the same change annotates its return as tuple\[torch.Tensor, int, int\], so the bare tuple hides this interface from type checkers and readers. Spell out the element types, e.g. -&gt; tuple\[torch.Tensor, torch.Tensor, tuple\[torch.Tensor, ...\], torch.Tensor, tuple\[torch.Tensor, torch.Tensor\] \| None\], wrapping the signature as needed to stay within the line limit.

    lightseek-bot lightseek-bot commented on Nov 18, 2026 00:49 UTC
    Reviewer

    <!-- lightseek-pr-style-review -->
    <!-- style-review-revision:90c8b3a25c7fa6272f456294ebd0a849e611831c8fc067221dd67e9e487260c5 -->
    <!-- style-review-content:5cf01ca58bd3ce798801b90fdec0025ec5382bf93dc16277c6e7408534d189b2 -->
    1 style finding. See inline comments.

    lightseek-bot lightseek-bot commented on Nov 18, 2026 02:43 UTC
    Reviewer

    <!-- lightseek-pr-style-review -->
    <!-- style-review-revision:df613d1ae783a6aebf32e63318acf9483c638eba3b56f03afa8c883a09aecce0 -->
    <!-- style-review-content:5f6710e5f979fb3bbc9e869218ac1fb03a0b2da487415dde279d788a31db25f0 -->
    Style LGTM.

    antiagainst antiagainst approved these changes on Nov 18, 2026 02:43 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    Yu-Zhewen Yu-Zhewen
    Labels
    risk: low confidence: 80.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 54.7% (MEDIUM) · Higher = larger blast radius
    54.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 80.5% · Lower = rushed or shallow review
    80.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 10.7% · Safe to merge
    10.7%