Skip to content

vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors_moe.compressed_tensors_moe_wna16

Classes:

CompressedTensorsWNA16MoEMethod

Bases: CompressedTensorsMoEMethod

Methods:

  • get_weight_shape –

    Return N-first buffer shape for the given weight/scale/zp tensor.

Source code in vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors_moe/compressed_tensors_moe_wna16.py
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
class CompressedTensorsWNA16MoEMethod(CompressedTensorsMoEMethod):
    def __init__(
        self,
        weight_quant: QuantizationArgs,
        input_quant: QuantizationArgs | None,
        moe: FusedMoEConfig,
        layer_name: str | None = None,
    ):
        super().__init__(moe)
        self.weight_quant = weight_quant
        self.input_quant = input_quant
        # Extract properties from weight_quant
        self.symmetric = weight_quant.symmetric
        self.num_bits = weight_quant.num_bits
        self.packed_factor = Fraction(32, weight_quant.num_bits)
        self.strategy = weight_quant.strategy
        # Per-channel strategies leave group_size unset; -1 is the in-tree
        # encoding for that, as in CompressedTensorsWNA16 and siblings.
        self.group_size = (
            -1 if weight_quant.group_size is None else weight_quant.group_size
        )

        # Extract quant_type and create weight key for oracle selection
        self.quant_type = (
            WNA16_SUPPORTED_TYPES_MAP[self.num_bits]
            if self.symmetric
            else WNA16_ZP_SUPPORTED_TYPES_MAP[self.num_bits]
        )

        if self.num_bits == 4:
            if self.group_size == 32:
                scale = kInt4Static32GroupScale
            else:
                scale = kInt4StaticGroupScale
        elif self.num_bits == 8:
            scale = kInt8StaticGroupScale
        else:
            scale = ScaleDesc(
                dtype=torch.float16,
                static=True,
                group_shape=(
                    GroupShape.PER_CHANNEL
                    if self.group_size == -1
                    else GroupShape(row=1, col=self.group_size)
                ),
            )

        weight_key = QuantKey(self.quant_type, scale, symmetric=self.symmetric)

        # Select WNA16 MoE backend via oracle.
        self.wna16_backend, self.experts_cls = select_wna16_moe_backend(
            config=self.moe,
            weight_key=weight_key,
            quant_config=self.weight_quant,
            may_have_zp=not self.symmetric,
            may_have_bias=False,
            allow_tile_padding=True,
        )

        self.is_marlin = self.wna16_backend in [
            WNA16MoEBackend.MARLIN,
            WNA16MoEBackend.BATCHED_MARLIN,
        ]
        # CT checkpoints always load in N-first format [E, N, K_packed].
        # Backend-specific transposition is handled in
        # convert_to_wna16_moe_kernel_format.
        self.is_transposed = False

        if self.is_marlin:
            assert check_moe_marlin_supports_config(
                self.moe, self.group_size, allow_tile_padding=True
            )
            self.input_dtype = get_marlin_input_dtype(layer_name)
        else:
            # channelwise is not supported by this kernel
            assert weight_quant.strategy == "group"

            # Non-Marlin WNA16 always uses bf16/fp16 inputs
            self.input_dtype = torch.bfloat16

    def _packed_dim(self, dim: int) -> int:
        return math.ceil(dim * self.num_bits / 32)

    def get_weight_shape(
        self,
        weight_name: str,
        num_experts: int,
        hidden_size: int,
        intermediate_size_per_partition: int,
        num_groups_w2: int | None = None,
        num_groups_w13: int | None = None,
    ) -> tuple[int, int, int]:
        """Return N-first buffer shape for the given weight/scale/zp tensor.

        All CT MoE weights are allocated in the checkpoint's native N-first
        layout ``[E, N, K_packed]``. Backend-specific transposition (e.g. to
        Marlin's K-first layout) is deferred to
        ``convert_to_wna16_moe_kernel_format``.
        """
        w13_num_shards = 2 if self.moe.is_act_and_mul else 1
        w13_n = w13_num_shards * intermediate_size_per_partition
        pf = self.packed_factor
        shape_map = {
            "w13_weight": (num_experts, w13_n, hidden_size // pf),
            "w13_scale": (num_experts, w13_n, num_groups_w13),
            "w13_zp": (num_experts, w13_n // pf, num_groups_w13),
            "w2_weight": (
                num_experts,
                hidden_size,
                intermediate_size_per_partition // pf,
            ),
            "w2_scale": (num_experts, hidden_size, num_groups_w2),
            "w2_zp": (num_experts, hidden_size // pf, num_groups_w2),
        }
        shape = shape_map[weight_name]
        assert isinstance(shape, tuple) and all(isinstance(d, int) for d in shape)
        return shape  # type: ignore[return-value]

    def create_weights(
        self,
        layer: torch.nn.Module,
        num_experts: int,
        hidden_size: int,
        intermediate_size_per_partition: int,
        params_dtype: torch.dtype,
        **extra_weight_attrs,
    ):
        extra_weight_attrs.update(
            {"is_transposed": False, "quant_method": self.strategy}
        )

        w13_weight = torch.nn.Parameter(
            torch.empty(
                *self.get_weight_shape(
                    "w13_weight",
                    num_experts,
                    hidden_size,
                    intermediate_size_per_partition,
                ),
                dtype=torch.int32,
            ),
            requires_grad=False,
        )
        layer.register_parameter("w13_weight_packed", w13_weight)
        set_weight_attrs(w13_weight, extra_weight_attrs)

        w2_weight = torch.nn.Parameter(
            torch.empty(
                *self.get_weight_shape(
                    "w2_weight",
                    num_experts,
                    hidden_size,
                    intermediate_size_per_partition,
                ),
                dtype=torch.int32,
            ),
            requires_grad=False,
        )
        layer.register_parameter("w2_weight_packed", w2_weight)
        set_weight_attrs(w2_weight, extra_weight_attrs)

        # Per-expert biases, as gpt-oss carries.
        if self.moe.has_bias:
            w13_num_shards = 2 if self.moe.is_act_and_mul else 1
            w13_bias = torch.nn.Parameter(
                torch.zeros(
                    num_experts,
                    w13_num_shards * intermediate_size_per_partition,
                    dtype=params_dtype,
                ),
                requires_grad=False,
            )
            layer.register_parameter("w13_bias", w13_bias)
            set_weight_attrs(w13_bias, extra_weight_attrs)

            w2_bias = torch.nn.Parameter(
                torch.zeros(num_experts, hidden_size, dtype=params_dtype),
                requires_grad=False,
            )
            layer.register_parameter("w2_bias", w2_bias)
            set_weight_attrs(w2_bias, extra_weight_attrs)

        if self.strategy == "channel":
            num_groups_w2 = num_groups_w13 = 1
            self.group_size = -1
        else:
            if hidden_size % self.group_size != 0:
                raise ValueError(
                    "CompressedTensors WNA16 MoE requires hidden_size "
                    f"({hidden_size}) to be divisible by group_size "
                    f"({self.group_size})."
                )
            if intermediate_size_per_partition % self.group_size != 0:
                raise ValueError(
                    "CompressedTensors WNA16 MoE with static group "
                    "scales requires the MoE intermediate size per "
                    "tensor-parallel partition "
                    f"({intermediate_size_per_partition}) to be divisible by "
                    f"group_size ({self.group_size}). Scale groups would "
                    "otherwise cross TP shard boundaries; use a compatible TP "
                    "size or enable expert parallelism."
                )
            num_groups_w2 = intermediate_size_per_partition // self.group_size
            num_groups_w13 = hidden_size // self.group_size

        if not self.symmetric:
            # For asymmetric int4 quantization, packed_factor (=8) int4 ZPs are
            # stored per int32. Each TP shard must contain a whole number of
            # int32 elements so the packed ZP can be sliced without straddling
            # an int32 boundary.
            w13_n = 2 * intermediate_size_per_partition  # gate+up output channels
            if w13_n % self.packed_factor != 0:
                raise ValueError(
                    f"CompressedTensors WNA16 MoE: gate+up output channels per "
                    f"TP rank (2 * intermediate_size_per_partition = {w13_n}) "
                    f"must be divisible by packed_factor ({self.packed_factor}). "
                    f"Use a TP size where 2 * intermediate_size is divisible by "
                    f"{self.packed_factor}."
                )
            if hidden_size % self.packed_factor != 0:
                raise ValueError(
                    f"CompressedTensors WNA16 MoE: hidden_size ({hidden_size}) "
                    f"must be divisible by packed_factor ({self.packed_factor}) "
                    f"for correct ZP unpacking."
                )

        layer.num_groups_w13 = num_groups_w13
        layer.num_groups_w2 = num_groups_w2

        w13_scale = torch.nn.Parameter(
            torch.ones(
                *self.get_weight_shape(
                    "w13_scale",
                    num_experts,
                    hidden_size,
                    intermediate_size_per_partition,
                    num_groups_w13=num_groups_w13,
                ),
                dtype=params_dtype,
            ),
            requires_grad=False,
        )
        layer.register_parameter("w13_weight_scale", w13_scale)
        set_weight_attrs(w13_scale, extra_weight_attrs)

        w2_scale = torch.nn.Parameter(
            torch.ones(
                *self.get_weight_shape(
                    "w2_scale",
                    num_experts,
                    hidden_size,
                    intermediate_size_per_partition,
                    num_groups_w2=num_groups_w2,
                ),
                dtype=params_dtype,
            ),
            requires_grad=False,
        )
        layer.register_parameter("w2_weight_scale", w2_scale)
        set_weight_attrs(w2_scale, extra_weight_attrs)

        if not self.symmetric:
            w13_zp = torch.nn.Parameter(
                torch.zeros(
                    *self.get_weight_shape(
                        "w13_zp",
                        num_experts,
                        hidden_size,
                        intermediate_size_per_partition,
                        num_groups_w13=num_groups_w13,
                    ),
                    dtype=torch.int32,
                ),
                requires_grad=False,
            )
            layer.register_parameter("w13_weight_zero_point", w13_zp)
            set_weight_attrs(w13_zp, extra_weight_attrs)

            w2_zp = torch.nn.Parameter(
                torch.zeros(
                    *self.get_weight_shape(
                        "w2_zp",
                        num_experts,
                        hidden_size,
                        intermediate_size_per_partition,
                        num_groups_w2=num_groups_w2,
                    ),
                    dtype=torch.int32,
                ),
                requires_grad=False,
            )
            layer.register_parameter("w2_weight_zero_point", w2_zp)
            set_weight_attrs(w2_zp, extra_weight_attrs)

        w2_weight_shape = torch.nn.Parameter(
            torch.empty(num_experts, 2), requires_grad=False
        )
        layer.register_parameter("w2_weight_shape", w2_weight_shape)
        set_weight_attrs(w2_weight_shape, extra_weight_attrs)
        w13_weight_shape = torch.nn.Parameter(
            torch.empty(num_experts, 2), requires_grad=False
        )

        layer.register_parameter("w13_weight_shape", w13_weight_shape)
        set_weight_attrs(w13_weight_shape, extra_weight_attrs)

        layer.a13_scale = None
        layer.a2_scale = None

    def _setup_kernel(self, layer: RoutedExperts):
        assert self.experts_cls is not None
        self.moe_quant_config = self.get_fused_moe_quant_config(layer)
        assert self.moe_quant_config is not None

        self.moe_kernel = make_wna16_moe_kernel(
            moe_quant_config=self.moe_quant_config,
            moe_config=self.moe,
            experts_cls=self.experts_cls,
            backend=self.wna16_backend,
            routing_tables=layer._expert_routing_tables(),
        )

        if self.wna16_backend == WNA16MoEBackend.ZEN_CPU:
            # Monolithic experts route inside apply(), so like the unquantized
            # CPU path they need the router config that only the layer carries.
            self.moe_kernel.fused_experts.process_weights_after_loading(layer)

    def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
        from vllm.model_executor.layers.fused_moe.experts.cpu_moe import (
            swigluoai_w13_interleave_perm,
        )

        # Reorder before the conversion below, which repacks w13 for the kernel.
        # The CT WNA16 buffers are N-first, so 2I is dim 1 of the packed weight
        # [E, 2I, K/pack] and of its group scales [E, 2I, G], as for the bias.
        perm = swigluoai_w13_interleave_perm(
            self.experts_cls,
            self.moe.activation,
            layer.w13_weight_packed.size(1),
            layer.w13_weight_packed.device,
        )
        if perm is not None:
            replace_parameter(
                layer,
                "w13_weight_packed",
                layer.w13_weight_packed.data[:, perm].contiguous(),
            )
            replace_parameter(
                layer,
                "w13_weight_scale",
                layer.w13_weight_scale.data[:, perm].contiguous(),
            )
            if self.moe.has_bias:
                replace_parameter(
                    layer, "w13_bias", layer.w13_bias.data[:, perm].contiguous()
                )

        # Process weights using the shared oracle infrastructure
        converted = convert_to_wna16_moe_kernel_format(
            backend=self.wna16_backend,
            layer=layer,
            quant_config=self.weight_quant,
            input_dtype=self.input_dtype,
            w13=layer.w13_weight_packed,
            w2=layer.w2_weight_packed,
            w13_scale=layer.w13_weight_scale,
            w2_scale=layer.w2_weight_scale,
            w13_qzeros=getattr(layer, "w13_weight_zero_point", None),
            w2_qzeros=getattr(layer, "w2_weight_zero_point", None),
            w13_bias=getattr(layer, "w13_bias", None),
            w2_bias=getattr(layer, "w2_bias", None),
        )

        if converted is None:
            self._setup_kernel(layer)
            return

        (
            w13_qweight,
            w2_qweight,
            w13_scales,
            w2_scales,
            w13_qzeros,
            w2_qzeros,
            w13_input_global_scale,
            w2_input_global_scale,
            w13_bias,
            w2_bias,
        ) = converted

        # Replace common parameters
        replace_parameter(layer, "w13_weight_packed", w13_qweight)
        replace_parameter(layer, "w2_weight_packed", w2_qweight)
        replace_parameter(layer, "w13_weight_scale", w13_scales)
        replace_parameter(layer, "w2_weight_scale", w2_scales)

        if w13_bias is not None:
            replace_parameter(layer, "w13_bias", w13_bias)
        if w2_bias is not None:
            replace_parameter(layer, "w2_bias", w2_bias)

        # CPU fused_experts_cpu and the RDNA3 HIP kernel require zero points
        # even for symmetric quant (the oracle synthesizes them).
        # EMULATION bakes ZP into the dequantized bf16 weights — ZP is None.
        if (
            not self.symmetric
            or self.wna16_backend in (WNA16MoEBackend.CPU, WNA16MoEBackend.RDNA3)
        ) and self.wna16_backend != WNA16MoEBackend.EMULATION:
            assert w13_qzeros is not None and w2_qzeros is not None
            replace_parameter(layer, "w13_weight_zero_point", w13_qzeros)
            replace_parameter(layer, "w2_weight_zero_point", w2_qzeros)

        if self.is_marlin:
            # Register input global scales if present
            if w13_input_global_scale is not None:
                layer.register_parameter(
                    "w13_input_global_scale",
                    torch.nn.Parameter(w13_input_global_scale, requires_grad=False),
                )
            if w2_input_global_scale is not None:
                layer.register_parameter(
                    "w2_input_global_scale",
                    torch.nn.Parameter(w2_input_global_scale, requires_grad=False),
                )

        # Alias packed weights to w13_weight/w2_weight for the modular kernel interface
        layer.w13_weight = layer.w13_weight_packed
        layer.w2_weight = layer.w2_weight_packed

        self._setup_kernel(layer)

    def get_fused_moe_quant_config(
        self, layer: torch.nn.Module
    ) -> FusedMoEQuantConfig | None:
        if self.wna16_backend == WNA16MoEBackend.HUMMING:
            from vllm.model_executor.layers.quantization.utils.humming import (
                get_humming_moe_quant_config,
            )

            return get_humming_moe_quant_config(
                layer,
                gemm1_alpha=getattr(layer, "swiglu_alpha", None),
                gemm1_beta=getattr(layer, "swiglu_beta", None),
                gemm1_clamp_limit=getattr(layer, "swiglu_limit", None),
            )
        return make_wna16_moe_quant_config(
            w1_scale=layer.w13_weight_scale,
            w2_scale=layer.w2_weight_scale,
            group_size=self.group_size,
            num_bits=self.num_bits,
            w1_zp=getattr(layer, "w13_weight_zero_point", None),
            w2_zp=getattr(layer, "w2_weight_zero_point", None),
            w1_bias=getattr(layer, "w13_bias", None),
            w2_bias=getattr(layer, "w2_bias", None),
            gemm1_clamp_limit=getattr(layer, "swiglu_limit", None),
            gemm1_alpha=getattr(layer, "swiglu_alpha", None),
            gemm1_beta=getattr(layer, "swiglu_beta", None),
        )

    def apply_monolithic(
        self,
        layer: RoutedExperts,
        x: torch.Tensor,
        router_logits: torch.Tensor,
        input_ids: torch.Tensor | None = None,
    ) -> torch.Tensor:
        assert self.is_monolithic
        assert self.moe_kernel is not None
        return self.moe_kernel.apply_monolithic(
            x,
            layer.w13_weight,
            layer.w2_weight,
            router_logits,
            activation=layer.activation,
            global_num_experts=layer.global_num_experts,
            expert_map=layer.expert_map,
            apply_router_weight_on_input=layer.apply_router_weight_on_input,
            num_expert_group=layer.num_expert_group,
            topk_group=layer.topk_group,
            e_score_correction_bias=layer.e_score_correction_bias,
            routed_scaling_factor=layer.routed_scaling_factor,
            routing_sink=layer.routing_sink,
        )

    def apply(
        self,
        layer: RoutedExperts,
        x: torch.Tensor,
        topk_weights: torch.Tensor,
        topk_ids: torch.Tensor,
        shared_experts: SharedExperts | None,
        shared_experts_input: torch.Tensor | None,
    ) -> torch.Tensor:
        assert not self.is_monolithic
        assert self.moe_kernel is not None
        return self.moe_kernel.apply(
            x,
            layer.w13_weight,
            layer.w2_weight,
            topk_weights=topk_weights,
            topk_ids=topk_ids,
            activation=layer.activation,
            global_num_experts=layer.global_num_experts,
            expert_map=layer.expert_map,
            apply_router_weight_on_input=layer.apply_router_weight_on_input,
            shared_experts=shared_experts,
            shared_experts_input=shared_experts_input,
        )

    @property
    def supports_eplb(self) -> bool:
        return self.wna16_backend == WNA16MoEBackend.TRITON

get_weight_shape(weight_name, num_experts, hidden_size, intermediate_size_per_partition, num_groups_w2=None, num_groups_w13=None)

Return N-first buffer shape for the given weight/scale/zp tensor.

All CT MoE weights are allocated in the checkpoint's native N-first layout [E, N, K_packed]. Backend-specific transposition (e.g. to Marlin's K-first layout) is deferred to convert_to_wna16_moe_kernel_format.

Source code in vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors_moe/compressed_tensors_moe_wna16.py
def get_weight_shape(
    self,
    weight_name: str,
    num_experts: int,
    hidden_size: int,
    intermediate_size_per_partition: int,
    num_groups_w2: int | None = None,
    num_groups_w13: int | None = None,
) -> tuple[int, int, int]:
    """Return N-first buffer shape for the given weight/scale/zp tensor.

    All CT MoE weights are allocated in the checkpoint's native N-first
    layout ``[E, N, K_packed]``. Backend-specific transposition (e.g. to
    Marlin's K-first layout) is deferred to
    ``convert_to_wna16_moe_kernel_format``.
    """
    w13_num_shards = 2 if self.moe.is_act_and_mul else 1
    w13_n = w13_num_shards * intermediate_size_per_partition
    pf = self.packed_factor
    shape_map = {
        "w13_weight": (num_experts, w13_n, hidden_size // pf),
        "w13_scale": (num_experts, w13_n, num_groups_w13),
        "w13_zp": (num_experts, w13_n // pf, num_groups_w13),
        "w2_weight": (
            num_experts,
            hidden_size,
            intermediate_size_per_partition // pf,
        ),
        "w2_scale": (num_experts, hidden_size, num_groups_w2),
        "w2_zp": (num_experts, hidden_size // pf, num_groups_w2),
    }
    shape = shape_map[weight_name]
    assert isinstance(shape, tuple) and all(isinstance(d, int) for d in shape)
    return shape  # type: ignore[return-value]