"""Kimi-K3.1: per-layer routed expert counts (non-uniform expert pruning).

An expert-pruned checkpoint lists the routed experts of every decoder layer in config.json
`text_config.num_experts_per_layer` (length num_hidden_layers; the dense layer 0 is 0).
KimiLinearConfig keeps unknown keys as attributes, so no config change is needed.
`text_config.num_experts` stays the maximum (896), so the checkpoint expert-name mapping in
`load_weights` is unchanged. Without the field the model behaves exactly as before.

Touched files (NVIDIA path only; the AMD/ROCm path models/kimi_k3/amd is not patched):
  * models/kimi_k3/nvidia/model.py
      KimiMoE builds the router gate, e_score_correction_bias and FusedMoE with the layer's
      expert count. EPLB is rejected for a pruned checkpoint (its expert counts assume one
      value for all layers).
  * models/kimi_k3/nvidia/specialized_decode/runtime/__init__.py
      decode_backend=latency_specialized hard-codes 896 experts in its CuTe DSL kernels:
      a pruned checkpoint is reported as unsupported instead of running wrong kernels.
"""

from __future__ import annotations

from ._ops import Edit

DESCRIPTION = "per-layer routed expert counts for Kimi-K3.1 (text_config.num_experts_per_layer)"

MODEL = "models/kimi_k3/nvidia/model.py"
SPECIALIZED = "models/kimi_k3/nvidia/specialized_decode/runtime/__init__.py"


def ops():
    return [
        Edit(
            MODEL,
            "        num_experts = config.num_experts\n"
            "        num_experts_per_token = config.num_experts_per_token\n",
            "        num_experts = config.num_experts\n"
            "        # non-uniform expert pruning: routed experts of this layer\n"
            "        num_experts_per_layer = getattr(config, \"num_experts_per_layer\", None)\n"
            "        if num_experts_per_layer is not None:\n"
            "            num_experts = int(num_experts_per_layer[layer_idx])\n"
            "            assert not vllm_config.parallel_config.enable_eplb, (\n"
            "                \"EPLB is not supported with num_experts_per_layer\"\n"
            "            )\n"
            "        num_experts_per_token = config.num_experts_per_token\n",
            "KimiMoE: use the layer's routed expert count",
        ),
        Edit(
            SPECIALIZED,
            "        (\n"
            "            moe != (\"situ\", 4.0, 25.0, 896, 16, 1, 1, \"sigmoid\"),\n",
            "        (\n"
            "            getattr(text, \"num_experts_per_layer\", None) is not None,\n"
            "            \"non-uniformly expert-pruned checkpoints (num_experts_per_layer)\",\n"
            "        ),\n"
            "        (\n"
            "            moe != (\"situ\", 4.0, 25.0, 896, 16, 1, 1, \"sigmoid\"),\n",
            "latency_specialized decode: reject pruned checkpoints (kernels assume 896 experts)",
        ),
    ]
