model.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. # SPDX-License-Identifier: Apache-2.0
  2. # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
  3. from collections.abc import Iterable
  4. from typing import ClassVar, Literal
  5. import os
  6. import torch
  7. from torch import nn
  8. from vllm.config import ParallelConfig, VllmConfig
  9. from vllm.distributed import (
  10. get_ep_group,
  11. get_pp_group,
  12. get_tensor_model_parallel_rank,
  13. get_tensor_model_parallel_world_size,
  14. tensor_model_parallel_all_gather,
  15. )
  16. from vllm.logger import init_logger
  17. from vllm.model_executor.layers.activation import SiluAndMul, SiluAndMulWithClamp
  18. from vllm.model_executor.layers.fused_moe import (
  19. FusedMoEFactory,
  20. GateLinear,
  21. fused_moe_make_expert_params_mapping,
  22. )
  23. from vllm.model_executor.layers.layernorm import RMSNorm
  24. from vllm.model_executor.layers.linear import (
  25. MergedColumnParallelLinear,
  26. RowParallelLinear,
  27. )
  28. from vllm.model_executor.layers.logits_processor import LogitsProcessor
  29. from vllm.model_executor.layers.mamba.mamba_utils import (
  30. MambaStateCopyFunc,
  31. MambaStateCopyFuncCalculator,
  32. MambaStateDtypeCalculator,
  33. MambaStateShapeCalculator,
  34. )
  35. from vllm.model_executor.layers.mhc import (
  36. MHCFusedPostPreOp,
  37. MHCPostOp,
  38. MHCPreOp,
  39. hc_contract,
  40. hc_expand,
  41. )
  42. from vllm.model_executor.layers.quantization import QuantizationConfig
  43. from vllm.model_executor.layers.quantization.utils.quant_utils import (
  44. GroupShape,
  45. scaled_dequantize,
  46. )
  47. from vllm.model_executor.layers.vocab_parallel_embedding import (
  48. ParallelLMHead,
  49. VocabParallelEmbedding,
  50. )
  51. from vllm.model_executor.model_loader.weight_utils import (
  52. default_weight_loader,
  53. maybe_remap_kv_scale_name,
  54. )
  55. from vllm.model_executor.models.deepseek_v2 import _get_moe_router_dtype
  56. from vllm.model_executor.models.glm4_1v import (
  57. Glm4vDummyInputsBuilder,
  58. Glm4vForConditionalGeneration,
  59. )
  60. from vllm.model_executor.models.interfaces import (
  61. EagleModelMixin,
  62. HasInnerState,
  63. IsHybrid,
  64. MixtureOfExperts,
  65. SupportsEagle3,
  66. SupportsPP,
  67. )
  68. from vllm.model_executor.models.utils import (
  69. AutoWeightsLoader,
  70. PPMissingLayer,
  71. init_vllm_registered_model,
  72. is_pp_missing_parameter,
  73. make_layers,
  74. maybe_prefix,
  75. sequence_parallel_chunk,
  76. )
  77. from vllm.models.common.ops.sequence_parallel import (
  78. sp_all_gather,
  79. sp_reduce_scatter,
  80. sp_shard,
  81. )
  82. # GB10: sequence parallelism over plain TP for prefill-sized batches
  83. # (VLLM_GLM_SP_TP=1). mHC, norms and residuals run on each rank's quarter of
  84. # the tokens; attention, the MoE and the dense MLPs all-gather their input and
  85. # reduce-scatter their partial output, the bytes of the all-reduce they
  86. # replace. Decode-sized batches keep plain TP: four small collectives per
  87. # layer cost more than the sharded work saves there (-10% decode measured).
  88. # GLM runs eagerly around CUDA graphs, so the choice is made per forward from
  89. # the batch size; graphs are captured below VLLM_GLM_SP_MIN_TOKENS, plain TP.
  90. _SP_TP = os.environ.get("VLLM_GLM_SP_TP") == "1"
  91. _SP_MIN_TOKENS = int(os.environ.get("VLLM_GLM_SP_MIN_TOKENS", "1024"))
  92. # Gather KDA attention inputs as per-token FP8 (half the bytes). The only
  93. # consumer is in_proj's FP8 GEMM, which would quantize the same rows the same way.
  94. _SP_FP8_GATHER = os.environ.get("VLLM_GLM_SP_FP8_GATHER") == "1"
  95. # Decode: each arx all-reduce asks L2 for the weights the next kernels read
  96. # (the MoE's gate and shared expert after attention, the next KDA in_proj
  97. # after the MLP) while it waits for the peers.
  98. _ARX_PREFETCH = os.environ.get("VLLM_GLM_ARX_PREFETCH") == "1"
  99. # SP prefill MoE layers: router, shared expert and moe_prefill's fc1/fc2 run
  100. # here, and one arxbig kernel writes shared + scaled routed sum straight into
  101. # the RDMA reduce-scatter while the network already sends finished rows. The
  102. # runner's separate scale and add passes and the NCCL reduce-scatter go away.
  103. _SP_MOE_FUSED = os.environ.get("VLLM_GLM_SP_MOE_FUSED") == "1"
  104. # Route each rank's own rows, then gather the MoE input already quantized:
  105. # NVFP4 for the routed experts and per-token FP8 for the shared expert, the
  106. # same values each would compute from the gathered bf16 rows.
  107. _SP_MOE_QUANT_GATHER = os.environ.get("VLLM_GLM_SP_MOE_QUANT_GATHER") == "1"
  108. _sp_moe_check = int(os.environ.get("VLLM_GLM_SP_MOE_CHECK", "0"))
  109. _sp_active = False
  110. # KDA spec verify from one checkpoint per request (recoverssm.py). The model
  111. # supplies the runner state that commits the accepted tokens after sampling.
  112. _RECOVERSSM = os.environ.get("VLLM_GLM5NEXT_RECOVERSSM") == "1"
  113. def _arxbig_rs():
  114. """arxbig's extension if it was set up with reduce-scatter buffers, else None."""
  115. from vllm.distributed import get_tp_group
  116. big = getattr(get_tp_group().device_communicator, "arxbig", None)
  117. return big.ext if big is not None and not big.disabled and big.rs else None
  118. def _arx_prefetch(tensors) -> None:
  119. from vllm.distributed.device_communicators import arx
  120. arx.set_prefetch(tensors)
  121. from vllm.multimodal import MULTIMODAL_REGISTRY
  122. from vllm.platforms import current_platform
  123. from vllm.sequence import IntermediateTensors
  124. from vllm.transformers_utils.configs.glm5_next import Glm5NextConfig
  125. from .attention import Glm5NextMLAAttention
  126. from .kda import Glm5NextLinearAttention
  127. from .multimodal import (
  128. Glm5NextMultiModalProcessor,
  129. Glm5NextProcessingInfo,
  130. Glm5NextVisionTransformer,
  131. )
  132. logger = init_logger(__name__)
  133. class Glm5NextMLP(nn.Module):
  134. def __init__(
  135. self,
  136. hidden_size: int,
  137. intermediate_size: int,
  138. hidden_act: str,
  139. quant_config: QuantizationConfig | None = None,
  140. reduce_results: bool = True,
  141. is_sequence_parallel=False,
  142. prefix: str = "",
  143. swiglu_limit: float | None = None,
  144. ) -> None:
  145. super().__init__()
  146. # If is_sequence_parallel, the input and output tensors are sharded
  147. # across the ranks within the tp_group. In this case the weights are
  148. # replicated and no collective ops are needed.
  149. # Otherwise we use standard TP with an allreduce at the end.
  150. self.gate_up_proj = MergedColumnParallelLinear(
  151. hidden_size,
  152. [intermediate_size] * 2,
  153. bias=False,
  154. quant_config=quant_config,
  155. disable_tp=is_sequence_parallel,
  156. prefix=f"{prefix}.gate_up_proj",
  157. )
  158. self.down_proj = RowParallelLinear(
  159. intermediate_size,
  160. hidden_size,
  161. bias=False,
  162. quant_config=quant_config,
  163. reduce_results=reduce_results,
  164. disable_tp=is_sequence_parallel,
  165. prefix=f"{prefix}.down_proj",
  166. )
  167. if hidden_act != "silu":
  168. raise ValueError(
  169. f"Unsupported activation: {hidden_act}. Only silu is supported for now."
  170. )
  171. self.swiglu_limit = swiglu_limit
  172. if self.swiglu_limit is not None:
  173. self.act_fn = SiluAndMulWithClamp(swiglu_limit=self.swiglu_limit)
  174. else:
  175. self.act_fn = SiluAndMul()
  176. def forward(self, x):
  177. gate_up, _ = self.gate_up_proj(x)
  178. x = self.act_fn(gate_up)
  179. x, _ = self.down_proj(x)
  180. return x
  181. class Glm5NextMoE(nn.Module):
  182. def __init__(
  183. self,
  184. config: Glm5NextConfig,
  185. parallel_config: ParallelConfig,
  186. quant_config: QuantizationConfig | None = None,
  187. prefix: str = "",
  188. apply_routed_scale_to_output: bool = False,
  189. ):
  190. super().__init__()
  191. self.tp_size = get_tensor_model_parallel_world_size()
  192. self.tp_rank = get_tensor_model_parallel_rank()
  193. self.routed_scaling_factor = config.routed_scaling_factor
  194. self.ep_group = get_ep_group().device_group
  195. self.ep_rank = get_ep_group().rank_in_group
  196. self.ep_size = self.ep_group.size()
  197. self.n_routed_experts: int = config.n_routed_experts
  198. self.n_shared_experts: int = config.n_shared_experts
  199. self.is_sequence_parallel = parallel_config.use_sequence_parallel_moe
  200. if config.hidden_act != "silu":
  201. raise ValueError(
  202. f"Unsupported activation: {config.hidden_act}. "
  203. "Only silu is supported for now."
  204. )
  205. self.router_dtype = _get_moe_router_dtype(config)
  206. self.gate = GateLinear(
  207. config.hidden_size,
  208. config.n_routed_experts,
  209. out_dtype=self.router_dtype,
  210. prefix=f"{prefix}.gate",
  211. )
  212. if config.topk_method == "noaux_tc":
  213. self.gate.e_score_correction_bias = nn.Parameter(
  214. torch.empty(config.n_routed_experts, dtype=torch.float32)
  215. )
  216. else:
  217. self.gate.e_score_correction_bias = None
  218. # Load balancing settings.
  219. eplb_config = parallel_config.eplb_config
  220. self.enable_eplb = parallel_config.enable_eplb
  221. self.n_redundant_experts = eplb_config.num_redundant_experts
  222. self.n_logical_experts = self.n_routed_experts
  223. self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts
  224. self.n_local_physical_experts = self.n_physical_experts // self.ep_size
  225. self.physical_expert_start = self.ep_rank * self.n_local_physical_experts
  226. self.physical_expert_end = (
  227. self.physical_expert_start + self.n_local_physical_experts
  228. )
  229. swiglu_limit = config.swiglu_limit
  230. if config.n_shared_experts is None:
  231. self.shared_experts = None
  232. else:
  233. intermediate_size = config.moe_intermediate_size * config.n_shared_experts
  234. self.shared_experts = Glm5NextMLP(
  235. hidden_size=config.hidden_size,
  236. intermediate_size=intermediate_size,
  237. hidden_act=config.hidden_act,
  238. quant_config=quant_config,
  239. is_sequence_parallel=self.is_sequence_parallel,
  240. reduce_results=False,
  241. prefix=f"{prefix}.shared_experts",
  242. swiglu_limit=swiglu_limit,
  243. )
  244. self.experts = FusedMoEFactory(
  245. shared_experts=self.shared_experts,
  246. gate=self.gate,
  247. num_experts=config.n_routed_experts,
  248. top_k=config.num_experts_per_token,
  249. hidden_size=config.hidden_size,
  250. intermediate_size=config.moe_intermediate_size,
  251. renormalize=config.moe_renormalize,
  252. quant_config=quant_config,
  253. use_grouped_topk=True,
  254. num_expert_group=config.n_group,
  255. topk_group=config.topk_group,
  256. prefix=f"{prefix}.experts",
  257. scoring_func=config.scoring_func,
  258. routed_scaling_factor=self.routed_scaling_factor,
  259. apply_routed_scale_to_output=apply_routed_scale_to_output,
  260. e_score_correction_bias=self.gate.e_score_correction_bias,
  261. enable_eplb=self.enable_eplb,
  262. num_redundant_experts=self.n_redundant_experts,
  263. is_sequence_parallel=self.is_sequence_parallel,
  264. n_shared_experts=None,
  265. router_logits_dtype=self.gate.out_dtype,
  266. swiglu_limit=swiglu_limit,
  267. )
  268. def forward(
  269. self,
  270. hidden_states: torch.Tensor,
  271. already_sequence_parallel: bool = False,
  272. ) -> torch.Tensor:
  273. num_tokens, hidden_dim = hidden_states.shape
  274. # Chunk the hidden states so they aren't replicated across TP ranks.
  275. # This avoids duplicate computation in self.experts.
  276. if self.is_sequence_parallel and not already_sequence_parallel:
  277. hidden_states = sequence_parallel_chunk(hidden_states)
  278. # MoERunner holds the gate (passed to FusedMoEFactory) and computes
  279. # the router logits itself, so nothing is precomputed here (matches
  280. # DeepseekV2MoE; `router_logits` is a placeholder).
  281. final_hidden_states = self.experts(
  282. hidden_states=hidden_states, router_logits=hidden_states
  283. )
  284. if self.is_sequence_parallel and not already_sequence_parallel:
  285. final_hidden_states = tensor_model_parallel_all_gather(
  286. final_hidden_states, 0
  287. )
  288. final_hidden_states = final_hidden_states[:num_tokens]
  289. return final_hidden_states.view(num_tokens, hidden_dim)
  290. class Glm5NextDecoderLayer(nn.Module):
  291. def __init__(
  292. self,
  293. vllm_config: VllmConfig,
  294. config: Glm5NextConfig,
  295. layer_idx: int,
  296. prefix: str = "",
  297. topk_indices_buffer: torch.Tensor | None = None,
  298. is_mtp_layer: bool = False,
  299. **kwargs,
  300. ) -> None:
  301. super().__init__()
  302. cache_config = vllm_config.cache_config
  303. quant_config = vllm_config.quant_config
  304. parallel_config = vllm_config.parallel_config
  305. self.hidden_size = config.hidden_size
  306. self.layer_idx = layer_idx
  307. self.is_moe = config.is_moe
  308. self.num_hidden_layers = config.num_hidden_layers
  309. self.rms_norm_eps = config.rms_norm_eps
  310. self.num_experts = config.n_routed_experts
  311. self.is_mtp_layer = is_mtp_layer
  312. self.mhc = config.mhc
  313. is_kda_layer = not is_mtp_layer and config.is_kda_layer(layer_idx)
  314. self.layer_kind = "kda" if is_kda_layer else "mla"
  315. self.is_sequence_parallel = parallel_config.use_sequence_parallel_moe
  316. if is_kda_layer:
  317. self.self_attn = Glm5NextLinearAttention(
  318. config=config,
  319. vllm_config=vllm_config,
  320. prefix=f"{prefix}.self_attn",
  321. )
  322. else:
  323. # MLA layers require the latent head dims, which are guaranteed set
  324. # on MLA configs; narrow away the `int | None`.
  325. assert config.v_head_dim is not None
  326. assert config.kv_lora_rank is not None
  327. self.self_attn = Glm5NextMLAAttention(
  328. vllm_config=vllm_config,
  329. config=config,
  330. hidden_size=self.hidden_size,
  331. num_heads=config.num_attention_heads,
  332. qk_nope_head_dim=config.qk_nope_head_dim,
  333. qk_rope_head_dim=config.qk_rope_head_dim,
  334. v_head_dim=config.v_head_dim,
  335. q_lora_rank=config.q_lora_rank,
  336. kv_lora_rank=config.kv_lora_rank,
  337. max_position_embeddings=config.max_position_embeddings,
  338. cache_config=cache_config,
  339. quant_config=None, # MLA projections are BF16 in checkpoint
  340. prefix=f"{prefix}.self_attn",
  341. topk_indices_buffer=topk_indices_buffer,
  342. skip_rope=config.mla_nope,
  343. )
  344. # MTP layers sit past the base model's hidden layers (layer_idx >=
  345. # num_hidden_layers), so they're outside mlp_layer_types; default them
  346. # to the last base layer's MLP type (sparse/MoE for these checkpoints).
  347. mlp_layer_types = config.mlp_layer_types
  348. mlp_type = (
  349. mlp_layer_types[layer_idx]
  350. if layer_idx < len(mlp_layer_types)
  351. else (mlp_layer_types[-1] if mlp_layer_types else "sparse")
  352. )
  353. if self.is_moe and self.num_experts is not None and mlp_type == "sparse":
  354. self.mlp = Glm5NextMoE(
  355. config=config,
  356. parallel_config=parallel_config,
  357. quant_config=quant_config,
  358. prefix=f"{prefix}.mlp",
  359. )
  360. else:
  361. self.mlp = Glm5NextMLP(
  362. hidden_size=self.hidden_size,
  363. intermediate_size=config.intermediate_size,
  364. hidden_act=config.hidden_act,
  365. quant_config=quant_config,
  366. is_sequence_parallel=self.is_sequence_parallel,
  367. prefix=f"{prefix}.mlp",
  368. swiglu_limit=config.swiglu_limit,
  369. )
  370. self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  371. # Cached for the hot forward path (isinstance per layer per step).
  372. self._mlp_is_moe = isinstance(self.mlp, Glm5NextMoE)
  373. self._in_proj = getattr(self.self_attn, "in_proj_qkvbfg_a", None)
  374. # In SP, the attention output projection leaves a partial sum; the
  375. # decoder-layer reduce_scatter after attention completes it (DSv4 pattern).
  376. # MTP layers use the non-mHC path which has no sp_reduce_scatter, so
  377. # their o_proj must still reduce normally.
  378. if self.is_sequence_parallel and not is_mtp_layer:
  379. self.self_attn.o_proj.reduce_results = False
  380. self.post_attention_layernorm = RMSNorm(
  381. config.hidden_size, eps=config.rms_norm_eps
  382. )
  383. if self.mhc and not is_mtp_layer:
  384. # mhc config
  385. self.mhc_num_residual_streams = config.mhc_num_residual_streams
  386. self.mhc_tau = config.mhc_tau
  387. self.hc_eps = config.hc_eps
  388. self.mhc_sinkhorn_iterations = config.mhc_sinkhorn_iterations
  389. self.mhc_post_mult_value = config.mhc_post_mult_value
  390. n = config.mhc_num_residual_streams
  391. d_model = n * self.hidden_size
  392. mix_hc = (2 + n) * n
  393. self.n = n
  394. # attn hc
  395. self.hc_attn_fn = nn.Parameter(
  396. torch.empty(mix_hc, d_model, dtype=torch.float32)
  397. )
  398. self.hc_attn_base = nn.Parameter(torch.empty(mix_hc, dtype=torch.float32))
  399. self.hc_attn_scale = nn.Parameter(torch.empty(3, dtype=torch.float32))
  400. # ffn hc
  401. self.hc_ffn_fn = nn.Parameter(
  402. torch.empty(mix_hc, d_model, dtype=torch.float32)
  403. )
  404. self.hc_ffn_base = nn.Parameter(torch.empty(mix_hc, dtype=torch.float32))
  405. self.hc_ffn_scale = nn.Parameter(torch.empty(3, dtype=torch.float32))
  406. self.mhc_pre_op = MHCPreOp()
  407. self.mhc_post_op = MHCPostOp()
  408. self.mhc_fused_post_pre_op = MHCFusedPostPreOp()
  409. if vllm_config.kernel_config.enable_jit_warmup:
  410. from vllm.model_executor.kernels.mhc.tilelang_kernels import (
  411. _HC_PRENORM_GEMM_TILELANG_KERNEL,
  412. _MHC_FUSED_TILELANG_KERNEL,
  413. _MHC_POST_TILELANG_KERNEL,
  414. _MHC_PRE_BIG_FUSE_TILELANG_KERNEL,
  415. )
  416. from vllm.utils.deep_gemm import is_deep_gemm_supported
  417. include_pre_gemm_splits = is_deep_gemm_supported()
  418. _MHC_PRE_BIG_FUSE_TILELANG_KERNEL.register_warmup(
  419. vllm_config,
  420. hidden_size=self.hidden_size,
  421. hc_mult=self.n,
  422. use_norm_weight=True,
  423. include_pre_gemm_splits=include_pre_gemm_splits,
  424. include_broadcast_splits=False,
  425. rms_eps=self.rms_norm_eps,
  426. hc_pre_eps=self.hc_eps,
  427. hc_sinkhorn_eps=self.hc_eps,
  428. hc_post_mult_value=self.mhc_post_mult_value,
  429. sinkhorn_repeat=self.mhc_sinkhorn_iterations,
  430. norm_eps=(
  431. self.input_layernorm.variance_epsilon,
  432. self.post_attention_layernorm.variance_epsilon,
  433. ),
  434. )
  435. if not include_pre_gemm_splits:
  436. _HC_PRENORM_GEMM_TILELANG_KERNEL.register_warmup(
  437. vllm_config,
  438. hidden_size=self.hidden_size,
  439. hc_mult=self.n,
  440. n_out=self.n * (2 + self.n),
  441. )
  442. _MHC_POST_TILELANG_KERNEL.register_warmup(
  443. hidden_size=self.hidden_size,
  444. hc_mult=self.n,
  445. )
  446. _MHC_FUSED_TILELANG_KERNEL.register_warmup(
  447. vllm_config,
  448. hidden_size=self.hidden_size,
  449. hc_mult=self.n,
  450. )
  451. def forward(
  452. self,
  453. positions: torch.Tensor,
  454. hidden_states: torch.Tensor,
  455. residual: torch.Tensor | None = None,
  456. post: torch.Tensor | None = None,
  457. comb: torch.Tensor | None = None,
  458. ) -> tuple[
  459. torch.Tensor,
  460. torch.Tensor | None,
  461. torch.Tensor | None,
  462. torch.Tensor | None,
  463. ]:
  464. # 70B or MTP layers: KDA + MoE without HC.
  465. if not self.mhc or self.is_mtp_layer:
  466. residual = hidden_states
  467. hidden_states = self.input_layernorm(hidden_states)
  468. attn_output = self.self_attn(
  469. hidden_states=hidden_states,
  470. positions=positions,
  471. )
  472. hidden_states, residual = self.post_attention_layernorm(
  473. attn_output, residual=residual
  474. )
  475. hidden_states = self.mlp(hidden_states)
  476. if self.is_mtp_layer:
  477. # Return the unsummed pair: the MTP caller feeds it straight
  478. # into shared_head's fused_add_rms_norm (one kernel instead of
  479. # a separate residual-add + norm). The sum itself is unchanged
  480. # (fp32-accumulated inside the fused kernel).
  481. return hidden_states, residual, None, None
  482. hidden_states = residual + hidden_states
  483. return hidden_states, residual, None, None
  484. # mHC start. `post`/`comb` carry the previous layer's deferred
  485. # hc_post inputs (its ffn-pre outputs); when present, fuse that
  486. # hc_post with this layer's attn hc_pre into one kernel (inter-layer
  487. # fusion). Layer 0 has no incoming state -> standalone hc_pre.
  488. x = hidden_states
  489. if post is None:
  490. if self.layer_idx == 0:
  491. x = hc_expand(x, self.n)
  492. residual = x
  493. post, comb, x = self.hc_pre(
  494. x,
  495. self.hc_attn_fn,
  496. self.hc_attn_scale,
  497. self.hc_attn_base,
  498. norm_weight=self.input_layernorm.weight.data,
  499. norm_eps=self.input_layernorm.variance_epsilon,
  500. )
  501. else:
  502. residual, post, comb, x = self.hc_fused_post_pre(
  503. x,
  504. residual,
  505. post,
  506. comb,
  507. self.hc_attn_fn,
  508. self.hc_attn_scale,
  509. self.hc_attn_base,
  510. norm_weight=self.input_layernorm.weight.data,
  511. norm_eps=self.input_layernorm.variance_epsilon,
  512. )
  513. # Attention needs the full token sequence; mHC above ran on the SP
  514. # shard. Gather for attention, scatter back afterward (DSv4 pattern).
  515. sp = self.is_sequence_parallel or _sp_active
  516. if _ARX_PREFETCH and not sp:
  517. _arx_prefetch(self._after_attn_weights())
  518. if (sp and _SP_FP8_GATHER and _sp_active and self._in_proj is not None
  519. and type(self._in_proj.quant_method).__name__ in ("Fp8DenseLinearMethod", "W4DenseLinearMethod")):
  520. x = self._fp8_gather(x, positions.shape[0])
  521. elif sp:
  522. x = sp_all_gather(x)[: positions.shape[0]]
  523. x = self.self_attn(
  524. hidden_states=x,
  525. positions=positions,
  526. )
  527. if sp:
  528. x = sp_reduce_scatter(x)
  529. # Fuse post-attn hc_post + pre-FFN hc_pre (+ RMSNorm) into one kernel.
  530. residual, post, comb, x = self.hc_fused_post_pre(
  531. x,
  532. residual,
  533. post,
  534. comb,
  535. self.hc_ffn_fn,
  536. self.hc_ffn_scale,
  537. self.hc_ffn_base,
  538. norm_weight=self.post_attention_layernorm.weight.data,
  539. norm_eps=self.post_attention_layernorm.variance_epsilon,
  540. )
  541. # Fully Connected
  542. if _ARX_PREFETCH and not sp:
  543. nxt = self.__dict__.get("_next_layer")
  544. _arx_prefetch(nxt._before_attn_weights() if nxt is not None else ())
  545. if _sp_active and not self.is_sequence_parallel:
  546. big = _arxbig_rs() if _SP_MOE_FUSED and self._mlp_is_moe else None
  547. if big is not None:
  548. x = self._sp_moe_fused(big, x, positions.shape[0])
  549. else:
  550. x = sp_all_gather(x)[: positions.shape[0]]
  551. x = self.mlp(x)
  552. x = sp_reduce_scatter(x)
  553. elif self._mlp_is_moe:
  554. x = self.mlp(x, already_sequence_parallel=self.is_sequence_parallel)
  555. else:
  556. x = self.mlp(x)
  557. # mHC end. The last mHC layer materializes its final hc_post (nothing
  558. # to fuse with) then contracts; every other layer defers its hc_post to
  559. # the next layer's fused pre, returning the state.
  560. if self.layer_idx == self.num_hidden_layers - 1:
  561. x = self.hc_post(x, residual, post, comb)
  562. x = hc_contract(x, self.n)
  563. return x, None, None, None
  564. return x, residual, post, comb
  565. def _sp_moe_fused(self, big, shard: torch.Tensor, n: int, quantized: bool = _SP_MOE_QUANT_GATHER) -> torch.Tensor:
  566. """SP MoE layer: gather, route, experts, and a reduce-scatter fed row by row."""
  567. global _sp_moe_check
  568. from vllm.model_executor.layers.fused_moe import megamoe_vllm
  569. moe = self.mlp
  570. runner = moe.experts
  571. routed = self.__dict__.get("_moe_prefill_layer")
  572. if routed is None:
  573. routed = next(m for m in moe.modules() if hasattr(m, "_moe_prefill_experts"))
  574. self.__dict__["_moe_prefill_layer"] = routed
  575. def route(x):
  576. logits = moe.gate(x)
  577. logits = logits[0] if isinstance(logits, tuple) else logits
  578. return runner.router.select_experts(
  579. hidden_states=x, router_logits=logits,
  580. topk_indices_dtype=runner._quant_method.topk_indices_dtype)
  581. H = shard.shape[1]
  582. # The quantized gather hands the shared experts an uninitialized
  583. # placeholder and their FP8 input through dense_fp8.prequant. A linear
  584. # left in BF16 would read the placeholder, so gather BF16 for those.
  585. shared_gate_up = getattr(moe.shared_experts, "gate_up_proj", None)
  586. if quantized and type(getattr(shared_gate_up, "quant_method", None)).__name__ not in (
  587. "Fp8DenseLinearMethod", "W4DenseLinearMethod"):
  588. quantized = False
  589. if quantized:
  590. from vllm import _custom_ops as ops
  591. from vllm.model_executor.model_loader import dense_fp8
  592. shard = shard.contiguous()
  593. rows = shard.shape[0]
  594. topk_weights, topk_ids = route(shard)
  595. topk_weights = sp_all_gather(topk_weights.float().contiguous())[:n]
  596. topk_ids = sp_all_gather(topk_ids.contiguous())[:n]
  597. x4 = shard if rows % 128 == 0 else torch.nn.functional.pad(shard, (0, 0, 0, -rows % 128))
  598. q4, s4 = ops.scaled_fp4_quant(x4, routed._moe_prefill_a1)
  599. q4 = sp_all_gather(q4)
  600. s4 = sp_all_gather(s4.view(torch.uint8).flatten())
  601. xq, xs = ops.scaled_fp8_quant(shard, use_per_token_if_dynamic=True)
  602. xq = sp_all_gather(xq.view(torch.uint8))[:n].view(torch.float8_e4m3fn)
  603. xs = sp_all_gather(xs)[:n]
  604. placeholder = shard.new_empty(n, H)
  605. dense_fp8.prequant(placeholder, xq, xs)
  606. shared = moe.shared_experts(placeholder)
  607. y, pos, y8s = megamoe_vllm.prefill_routed(
  608. routed, placeholder, topk_weights, topk_ids, megamoe_vllm._PREFILL_Y8, x4=(q4, s4, rows))
  609. else:
  610. x = sp_all_gather(shard)[:n]
  611. topk_weights, topk_ids = route(x)
  612. shared = moe.shared_experts(x)
  613. y, pos, y8s = megamoe_vllm.prefill_routed(routed, x, topk_weights, topk_ids, megamoe_vllm._PREFILL_Y8)
  614. w = (topk_weights.float() * runner.routed_scaling_factor).contiguous()
  615. n_pad = shard.shape[0] * get_tensor_model_parallel_world_size()
  616. seq = big.moe_finalize_rs(y, pos, w, shared.contiguous(), n, n_pad, y8s)
  617. out = big.rs_finish(seq, shard.shape[0], H)
  618. if _sp_moe_check > 0:
  619. left, _sp_moe_check = _sp_moe_check - 1, 0
  620. x = sp_all_gather(shard)[:n]
  621. ref = sp_reduce_scatter(self.mlp(x))
  622. rel = ((out.float() - ref.float()).norm() / ref.float().norm()).item()
  623. logger.warning("SP MoE fused check: %d tokens, rel diff vs runner %.5f", n, rel)
  624. if quantized:
  625. alt = self._sp_moe_fused(big, shard, n, False)
  626. rel = ((out.float() - alt.float()).norm() / alt.float().norm()).item()
  627. logger.warning("SP MoE fused check: rel diff vs the bf16 gather %.6f", rel)
  628. _sp_moe_check = left
  629. return out
  630. def _after_attn_weights(self) -> list:
  631. """Weights the MoE reads first: the router gate and the shared expert."""
  632. if not self._mlp_is_moe:
  633. return []
  634. shared = self.mlp.shared_experts
  635. out = [self.mlp.gate.weight]
  636. if shared is not None:
  637. out += [shared.gate_up_proj.weight, shared.down_proj.weight]
  638. return out
  639. def _before_attn_weights(self) -> list:
  640. """This layer's KDA in_proj (packed weight and block scales)."""
  641. if self._in_proj is None:
  642. return []
  643. return [self._in_proj.weight, getattr(self._in_proj, "weight_scale", None)]
  644. def _fp8_gather(self, x: torch.Tensor, n: int) -> torch.Tensor:
  645. """All-gather the SP shard as per-token FP8 for in_proj; returns its placeholder."""
  646. from vllm import _custom_ops as ops
  647. from vllm.model_executor.model_loader import dense_fp8
  648. xq, xs = ops.scaled_fp8_quant(x.contiguous(), use_per_token_if_dynamic=True)
  649. xq = sp_all_gather(xq.view(torch.uint8))[:n].view(torch.float8_e4m3fn)
  650. xs = sp_all_gather(xs)[:n]
  651. placeholder = x.new_empty(n, x.shape[1])
  652. dense_fp8.prequant(placeholder, xq, xs)
  653. return placeholder
  654. def hc_pre(
  655. self,
  656. x: torch.Tensor,
  657. hc_fn: torch.Tensor,
  658. hc_scale: torch.Tensor,
  659. hc_base: torch.Tensor,
  660. norm_weight: torch.Tensor | None = None,
  661. norm_eps: float = 0.0,
  662. ):
  663. post_mix, res_mix, layer_input = self.mhc_pre_op(
  664. residual=x,
  665. fn=hc_fn,
  666. hc_scale=hc_scale,
  667. hc_base=hc_base,
  668. rms_eps=self.rms_norm_eps,
  669. hc_pre_eps=self.hc_eps,
  670. hc_sinkhorn_eps=self.hc_eps,
  671. hc_post_mult_value=self.mhc_post_mult_value,
  672. sinkhorn_repeat=self.mhc_sinkhorn_iterations,
  673. norm_weight=norm_weight,
  674. norm_eps=norm_eps,
  675. )
  676. return post_mix, res_mix, layer_input
  677. def hc_post(
  678. self,
  679. x: torch.Tensor,
  680. residual: torch.Tensor,
  681. post: torch.Tensor,
  682. comb: torch.Tensor,
  683. ):
  684. return self.mhc_post_op(x, residual, post, comb)
  685. def hc_fused_post_pre(
  686. self,
  687. x: torch.Tensor,
  688. residual: torch.Tensor,
  689. post: torch.Tensor,
  690. comb: torch.Tensor,
  691. hc_fn: torch.Tensor,
  692. hc_scale: torch.Tensor,
  693. hc_base: torch.Tensor,
  694. norm_weight: torch.Tensor | None = None,
  695. norm_eps: float = 0.0,
  696. ):
  697. return self.mhc_fused_post_pre_op(
  698. x=x,
  699. residual=residual,
  700. post_layer_mix=post,
  701. comb_res_mix=comb,
  702. fn=hc_fn,
  703. hc_scale=hc_scale,
  704. hc_base=hc_base,
  705. rms_eps=self.rms_norm_eps,
  706. hc_pre_eps=self.hc_eps,
  707. hc_sinkhorn_eps=self.hc_eps,
  708. hc_post_mult_value=self.mhc_post_mult_value,
  709. sinkhorn_repeat=self.mhc_sinkhorn_iterations,
  710. n_splits=1,
  711. tile_n=1,
  712. norm_weight=norm_weight,
  713. norm_eps=norm_eps,
  714. )
  715. class Glm5NextModel(nn.Module, EagleModelMixin):
  716. def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
  717. super().__init__()
  718. config = vllm_config.model_config.hf_config
  719. self.config = config
  720. self.vocab_size = config.vocab_size
  721. self.device = current_platform.device_type
  722. self.is_v32 = config.index_topk is not None
  723. if self.is_v32:
  724. topk_tokens = config.index_topk
  725. assert topk_tokens is not None
  726. # Reserve room for the incomplete pool tail.
  727. kpool = config.index_kpool
  728. assert kpool is not None
  729. buffer_width = topk_tokens + (kpool - 1 if kpool > 1 else 0)
  730. # Sparse MLA tiles top-k in 128 columns; padded slots remain masked.
  731. sparse_topk_block_n = 128
  732. buffer_width = (
  733. (buffer_width + sparse_topk_block_n - 1) // sparse_topk_block_n
  734. ) * sparse_topk_block_n
  735. topk_indices_buffer = torch.empty(
  736. vllm_config.scheduler_config.max_num_batched_tokens,
  737. buffer_width,
  738. dtype=torch.int32,
  739. device=self.device,
  740. )
  741. else:
  742. # Full-MLA config (no kpool sparse indexer): no topk buffer.
  743. topk_indices_buffer = None
  744. if get_pp_group().is_first_rank:
  745. self.embed_tokens = VocabParallelEmbedding(
  746. config.vocab_size,
  747. config.hidden_size,
  748. prefix=f"{prefix}.embed_tokens",
  749. )
  750. else:
  751. self.embed_tokens = PPMissingLayer()
  752. def get_layer(prefix: str):
  753. layer_idx = int(prefix.rsplit(".", 1)[1])
  754. return Glm5NextDecoderLayer(
  755. vllm_config=vllm_config,
  756. config=config,
  757. layer_idx=layer_idx,
  758. prefix=prefix,
  759. topk_indices_buffer=topk_indices_buffer,
  760. )
  761. self.start_layer, self.end_layer, self.layers = make_layers(
  762. config.num_hidden_layers,
  763. get_layer,
  764. prefix=f"{prefix}.layers",
  765. )
  766. # The active slice is fixed after construction; cache it so forward
  767. # doesn't rebuild the slice (a fresh list) every step.
  768. self._active_layers = self.layers[self.start_layer : self.end_layer]
  769. for a, b in zip(self._active_layers, self._active_layers[1:]):
  770. a.__dict__["_next_layer"] = b # plain attribute: not a submodule
  771. if get_pp_group().is_last_rank:
  772. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  773. else:
  774. self.norm = PPMissingLayer()
  775. self.is_sequence_parallel = (
  776. vllm_config.parallel_config.use_sequence_parallel_moe
  777. )
  778. world_size = get_tensor_model_parallel_world_size()
  779. assert config.num_attention_heads % world_size == 0, (
  780. "num_attention_heads must be divisible by world_size"
  781. )
  782. def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
  783. return self.embed_tokens(input_ids)
  784. def _completed_layer_output(
  785. self,
  786. layer: Glm5NextDecoderLayer,
  787. hidden_states: torch.Tensor,
  788. residual: torch.Tensor | None,
  789. post: torch.Tensor | None,
  790. comb: torch.Tensor | None,
  791. ) -> torch.Tensor:
  792. """The tensor an aux consumer expects: this layer's completed output.
  793. `post is None` means there is nothing deferred -- a non-mHC layer, whose
  794. hidden_states already carries residual + mlp, or the final mHC layer,
  795. already hc_post'ed and contracted.
  796. """
  797. if post is None:
  798. return hidden_states
  799. recon = layer.hc_post(hidden_states, residual, post, comb)
  800. return hc_contract(recon, layer.n)
  801. def forward(
  802. self,
  803. input_ids: torch.Tensor | None,
  804. positions: torch.Tensor,
  805. intermediate_tensors: IntermediateTensors | None,
  806. inputs_embeds: torch.Tensor | None = None,
  807. **kwargs,
  808. ) -> torch.Tensor:
  809. if get_pp_group().is_first_rank:
  810. if inputs_embeds is not None:
  811. hidden_states = inputs_embeds
  812. else:
  813. hidden_states = self.embed_input_ids(input_ids)
  814. residual = None
  815. post = None
  816. comb = None
  817. else:
  818. assert intermediate_tensors is not None
  819. hidden_states = intermediate_tensors["hidden_states"]
  820. residual = intermediate_tensors["residual"]
  821. # post/comb (deferred mHC hc_post state) are not propagated across
  822. # PP ranks; the receiving rank's first mHC layer uses standalone pre.
  823. post = None
  824. comb = None
  825. full_num_tokens = positions.shape[0]
  826. global _sp_active
  827. sp_now = _SP_TP and not self.is_sequence_parallel and full_num_tokens >= _SP_MIN_TOKENS
  828. if sp_now != _sp_active:
  829. self._set_sp_reductions(sp_now)
  830. _sp_active = sp_now
  831. sp = self.is_sequence_parallel or sp_now
  832. if sp:
  833. hidden_states = sp_shard(hidden_states)
  834. aux_hidden_states: list[torch.Tensor] = []
  835. for idx, layer in enumerate(self._active_layers, start=self.start_layer):
  836. hidden_states, residual, post, comb = layer(
  837. positions, hidden_states, residual, post, comb
  838. )
  839. if idx + 1 in self.aux_hidden_state_layers:
  840. aux = self._completed_layer_output(
  841. layer, hidden_states, residual, post, comb
  842. )
  843. if sp:
  844. # clone: the gather may return a buffer later gathers reuse
  845. aux = sp_all_gather(aux)[:full_num_tokens].clone()
  846. aux_hidden_states.append(aux)
  847. if not get_pp_group().is_last_rank:
  848. # PP is gated off for GLM-5.3-Flash (no make_empty_intermediate_tensors),
  849. # so this branch is not exercised. post/comb are the deferred
  850. # hc_post state of this rank's last mHC layer; a future PP path
  851. # would need to propagate them, but for now they are dropped (the
  852. # receiving rank's first layer would fall back to standalone pre).
  853. return IntermediateTensors(
  854. {"hidden_states": hidden_states, "residual": residual}
  855. )
  856. if sp:
  857. hidden_states = sp_all_gather(hidden_states)[:full_num_tokens]
  858. hidden_states = self.norm(hidden_states)
  859. if self.aux_hidden_state_layers:
  860. # The runner unpacks a tuple whenever use_aux_hidden_state_outputs
  861. # is set, which is exactly when the layers were configured.
  862. return hidden_states, aux_hidden_states
  863. return hidden_states
  864. def _set_sp_reductions(self, sp: bool) -> None:
  865. """Under SP the decoder layer reduce-scatters attention and MLP
  866. outputs itself, so their own final all-reduces must be off."""
  867. for layer in self._active_layers:
  868. if getattr(layer, "is_mtp_layer", False) or layer.is_sequence_parallel:
  869. continue
  870. layer.self_attn.o_proj.reduce_results = not sp
  871. if layer._mlp_is_moe:
  872. for mod in layer.mlp.modules():
  873. cfg = getattr(mod, "moe_config", None)
  874. if cfg is not None and hasattr(cfg, "skip_final_all_reduce"):
  875. cfg.skip_final_all_reduce = sp
  876. else:
  877. layer.mlp.down_proj.reduce_results = not sp
  878. def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
  879. # TP=3: zero-pad heads / MoE intermediate to the served config's sizes.
  880. # Only tp3.yaml mounts tp3pad.py, so import it only for a padded config.
  881. if getattr(self.config, "tp_pad_orig", None):
  882. from .tp3pad import pad_weights
  883. weights = pad_weights(weights, self.config)
  884. stacked_params_mapping = [
  885. # (param_name, shard_name, shard_id)
  886. (".gate_up_proj", ".gate_proj", 0),
  887. (".gate_up_proj", ".up_proj", 1),
  888. # MLA: fuse q_a_proj and kv_a_proj_with_mqa
  889. (".fused_qkv_a_proj", ".q_a_proj", 0),
  890. (".fused_qkv_a_proj", ".kv_a_proj_with_mqa", 1),
  891. # Indexer: fuse wk and weights_proj
  892. (".wk_weights_proj", ".wk", 0),
  893. (".wk_weights_proj", ".weights_proj", 1),
  894. # KDA: merge q, k, v, b, f_a, g_a projections into one GEMM
  895. (".in_proj_qkvbfg_a", ".q_proj", 0),
  896. (".in_proj_qkvbfg_a", ".k_proj", 1),
  897. (".in_proj_qkvbfg_a", ".v_proj", 2),
  898. (".in_proj_qkvbfg_a", ".b_proj", 3),
  899. (".in_proj_qkvbfg_a", ".f_a_proj", 4),
  900. (".in_proj_qkvbfg_a", ".g_a_proj", 5),
  901. ]
  902. if self.config.is_moe:
  903. # Params for weights, fp8 weight scales, fp8 activation scales
  904. # (param_name, weight_name, expert_id, shard_id)
  905. # EPLB: the mapping enumerates physical experts, so it must cover
  906. # the redundant replicas or their slots are never loaded.
  907. num_redundant_experts = next(
  908. (
  909. layer.mlp.n_redundant_experts
  910. for layer in self.layers
  911. if isinstance(layer, Glm5NextDecoderLayer)
  912. and isinstance(layer.mlp, Glm5NextMoE)
  913. ),
  914. 0,
  915. )
  916. expert_params_mapping = fused_moe_make_expert_params_mapping(
  917. self,
  918. ckpt_gate_proj_name="gate_proj",
  919. ckpt_down_proj_name="down_proj",
  920. ckpt_up_proj_name="up_proj",
  921. num_experts=self.config.n_routed_experts,
  922. num_redundant_experts=num_redundant_experts,
  923. )
  924. else:
  925. expert_params_mapping = []
  926. params_dict = dict(self.named_parameters())
  927. loaded_params: set[str] = set()
  928. # GLM-5.3-Flash NoPE checkpoints omit the RoPE rows from
  929. # ``kv_a_proj_with_mqa``; pad them with zeros for the model shape.
  930. kv_a_pad_size = 0
  931. if self.config.mla_nope and self.config.qk_rope_head_dim > 0:
  932. kv_a_pad_size = self.config.qk_rope_head_dim
  933. _pending_wk_fp8: dict = {}
  934. for args in weights:
  935. name, loaded_weight = args[:2]
  936. kwargs: dict = args[2] if len(args) > 2 else {}
  937. if "rotary_emb.inv_freq" in name:
  938. continue
  939. spec_layer = get_spec_layer_idx_from_weight_name(self.config, name)
  940. if spec_layer is not None:
  941. continue # skip spec decode layers for main model
  942. if "rotary_emb.cos_cached" in name or "rotary_emb.sin_cached" in name:
  943. # Models trained using ColossalAI may include these tensors in
  944. # the checkpoint. Skip them.
  945. continue
  946. # Handle FP8 indexer WK: dequantize to BF16 for fusion with
  947. # weights_proj into wk_weights_proj.
  948. if _try_load_fp8_indexer_wk(
  949. name,
  950. loaded_weight,
  951. _pending_wk_fp8,
  952. params_dict,
  953. loaded_params,
  954. ):
  955. continue
  956. # FP8 checkpoint: dequantize BF16-kept MLA projections
  957. # (q_a_proj / kv_a_proj_with_mqa / o_proj) to BF16.
  958. if _try_load_fp8_attn_proj(
  959. name,
  960. loaded_weight,
  961. _pending_wk_fp8,
  962. params_dict,
  963. loaded_params,
  964. kv_a_pad_size,
  965. ):
  966. continue
  967. # Pad kv_a_proj_with_mqa for NoPE models
  968. if kv_a_pad_size > 0 and ".kv_a_proj_with_mqa." in name:
  969. pad = torch.zeros(
  970. kv_a_pad_size,
  971. *loaded_weight.shape[1:],
  972. dtype=loaded_weight.dtype,
  973. device=loaded_weight.device,
  974. )
  975. loaded_weight = torch.cat([loaded_weight, pad], dim=0)
  976. for param_name, weight_name, shard_id in stacked_params_mapping:
  977. if weight_name not in name:
  978. continue
  979. # We have mlp.experts[0].gate_proj in the checkpoint.
  980. # Since we handle the experts below in expert_params_mapping,
  981. # we need to skip here BEFORE we update the name, otherwise
  982. # name will be updated to mlp.experts[0].gate_up_proj, which
  983. # will then be updated below in expert_params_mapping
  984. # for mlp.experts[0].gate_gate_up_proj, which breaks load.
  985. if ("mlp.experts." in name) and name not in params_dict:
  986. continue
  987. name_mapped = name.replace(weight_name, param_name)
  988. # QKV fusion: skip if fused module doesn't exist in model
  989. if param_name == ".fused_qkv_a_proj" and name_mapped not in params_dict:
  990. continue
  991. name = name_mapped
  992. # Skip loading extra bias for GPTQ models.
  993. if name.endswith(".bias") and name not in params_dict:
  994. continue
  995. if is_pp_missing_parameter(name, self):
  996. continue
  997. param = params_dict[name]
  998. weight_loader = param.weight_loader
  999. weight_loader(param, loaded_weight, shard_id)
  1000. break
  1001. else:
  1002. is_expert_weight = False
  1003. for (
  1004. param_name,
  1005. weight_name,
  1006. expert_id,
  1007. expert_shard_id,
  1008. ) in expert_params_mapping:
  1009. if weight_name not in name:
  1010. continue
  1011. # A checkpoint expert may map to several physical replicas
  1012. # under EPLB; keep `name` intact and try the next entry
  1013. # when this physical expert is not local to the rank.
  1014. is_expert_weight = True
  1015. name_mapped = name.replace(weight_name, param_name)
  1016. if is_pp_missing_parameter(name_mapped, self):
  1017. continue
  1018. param = params_dict[name_mapped]
  1019. weight_loader = param.weight_loader
  1020. success = weight_loader(
  1021. param,
  1022. loaded_weight,
  1023. name_mapped,
  1024. expert_id=expert_id,
  1025. shard_id=expert_shard_id,
  1026. return_success=True,
  1027. )
  1028. if success:
  1029. name = name_mapped
  1030. break
  1031. else:
  1032. if is_expert_weight:
  1033. continue
  1034. # Skip loading extra bias for GPTQ models.
  1035. if (
  1036. name.endswith(".bias")
  1037. and name not in params_dict
  1038. and not self.config.is_linear_attn
  1039. ): # noqa: E501
  1040. continue
  1041. # Remapping the name of FP8 kv-scale.
  1042. remapped_name = maybe_remap_kv_scale_name(name, params_dict)
  1043. if remapped_name is None:
  1044. continue
  1045. name = remapped_name
  1046. if is_pp_missing_parameter(name, self):
  1047. continue
  1048. param = params_dict[name]
  1049. weight_loader = getattr(
  1050. param, "weight_loader", default_weight_loader
  1051. )
  1052. weight_loader(param, loaded_weight, **kwargs)
  1053. loaded_params.add(name)
  1054. return loaded_params
  1055. class Glm5NextForCausalLM(
  1056. nn.Module, HasInnerState, SupportsPP, SupportsEagle3, MixtureOfExperts, IsHybrid
  1057. ):
  1058. def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
  1059. super().__init__()
  1060. self.model_config = vllm_config.model_config
  1061. self.vllm_config = vllm_config
  1062. self.config = self.model_config.hf_config
  1063. quant_config = vllm_config.quant_config
  1064. self.quant_config = quant_config
  1065. self.model = Glm5NextModel(
  1066. vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
  1067. )
  1068. if get_pp_group().is_last_rank:
  1069. self.lm_head = ParallelLMHead(
  1070. self.config.vocab_size,
  1071. self.config.hidden_size,
  1072. quant_config=quant_config,
  1073. prefix=maybe_prefix(prefix, "lm_head"),
  1074. )
  1075. else:
  1076. self.lm_head = PPMissingLayer()
  1077. self.logits_processor = LogitsProcessor(
  1078. self.config.vocab_size, scale=self.config.logit_scale
  1079. )
  1080. def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
  1081. return self.model.embed_input_ids(input_ids)
  1082. if _RECOVERSSM:
  1083. @staticmethod
  1084. def get_model_state_cls():
  1085. from .recoverssm import model_state_cls
  1086. return model_state_cls()
  1087. def forward(
  1088. self,
  1089. input_ids: torch.Tensor | None,
  1090. positions: torch.Tensor,
  1091. intermediate_tensors: IntermediateTensors | None = None,
  1092. inputs_embeds: torch.Tensor | None = None,
  1093. **kwargs,
  1094. ) -> torch.Tensor | IntermediateTensors:
  1095. hidden_states = self.model(
  1096. input_ids, positions, intermediate_tensors, inputs_embeds, **kwargs
  1097. )
  1098. return hidden_states
  1099. @classmethod
  1100. def get_mamba_state_dtype_from_config(
  1101. cls,
  1102. vllm_config: "VllmConfig",
  1103. ) -> tuple[torch.dtype, torch.dtype]:
  1104. return MambaStateDtypeCalculator.kda_state_dtype(
  1105. vllm_config.model_config.dtype, vllm_config.cache_config.mamba_cache_dtype
  1106. )
  1107. @classmethod
  1108. def get_mamba_state_shape_from_config(
  1109. cls, vllm_config: "VllmConfig"
  1110. ) -> tuple[tuple[int, int], tuple[int, int, int]]:
  1111. parallel_config = vllm_config.parallel_config
  1112. hf_config = vllm_config.model_config.hf_config
  1113. tp_size = parallel_config.tensor_parallel_size
  1114. num_spec = (
  1115. vllm_config.speculative_config.num_speculative_tokens
  1116. if vllm_config.speculative_config
  1117. else 0
  1118. )
  1119. return MambaStateShapeCalculator.kda_state_shape(
  1120. tp_size,
  1121. hf_config.linear_num_heads,
  1122. hf_config.linear_head_dim,
  1123. conv_kernel_size=hf_config.linear_conv_kernel_dim,
  1124. num_spec=num_spec,
  1125. )
  1126. @classmethod
  1127. def get_mamba_state_copy_func(
  1128. cls,
  1129. ) -> tuple[
  1130. MambaStateCopyFunc, MambaStateCopyFunc, MambaStateCopyFunc, MambaStateCopyFunc
  1131. ]:
  1132. return MambaStateCopyFuncCalculator.kda_state_copy_func()
  1133. def compute_logits(
  1134. self,
  1135. hidden_states: torch.Tensor,
  1136. ) -> torch.Tensor | None:
  1137. logits = self.logits_processor(self.lm_head, hidden_states)
  1138. return logits
  1139. def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
  1140. loader = AutoWeightsLoader(self)
  1141. return loader.load_weights(weights)
  1142. @MULTIMODAL_REGISTRY.register_processor(
  1143. Glm5NextMultiModalProcessor,
  1144. info=Glm5NextProcessingInfo,
  1145. dummy_inputs=Glm4vDummyInputsBuilder,
  1146. )
  1147. class Glm5NextForConditionalGeneration(
  1148. Glm4vForConditionalGeneration, HasInnerState, IsHybrid, MixtureOfExperts,
  1149. SupportsEagle3
  1150. ):
  1151. # The text model (KDA + dense-MLA + MoE) is a hybrid mamba model. The
  1152. # multimodal wrapper must declare the same interfaces so vLLM treats it as
  1153. # hybrid (auto-aligns mamba/attention block sizes, sizes the mamba state
  1154. # cache); the mamba-state classmethods delegate to the text model.
  1155. has_inner_state: ClassVar[Literal[True]] = True
  1156. is_hybrid: ClassVar[Literal[True]] = True
  1157. # GLM-5.3-Flash stores the dense-MLP gate/up as separate tensors (like
  1158. # ``Glm4vMoeForConditionalGeneration``, ``glm4_moe`` and ``deepseek_v2``),
  1159. # so the fused ``gate_up_proj`` must expand to its real shard names for
  1160. # per-layer quant-scheme resolution. The identity ``gate_up_proj`` entry
  1161. # inherited from ``Glm4vForConditionalGeneration`` (pre-fused gate_up_proj)
  1162. # would otherwise route the module to ``global_quant_config`` and mismatch
  1163. # at load for mixed-precision Quark checkpoints.
  1164. packed_modules_mapping = {
  1165. "gate_up_proj": ["gate_proj", "up_proj"],
  1166. }
  1167. # NOTE: weight-prefix mapping is inherited from Glm4vForConditionalGeneration
  1168. # (``model.visual.`` -> ``visual.``, ``model.language_model.`` ->
  1169. # ``language_model.model.``, ``lm_head.`` -> ``language_model.lm_head.``),
  1170. # matching the GLM-OCR / GLM-4V serialization convention. If the real
  1171. # checkpoint's safetensors keys differ (e.g. ``language_model.model.`` with
  1172. # no outer ``model.``), override ``hf_to_vllm_mapper`` accordingly.
  1173. @classmethod
  1174. def get_mamba_state_dtype_from_config(cls, vllm_config: VllmConfig):
  1175. from .model import Glm5NextForCausalLM
  1176. return Glm5NextForCausalLM.get_mamba_state_dtype_from_config(vllm_config)
  1177. @classmethod
  1178. def get_mamba_state_shape_from_config(cls, vllm_config: VllmConfig):
  1179. from .model import Glm5NextForCausalLM
  1180. return Glm5NextForCausalLM.get_mamba_state_shape_from_config(vllm_config)
  1181. @classmethod
  1182. def get_mamba_state_copy_func(cls):
  1183. from .model import Glm5NextForCausalLM
  1184. return Glm5NextForCausalLM.get_mamba_state_copy_func()
  1185. if _RECOVERSSM:
  1186. @staticmethod
  1187. def get_model_state_cls():
  1188. from .recoverssm import model_state_cls
  1189. return model_state_cls()
  1190. def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
  1191. super(Glm4vForConditionalGeneration, self).__init__()
  1192. config = vllm_config.model_config.hf_config
  1193. multimodal_config = vllm_config.model_config.multimodal_config
  1194. assert multimodal_config is not None
  1195. self.config = config
  1196. self.model_config = vllm_config.model_config
  1197. self.multimodal_config = multimodal_config
  1198. self.use_data_parallel = multimodal_config.mm_encoder_tp_mode == "data"
  1199. self.is_multimodal_pruning_enabled = (
  1200. multimodal_config.is_multimodal_pruning_enabled()
  1201. )
  1202. with self._mark_tower_model(vllm_config, {"image", "video"}):
  1203. self.visual = Glm5NextVisionTransformer(
  1204. config.text_config,
  1205. config.vision_config,
  1206. # Read eps from the VISION sub-config, not the top-level
  1207. # `config.rms_norm_eps`: Glm5NextConfig.__getattribute__ mirrors
  1208. # the latter onto text_config (1e-5), silently ignoring the
  1209. # vision tower's own (1e-6) rms_norm_eps.
  1210. norm_eps=config.vision_config.rms_norm_eps,
  1211. # Vision tower ships BF16 weights in this fp8 checkpoint (no
  1212. # weight_scale_inv for visual.*), so it must NOT inherit the
  1213. # global fp8 quant_config -- doing so incorrectly quantizes
  1214. # the tower
  1215. # and yields NaN image features. Mirrors the MLA/KDA proj
  1216. # pattern (quant_config=None for BF16 submodules).
  1217. quant_config=None,
  1218. prefix=maybe_prefix(prefix, "visual"),
  1219. )
  1220. with self._mark_language_model(vllm_config):
  1221. self.language_model = init_vllm_registered_model(
  1222. vllm_config=vllm_config,
  1223. hf_config=config.text_config,
  1224. prefix=maybe_prefix(prefix, "language_model"),
  1225. architectures=["Glm5NextForCausalLM"],
  1226. )
  1227. self.set_moe_parameters()
  1228. # Glm5NextForCausalLM does not implement make_empty_intermediate_tensors,
  1229. # so pipeline parallelism is gated off (consistent with the text-only
  1230. # model) and we intentionally do not alias it here.
  1231. def set_moe_parameters(self) -> None:
  1232. self.moe_mlp_layers = [
  1233. layer.mlp
  1234. for layer in self.language_model.model.layers
  1235. if isinstance(layer, Glm5NextDecoderLayer)
  1236. and isinstance(layer.mlp, Glm5NextMoE)
  1237. ]
  1238. self.moe_layers = [moe.experts for moe in self.moe_mlp_layers]
  1239. self.num_moe_layers = len(self.moe_layers)
  1240. if not self.num_moe_layers:
  1241. return
  1242. example_moe = self.moe_mlp_layers[0]
  1243. self.num_expert_groups = self.config.text_config.n_group
  1244. self.num_logical_experts = example_moe.n_logical_experts
  1245. self.num_physical_experts = example_moe.n_physical_experts
  1246. self.num_local_physical_experts = example_moe.n_local_physical_experts
  1247. self.num_routed_experts = example_moe.n_routed_experts
  1248. self.num_shared_experts = example_moe.n_shared_experts
  1249. self.num_redundant_experts = example_moe.n_redundant_experts
  1250. def update_physical_experts_metadata(
  1251. self,
  1252. num_physical_experts: int,
  1253. num_local_physical_experts: int,
  1254. ) -> None:
  1255. if not self.num_moe_layers:
  1256. return
  1257. assert self.num_local_physical_experts == num_local_physical_experts
  1258. self.num_physical_experts = num_physical_experts
  1259. self.num_redundant_experts = num_physical_experts - self.num_logical_experts
  1260. for moe in self.moe_mlp_layers:
  1261. moe.n_physical_experts = num_physical_experts
  1262. moe.n_redundant_experts = self.num_redundant_experts
  1263. moe.experts.update_expert_map()
  1264. def get_encoder_cudagraph_config(self):
  1265. # This vision tower does not produce the absolute position embedding
  1266. # buffer used by GLM4V.
  1267. config = super().get_encoder_cudagraph_config()
  1268. config.buffer_keys = [k for k in config.buffer_keys if k != "pos_embeds"]
  1269. return config
  1270. def get_spec_layer_idx_from_weight_name(
  1271. config: Glm5NextConfig, weight_name: str
  1272. ) -> int | None:
  1273. if hasattr(config, "num_nextn_predict_layers") and (
  1274. config.num_nextn_predict_layers > 0
  1275. ):
  1276. layer_idx = config.num_hidden_layers
  1277. for i in range(config.num_nextn_predict_layers):
  1278. if weight_name.startswith(
  1279. f"model.layers.{layer_idx + i}."
  1280. ) or weight_name.startswith(f"layers.{layer_idx + i}."):
  1281. return layer_idx + i
  1282. return None
  1283. def _try_load_fp8_indexer_wk(name, tensor, buf, params_dict, loaded_params):
  1284. if "indexer.wk." not in name or "wk_weights" in name:
  1285. return False
  1286. is_weight = name.endswith(".weight") and tensor.dtype == torch.float8_e4m3fn
  1287. is_scale = "weight_scale_inv" in name
  1288. if not is_weight and not is_scale:
  1289. return False
  1290. layer_prefix = name.rsplit(".wk.", 1)[0]
  1291. entry = buf.setdefault(layer_prefix, {})
  1292. entry["weight" if is_weight else "scale"] = tensor
  1293. if "weight" not in entry or "scale" not in entry:
  1294. return True
  1295. weight_fp8, scale_inv = entry["weight"], entry["scale"]
  1296. del buf[layer_prefix]
  1297. block_size = weight_fp8.shape[1] // scale_inv.shape[1]
  1298. weight_bf16 = scaled_dequantize(
  1299. weight_fp8,
  1300. scale_inv,
  1301. group_shape=GroupShape(block_size, block_size),
  1302. out_dtype=torch.bfloat16,
  1303. )
  1304. fused_name = f"{layer_prefix}.wk_weights_proj.weight"
  1305. param = params_dict[fused_name]
  1306. param.weight_loader(param, weight_bf16, 0)
  1307. loaded_params.add(fused_name)
  1308. return True
  1309. def _dequant_fp8_block(
  1310. weight_fp8: torch.Tensor,
  1311. scale_inv: torch.Tensor,
  1312. block_size: int = 128,
  1313. ) -> torch.Tensor:
  1314. """Dequantize a block-FP8 (e4m3) weight with per-block scale to BF16.
  1315. Unlike ``scaled_dequantize`` this tolerates a non-divisible (partial last
  1316. block) shape by zero-padding to a multiple of ``block_size`` before the
  1317. scale broadcast and trimming back afterwards (e.g. kv_a_proj_with_mqa is
  1318. 576 rows = 4*128 + 64).
  1319. """
  1320. out_dim, in_dim = weight_fp8.shape
  1321. pad_out = (-out_dim) % block_size
  1322. pad_in = (-in_dim) % block_size
  1323. w = weight_fp8
  1324. if pad_out or pad_in:
  1325. w = torch.nn.functional.pad(w, (0, pad_in, 0, pad_out))
  1326. # scale_inv is (ceil(out/block), ceil(in/block)); broadcast to (out, in).
  1327. s = scale_inv.to(torch.float32)
  1328. s_full = s.repeat_interleave(block_size, dim=0).repeat_interleave(block_size, dim=1)
  1329. out = (w.to(torch.float32) * s_full).to(torch.bfloat16)
  1330. return out[:out_dim, :in_dim].contiguous()
  1331. # FP8 checkpoint projections that the MODEL keeps in BF16, so the block-FP8
  1332. # (weight + weight_scale_inv) must be dequantized to BF16 on load.
  1333. # Maps checkpoint proj-suffix -> (buffer key, model target base, fused shard id
  1334. # or None for a direct projection, whether NoPE rope-padding applies).
  1335. _FP8_ATTN_PROJS = {
  1336. ".q_a_proj.": ("q_a", "fused_qkv_a_proj", 0, False),
  1337. ".kv_a_proj_with_mqa.": ("kv_a", "fused_qkv_a_proj", 1, True),
  1338. ".q_b_proj.": ("q_b", "q_b_proj", None, False),
  1339. ".o_proj.": ("o_proj", "o_proj", None, False),
  1340. }
  1341. def _try_load_fp8_attn_proj(
  1342. name,
  1343. tensor,
  1344. buf,
  1345. params_dict,
  1346. loaded_params,
  1347. kv_a_pad_size: int,
  1348. ) -> bool:
  1349. """Dequantize FP8 q_a_proj / kv_a_proj_with_mqa / o_proj to BF16 on load.
  1350. The FP8 checkpoint stores these as block-FP8 (weight + weight_scale_inv),
  1351. but the model holds them in BF16 (``fused_qkv_a_proj`` is always BF16 via
  1352. DeepSeekV2FusedQkvAProjLinear; ``o_proj`` is excluded by
  1353. modules_to_not_convert). When the model target is BF16 (no
  1354. ``weight_scale_inv`` param) we dequantize; otherwise we return False so the
  1355. normal stacked/direct path loads the FP8 tensor as-is.
  1356. """
  1357. matched = None
  1358. for suffix, info in _FP8_ATTN_PROJS.items():
  1359. if suffix in name:
  1360. matched = (suffix, info)
  1361. break
  1362. if matched is None:
  1363. return False
  1364. suffix, (key, target_base, shard_id, is_kva) = matched
  1365. is_weight = name.endswith(".weight") and tensor.dtype == torch.float8_e4m3fn
  1366. # Need to accept both the DeepSeek-native ``weight_scale_inv`` and the Quark
  1367. # ``weight_scale`` names before feeding the shared block dequant below.
  1368. is_scale = "weight_scale_inv" in name or name.endswith(".weight_scale")
  1369. if not is_weight and not is_scale:
  1370. return False
  1371. layer_prefix = name.rsplit(suffix, 1)[0]
  1372. target_w = f"{layer_prefix}.{target_base}.weight"
  1373. target_s = f"{layer_prefix}.{target_base}.weight_scale_inv"
  1374. # If the model actually kept this projection in FP8, let the normal path
  1375. # handle it (it has a weight_scale_inv param).
  1376. if target_s in params_dict:
  1377. return False
  1378. entry = buf.setdefault(layer_prefix, {}).setdefault(key, {})
  1379. entry["weight" if is_weight else "scale"] = tensor
  1380. if "weight" not in entry or "scale" not in entry:
  1381. return True
  1382. weight_fp8, scale_inv = entry["weight"], entry["scale"]
  1383. buf[layer_prefix].pop(key, None)
  1384. block_size = weight_fp8.shape[1] // scale_inv.shape[1]
  1385. weight_bf16 = _dequant_fp8_block(weight_fp8, scale_inv, block_size)
  1386. # NoPE: pad kv_a rope portion (kv_lora_rank -> kv_lora_rank + qk_rope_head_dim).
  1387. if is_kva and kv_a_pad_size > 0:
  1388. pad = torch.zeros(
  1389. kv_a_pad_size,
  1390. weight_bf16.shape[1],
  1391. dtype=weight_bf16.dtype,
  1392. device=weight_bf16.device,
  1393. )
  1394. weight_bf16 = torch.cat([weight_bf16, pad], dim=0)
  1395. param = params_dict[target_w]
  1396. if shard_id is None:
  1397. param.weight_loader(param, weight_bf16)
  1398. else:
  1399. param.weight_loader(param, weight_bf16, shard_id)
  1400. loaded_params.add(target_w)
  1401. return True