|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Latent MoE and SiTU-activated MLP layers for Kimi-K3.""" |
| 16 | + |
| 17 | +from typing import Optional |
| 18 | + |
| 19 | +from flax import nnx |
| 20 | +import jax.numpy as jnp |
| 21 | +from jax.sharding import Mesh, NamedSharding |
| 22 | + |
| 23 | +from maxtext.common.common_types import Array, Config, DType, ShardMode |
| 24 | +from maxtext.layers import moe |
| 25 | +from maxtext.layers.initializers import NdInitializer, nd_dense_init |
| 26 | +from maxtext.layers.linears import DenseGeneral, situ_gate, situ_linear |
| 27 | +from maxtext.layers.normalizations import RMSNorm |
| 28 | +from maxtext.layers.quantizations import AqtQuantization as Quant |
| 29 | + |
| 30 | + |
| 31 | +class KimiDenseMLP(nnx.Module): |
| 32 | + """Dense MLP with SiTU activations (Layer 0 and shared experts).""" |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + in_features: int, |
| 37 | + intermediate_dim: int, |
| 38 | + out_features: Optional[int] = None, |
| 39 | + dtype: DType = jnp.float32, |
| 40 | + weight_dtype: DType = jnp.float32, |
| 41 | + kernel_init: NdInitializer = nd_dense_init(1.0, "fan_in", "truncated_normal"), |
| 42 | + quant: Optional[Quant] = None, |
| 43 | + shard_mode: ShardMode = ShardMode.AUTO, |
| 44 | + matmul_precision: str = "default", |
| 45 | + mesh: Optional[Mesh] = None, |
| 46 | + *, |
| 47 | + rngs: nnx.Rngs, |
| 48 | + ): |
| 49 | + out_features = out_features or in_features |
| 50 | + self.in_features = in_features |
| 51 | + self.intermediate_dim = intermediate_dim |
| 52 | + self.out_features = out_features |
| 53 | + self.dtype = dtype |
| 54 | + self.weight_dtype = weight_dtype |
| 55 | + |
| 56 | + self.wi_0 = DenseGeneral( |
| 57 | + in_features_shape=in_features, |
| 58 | + out_features_shape=intermediate_dim, |
| 59 | + dtype=dtype, |
| 60 | + weight_dtype=weight_dtype, |
| 61 | + kernel_init=kernel_init, |
| 62 | + kernel_axes=("embed", "mlp"), |
| 63 | + quant=quant, |
| 64 | + shard_mode=shard_mode, |
| 65 | + matmul_precision=matmul_precision, |
| 66 | + mesh=mesh, |
| 67 | + rngs=rngs, |
| 68 | + ) |
| 69 | + self.wi_1 = DenseGeneral( |
| 70 | + in_features_shape=in_features, |
| 71 | + out_features_shape=intermediate_dim, |
| 72 | + dtype=dtype, |
| 73 | + weight_dtype=weight_dtype, |
| 74 | + kernel_init=kernel_init, |
| 75 | + kernel_axes=("embed", "mlp"), |
| 76 | + quant=quant, |
| 77 | + shard_mode=shard_mode, |
| 78 | + matmul_precision=matmul_precision, |
| 79 | + mesh=mesh, |
| 80 | + rngs=rngs, |
| 81 | + ) |
| 82 | + self.wo = DenseGeneral( |
| 83 | + in_features_shape=intermediate_dim, |
| 84 | + out_features_shape=out_features, |
| 85 | + dtype=dtype, |
| 86 | + weight_dtype=weight_dtype, |
| 87 | + kernel_init=kernel_init, |
| 88 | + kernel_axes=("mlp", "embed"), |
| 89 | + quant=quant, |
| 90 | + shard_mode=shard_mode, |
| 91 | + matmul_precision=matmul_precision, |
| 92 | + mesh=mesh, |
| 93 | + rngs=rngs, |
| 94 | + ) |
| 95 | + |
| 96 | + def __call__( |
| 97 | + self, |
| 98 | + x: Array, |
| 99 | + out_sharding: Optional[NamedSharding] = None, |
| 100 | + ) -> Array: |
| 101 | + """Forward pass of KimiDenseMLP.""" |
| 102 | + gate = self.wi_0(x) |
| 103 | + up = self.wi_1(x) |
| 104 | + act = situ_gate(gate) * situ_linear(up) |
| 105 | + return self.wo(act.astype(self.dtype), out_sharding=out_sharding) |
| 106 | + |
| 107 | + |
| 108 | +# Logical sharding axes (same names as `moe.RoutedMoE` / the DeepSeek gate). |
| 109 | +ROUTER_KERNEL_AXES = ("embed_router", None) |
| 110 | + |
| 111 | + |
| 112 | +class KimiLatentMoEBlock(nnx.Module): |
| 113 | + """Kimi-K3 Latent MoE Block with routed and shared experts. |
| 114 | +
|
| 115 | + The router reads the full hidden state; the routed experts run on a down-projected latent |
| 116 | + (7168 -> 3584), followed by an RMSNorm and an up-projection; shared experts read the full |
| 117 | + hidden state. |
| 118 | +
|
| 119 | + The router and routed experts are a `moe.RoutedMoE` (sorted/grouped dispatch: megablox / |
| 120 | + tokamax GMM / `ragged_dot`, expert parallelism), which needs `config` and `mesh`. The config |
| 121 | + must set `moe_expert_input_dim=routed_expert_hidden_size` and |
| 122 | + `moe_router_input_dim=hidden_size`; the latent is the expert input and the hidden state is |
| 123 | + passed as `gate_inputs`. |
| 124 | + """ |
| 125 | + |
| 126 | + def __init__( |
| 127 | + self, |
| 128 | + hidden_size: int = 7168, |
| 129 | + num_experts: int = 896, |
| 130 | + top_k: int = 16, |
| 131 | + routed_expert_hidden_size: int = 3584, |
| 132 | + moe_intermediate_size: int = 3072, |
| 133 | + num_shared_experts: int = 2, |
| 134 | + shared_intermediate_size: Optional[int] = None, |
| 135 | + routed_scaling_factor: float = 1.0, |
| 136 | + moe_renormalize: bool = True, |
| 137 | + latent_moe_use_norm: bool = True, |
| 138 | + rms_norm_eps: float = 1e-5, |
| 139 | + dtype: DType = jnp.float32, |
| 140 | + weight_dtype: DType = jnp.float32, |
| 141 | + kernel_init: NdInitializer = nd_dense_init(1.0, "fan_in", "truncated_normal"), |
| 142 | + quant: Optional[Quant] = None, |
| 143 | + shard_mode: ShardMode = ShardMode.AUTO, |
| 144 | + matmul_precision: str = "default", |
| 145 | + mesh: Optional[Mesh] = None, |
| 146 | + config: Optional[Config] = None, |
| 147 | + *, |
| 148 | + rngs: nnx.Rngs, |
| 149 | + ): |
| 150 | + self.hidden_size = hidden_size |
| 151 | + self.num_experts = num_experts |
| 152 | + self.top_k = top_k |
| 153 | + self.routed_expert_hidden_size = routed_expert_hidden_size |
| 154 | + self.moe_intermediate_size = moe_intermediate_size |
| 155 | + self.latent_moe_use_norm = latent_moe_use_norm |
| 156 | + self.dtype = dtype |
| 157 | + self.weight_dtype = weight_dtype |
| 158 | + |
| 159 | + # Routed down projection: 7168 -> 3584 |
| 160 | + self.routed_expert_down_proj = DenseGeneral( |
| 161 | + in_features_shape=hidden_size, |
| 162 | + out_features_shape=routed_expert_hidden_size, |
| 163 | + dtype=dtype, |
| 164 | + weight_dtype=weight_dtype, |
| 165 | + kernel_init=kernel_init, |
| 166 | + # The 3584-wide latent axis is deliberately unsharded (replicated); `embed` carries the sharding. |
| 167 | + kernel_axes=("embed", None), |
| 168 | + quant=quant, |
| 169 | + shard_mode=shard_mode, |
| 170 | + matmul_precision=matmul_precision, |
| 171 | + mesh=mesh, |
| 172 | + rngs=rngs, |
| 173 | + ) |
| 174 | + |
| 175 | + # 896 Routed Experts: 3584 -> 3072 -> 3584 (router on the 7168 hidden state) |
| 176 | + if config is None or mesh is None: |
| 177 | + raise ValueError("KimiLatentMoEBlock's routed experts are a moe.RoutedMoE, which needs `config` and `mesh`.") |
| 178 | + expected = { |
| 179 | + "moe_expert_input_dim": routed_expert_hidden_size, |
| 180 | + "moe_router_input_dim": hidden_size, |
| 181 | + "num_experts": num_experts, |
| 182 | + "num_experts_per_tok": top_k, |
| 183 | + "routed_scaling_factor": routed_scaling_factor, |
| 184 | + } |
| 185 | + mismatched = {k: (getattr(config, k), v) for k, v in expected.items() if getattr(config, k) != v} |
| 186 | + if mismatched: |
| 187 | + raise ValueError(f"config disagrees with KimiLatentMoEBlock args (config, arg): {mismatched}") |
| 188 | + if not moe_renormalize: |
| 189 | + raise ValueError("RoutedMoE always renormalizes sigmoid top-k weights; moe_renormalize=False is unsupported.") |
| 190 | + # This block returns only the MoE output (the decoder layer expects a single array), so the RoutedMoE |
| 191 | + # load-balance loss would be dropped; fail fast instead of training without it. (Router-bias updates, |
| 192 | + # `routed_bias_update_rate > 0`, are already rejected by config validation for non-DeepSeek decoder blocks.) |
| 193 | + if config.load_balance_loss_weight > 0.0: |
| 194 | + raise NotImplementedError( |
| 195 | + "KimiLatentMoEBlock does not propagate the MoE load-balance loss yet;" |
| 196 | + f" got load_balance_loss_weight={config.load_balance_loss_weight}. Set it to 0." |
| 197 | + ) |
| 198 | + self.routed_experts = moe.RoutedMoE( |
| 199 | + config=config, |
| 200 | + num_experts=num_experts, |
| 201 | + num_experts_per_tok=top_k, |
| 202 | + mesh=mesh, |
| 203 | + kernel_init=kernel_init, |
| 204 | + kernel_axes=ROUTER_KERNEL_AXES, |
| 205 | + intermediate_dim=moe_intermediate_size, |
| 206 | + weight_dtype=weight_dtype, |
| 207 | + dtype=dtype, |
| 208 | + quant=quant, |
| 209 | + rngs=rngs, |
| 210 | + ) |
| 211 | + |
| 212 | + # Post-expert RMSNorm: 3584 |
| 213 | + if self.latent_moe_use_norm: |
| 214 | + self.routed_expert_norm = RMSNorm( |
| 215 | + num_features=routed_expert_hidden_size, |
| 216 | + epsilon=rms_norm_eps, |
| 217 | + dtype=dtype, |
| 218 | + weight_dtype=weight_dtype, |
| 219 | + kernel_axes=("norm",), |
| 220 | + shard_mode=shard_mode, |
| 221 | + rngs=rngs, |
| 222 | + ) |
| 223 | + else: |
| 224 | + self.routed_expert_norm = None |
| 225 | + |
| 226 | + # Routed up projection: 3584 -> 7168 |
| 227 | + self.routed_expert_up_proj = DenseGeneral( |
| 228 | + in_features_shape=routed_expert_hidden_size, |
| 229 | + out_features_shape=hidden_size, |
| 230 | + dtype=dtype, |
| 231 | + weight_dtype=weight_dtype, |
| 232 | + kernel_init=kernel_init, |
| 233 | + kernel_axes=(None, "embed"), # latent axis unsharded, as in the down projection. |
| 234 | + quant=quant, |
| 235 | + shard_mode=shard_mode, |
| 236 | + matmul_precision=matmul_precision, |
| 237 | + mesh=mesh, |
| 238 | + rngs=rngs, |
| 239 | + ) |
| 240 | + |
| 241 | + # Shared Experts: 7168 -> 6144 -> 7168 |
| 242 | + if num_shared_experts > 0: |
| 243 | + shared_dim = shared_intermediate_size or (moe_intermediate_size * num_shared_experts) |
| 244 | + self.shared_expert = KimiDenseMLP( |
| 245 | + in_features=hidden_size, |
| 246 | + intermediate_dim=shared_dim, |
| 247 | + out_features=hidden_size, |
| 248 | + dtype=dtype, |
| 249 | + weight_dtype=weight_dtype, |
| 250 | + kernel_init=kernel_init, |
| 251 | + quant=quant, |
| 252 | + shard_mode=shard_mode, |
| 253 | + matmul_precision=matmul_precision, |
| 254 | + mesh=mesh, |
| 255 | + rngs=rngs, |
| 256 | + ) |
| 257 | + else: |
| 258 | + self.shared_expert = None |
| 259 | + |
| 260 | + def __call__( |
| 261 | + self, |
| 262 | + hidden_states: Array, |
| 263 | + out_sharding: Optional[NamedSharding] = None, |
| 264 | + ) -> Array: |
| 265 | + """Forward pass of KimiLatentMoEBlock. |
| 266 | +
|
| 267 | + Args: |
| 268 | + hidden_states: Input tensor of shape [..., hidden_size]. |
| 269 | + out_sharding: Optional sharding specification. |
| 270 | +
|
| 271 | + Returns: |
| 272 | + Output tensor of shape [..., hidden_size]. |
| 273 | + """ |
| 274 | + identity = hidden_states |
| 275 | + orig_shape = hidden_states.shape |
| 276 | + |
| 277 | + # Down-project to the latent (7168 -> 3584); the router reads the full hidden state. |
| 278 | + x_latent = self.routed_expert_down_proj(hidden_states) |
| 279 | + y_routed, _, _ = self.routed_experts(x_latent, gate_inputs=hidden_states) |
| 280 | + |
| 281 | + # Post-expert RMSNorm |
| 282 | + if self.routed_expert_norm is not None: |
| 283 | + y_routed = self.routed_expert_norm(y_routed) |
| 284 | + |
| 285 | + # Up-project back to model dimension: 3584 -> 7168 |
| 286 | + y_routed = self.routed_expert_up_proj(y_routed, out_sharding=out_sharding) |
| 287 | + y_routed = y_routed.reshape(orig_shape) |
| 288 | + |
| 289 | + # Shared experts addition |
| 290 | + if self.shared_expert is not None: |
| 291 | + y_shared = self.shared_expert(identity, out_sharding=out_sharding) |
| 292 | + y_routed = y_routed + y_shared |
| 293 | + |
| 294 | + return y_routed.astype(self.dtype) |
0 commit comments