gguf.py 23.7 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
from collections.abc import Callable, Mapping
from types import MappingProxyType
6
from typing import Any, Optional
7
8
9

import gguf
import torch
10
from gguf import GGMLQuantizationType as WeightType
11
12
13
from torch.nn.parameter import Parameter, UninitializedParameter

from vllm import _custom_ops as ops
14
from vllm.logger import init_logger
15
16
17
18
19
20
21
22
23
24
from vllm.model_executor.layers.fused_moe.config import (
    FusedMoEConfig,
    FusedMoEQuantConfig,
)
from vllm.model_executor.layers.fused_moe.layer import FusedMoE, FusedMoEMethodBase
from vllm.model_executor.layers.linear import (
    LinearBase,
    LinearMethodBase,
    UnquantizedLinearMethod,
)
25
from vllm.model_executor.layers.quantization import QuantizationMethods
26
from vllm.model_executor.layers.quantization.base_config import (
27
28
29
    QuantizationConfig,
    QuantizeMethodBase,
)
30
31
32
33
34
from vllm.model_executor.layers.vocab_parallel_embedding import (
    UnquantizedEmbeddingMethod,
    VocabParallelEmbedding,
)
from vllm.model_executor.models.utils import WeightsMapper
35
from vllm.model_executor.utils import set_weight_attrs
36
from vllm.utils.torch_utils import direct_register_custom_op
37

38
39
logger = init_logger(__name__)

40
41
42
43

class GGUFConfig(QuantizationConfig):
    """Config class for GGUF."""

44
    def __init__(self, unquantized_modules: list[str] | None = None) -> None:
45
        super().__init__()
46
        self.unquantized_modules = unquantized_modules or []
47
48

    def __repr__(self) -> str:
49
        return "GGUFConfig()"
50

51
    def get_name(self) -> QuantizationMethods:
52
53
        return "gguf"

54
    def get_supported_act_dtypes(self) -> list[torch.dtype]:
55
        return [torch.half, torch.bfloat16, torch.float32]
56
57
58
59
60
61

    @classmethod
    def get_min_capability(cls) -> int:
        return 60

    @classmethod
62
    def get_config_filenames(cls) -> list[str]:
63
64
65
        return []  # no extra configs.

    @classmethod
66
    def from_config(cls, config: dict[str, Any]) -> "GGUFConfig":
67
68
        return cls()

69
70
71
    def get_quant_method(
        self, layer: torch.nn.Module, prefix: str
    ) -> Optional["QuantizeMethodBase"]:
72
        if isinstance(layer, LinearBase):
73
74
75
            if is_layer_skipped_gguf(
                prefix, self.unquantized_modules, self.packed_modules_mapping
            ):
76
                return UnquantizedLinearMethod()
77
78
            return GGUFLinearMethod(self)
        elif isinstance(layer, VocabParallelEmbedding):
79
80
81
82
            if is_layer_skipped_gguf(
                prefix, self.unquantized_modules, self.packed_modules_mapping
            ):
                return UnquantizedEmbeddingMethod()
83
            return GGUFEmbeddingMethod(self)
84
        elif isinstance(layer, FusedMoE):
85
            return GGUFMoEMethod(self, layer.moe_config)
86
87
        return None

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
    def apply_vllm_mapper(self, hf_to_vllm_mapper: "WeightsMapper"):
        """
        Interface for models to update module names referenced in
        quantization configs in order to reflect the vllm model structure

        :param hf_to_vllm_mapper: maps from hf model structure (the assumed
            structure of the qconfig) to vllm model structure
        """
        if self.unquantized_modules is not None:
            self.unquantized_modules = hf_to_vllm_mapper.apply_list(
                self.unquantized_modules
            )


def is_layer_skipped_gguf(
    prefix: str,
    unquantized_modules: list[str],
    fused_mapping: Mapping[str, list[str]] = MappingProxyType({}),
):
    # Fused layers like gate_up_proj or qkv_proj will not be fused
    # in the safetensors checkpoint. So, we convert the name
    # from the fused version to unfused + check to make sure that
    # each shard of the fused layer has the same scheme.
    proj_name = prefix.split(".")[-1]
    if proj_name in fused_mapping:
        shard_prefixes = [
            prefix.replace(proj_name, shard_proj_name)
            for shard_proj_name in fused_mapping[proj_name]
        ]

        is_skipped = None
        for shard_prefix in shard_prefixes:
            is_shard_skipped = any(
                shard_prefix in module_name for module_name in unquantized_modules
            )

            if is_skipped is None:
                is_skipped = is_shard_skipped
            elif is_shard_skipped != is_skipped:
                raise ValueError(
                    f"Detected some but not all shards of {prefix} "
                    "are quantized. All shards of fused layers "
                    "to have the same precision."
                )
    else:
        is_skipped = any(module_name in prefix for module_name in unquantized_modules)

    assert is_skipped is not None
    return is_skipped
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
UNQUANTIZED_TYPES = {WeightType.F32, WeightType.F16, WeightType.BF16}
STANDARD_QUANT_TYPES = {
    WeightType.Q4_0,
    WeightType.Q4_1,
    WeightType.Q5_0,
    WeightType.Q5_1,
    WeightType.Q8_0,
    WeightType.Q8_1,
}
KQUANT_TYPES = {
    WeightType.Q2_K,
    WeightType.Q3_K,
    WeightType.Q4_K,
    WeightType.Q5_K,
    WeightType.Q6_K,
}
IMATRIX_QUANT_TYPES = {
    WeightType.IQ1_M,
    WeightType.IQ1_S,
    WeightType.IQ2_XXS,
    WeightType.IQ2_XS,
    WeightType.IQ2_S,
    WeightType.IQ3_XXS,
    WeightType.IQ3_S,
    WeightType.IQ4_XS,
    WeightType.IQ4_NL,
}
# TODO(Isotr0py): Currently, we don't have MMQ kernel for I-Matrix quantization.
# Consolidate DEQUANT_TYPES, MMVQ_QUANT_TYPES and MMQ_QUANT_TYPES after we add
# MMQ kernel for I-Matrix quantization.
DEQUANT_TYPES = STANDARD_QUANT_TYPES | KQUANT_TYPES | IMATRIX_QUANT_TYPES
MMVQ_QUANT_TYPES = STANDARD_QUANT_TYPES | KQUANT_TYPES | IMATRIX_QUANT_TYPES
MMQ_QUANT_TYPES = STANDARD_QUANT_TYPES | KQUANT_TYPES


174
175
176
def _fused_mul_mat_gguf(
    x: torch.Tensor, qweight: torch.Tensor, qweight_type: int
) -> torch.Tensor:
177
178
179
180
    if qweight_type in IMATRIX_QUANT_TYPES:
        mmvq_safe = 8 if qweight.shape[0] > 5120 else 16
    else:
        mmvq_safe = 2 if qweight.shape[0] > 5120 else 6
181
182
183
    # HACK: when doing chunked prefill we don't generate output tokens
    # so input to logits generator is empty which causes invalid parameter
    if x.shape[0] == 0:
184
        return torch.empty(x.shape[0], qweight.shape[0], dtype=x.dtype, device=x.device)
185
186
187
188
    # there is no need to call any kernel for fp16/bf16
    if qweight_type in UNQUANTIZED_TYPES:
        return x @ qweight.T
    # enable MMVQ in contiguous batching with batch_size=1
189
    if x.shape[0] <= mmvq_safe and qweight_type in MMVQ_QUANT_TYPES:
190
        y = ops.ggml_mul_mat_vec_a8(qweight, x, qweight_type, qweight.shape[0])
191
192
193
194
195
    # Use MMQ Kernel if it's available (standard + k-quants)
    elif qweight_type in MMQ_QUANT_TYPES:
        y = ops.ggml_mul_mat_a8(qweight, x, qweight_type, qweight.shape[0])
    # If there is no available MMQ kernel, fallback to dequantize
    elif qweight_type in DEQUANT_TYPES:
196
197
        block_size, type_size = gguf.GGML_QUANT_SIZES[qweight_type]
        shape = (qweight.shape[0], qweight.shape[1] // type_size * block_size)
198
        weight = ops.ggml_dequantize(qweight, qweight_type, *shape, x.dtype)
199
200
        y = x @ weight.T
    else:
201
202
203
204
        # Raise an error if the quantization type is not supported.
        # Might be useful if llama.cpp adds a new quantization type.
        # Wrap to GGMLQuantizationType IntEnum to make sure it's a valid type.
        qweight_type = WeightType(qweight_type)
205
        raise NotImplementedError(f"Unsupported GGUF quantization type: {qweight_type}")
206
207
208
    return y


209
210
211
212
213
def _fused_mul_mat_gguf_fake(
    x: torch.Tensor,
    qweight: torch.Tensor,
    qweight_type: int,
) -> torch.Tensor:
214
    return torch.empty(x.shape[0], qweight.shape[0], dtype=x.dtype, device=x.device)
215
216
217
218
219
220
221
222
223
224
225
226
227
228


try:
    direct_register_custom_op(
        op_name="_fused_mul_mat_gguf",
        op_func=_fused_mul_mat_gguf,
        fake_impl=_fused_mul_mat_gguf_fake,
    )
    fused_mul_mat_gguf = torch.ops.vllm._fused_mul_mat_gguf

except AttributeError as error:
    raise error


229
230
231
232
233
234
235
236
def _fused_moe_gguf(
    x: torch.Tensor,
    w1: torch.Tensor,
    w2: torch.Tensor,
    topk_weights: torch.Tensor,
    topk_ids: torch.Tensor,
    qweight_type: int,
    qweight_type2: int,
237
    activation: str,
238
) -> torch.Tensor:
239
240
    def act(x: torch.Tensor):
        d = x.shape[-1] // 2
241
        output_shape = x.shape[:-1] + (d,)
242
243
244
245
246
247
248
249
250
        out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
        if activation == "silu":
            torch.ops._C.silu_and_mul(out, x)
        elif activation == "gelu":
            torch.ops._C.gelu_and_mul(out, x)
        else:
            raise ValueError(f"Unsupported activation: {activation}")
        return out

251
    # lazy import to avoid triggering triton import in CPU backend
252
    from vllm.model_executor.layers.fused_moe.fused_moe import moe_align_block_size
253

254
    out_hidden_states = torch.empty_like(x)
255
    # unless we decent expert reuse we are better off running moe_vec kernel
256
257
258
259
260
    if (
        qweight_type2 in MMQ_QUANT_TYPES
        and qweight_type in MMQ_QUANT_TYPES
        and x.shape[0] > 64
    ):
261
262
263
264
265
        num_tokens, _ = x.shape
        E, N, _ = w1.shape
        top_k = topk_ids.shape[1]
        BLOCK_SIZE = ops.ggml_moe_get_block_size(qweight_type)

266
267
268
269
270
271
272
273
274
275
276
277
278
279
        sorted_token_ids, expert_ids, num_tokens_post_padded = moe_align_block_size(
            topk_ids, BLOCK_SIZE, E
        )
        out = ops.ggml_moe_a8(
            x,
            w1,
            sorted_token_ids,
            expert_ids,
            num_tokens_post_padded,
            qweight_type,
            N,
            top_k,
            num_tokens,
        )
280
        out = act(out)
281
282
283
284
285
286
287
288
289
290
291
        out = ops.ggml_moe_a8(
            out,
            w2,
            sorted_token_ids,
            expert_ids,
            num_tokens_post_padded,
            qweight_type2,
            w2.shape[1],
            1,
            num_tokens * top_k,
        )
292
        out = out.reshape(num_tokens, top_k, w2.shape[1]).mul_(
293
294
            topk_weights.view(num_tokens, top_k, 1)
        )
295
        ops.moe_sum(out, out_hidden_states)
296
297
298
299
300
    elif qweight_type2 in MMVQ_QUANT_TYPES and qweight_type in MMVQ_QUANT_TYPES:
        num_tokens, _ = x.shape
        E, N, _ = w1.shape
        top_k = topk_ids.shape[1]

301
        out = ops.ggml_moe_a8_vec(x, w1, topk_ids, top_k, qweight_type, N, num_tokens)
302
303
        out = act(out)

304
305
306
        out = ops.ggml_moe_a8_vec(
            out, w2, topk_ids, 1, qweight_type2, w2.shape[1], num_tokens * top_k
        )
307
        out = out.reshape(num_tokens, top_k, w2.shape[1]).mul_(
308
309
            topk_weights.view(num_tokens, top_k, 1)
        )
310
        ops.moe_sum(out, out_hidden_states)
311
    else:
312
313
314
315
316
        logger.warning_once(
            "There is no support for fast MoE kernel "
            "for current quantization method. "
            "Falling back to slow implementation. "
        )
317
        for tok, (w, idx) in enumerate(zip(topk_weights, topk_ids)):
318
            inp = x[tok].reshape((1,) + x.shape[1:])
319
320
321
322
            current_hidden_state = None
            for ww, ii in zip(w, idx):
                expert_up = w1[ii]

323
                out = fused_mul_mat_gguf(inp, expert_up, qweight_type)
324
325
326
                out = act(out)

                expert_down = w2[ii]
327
328
329
                current_state = fused_mul_mat_gguf(
                    out, expert_down, qweight_type2
                ).mul_(ww)
330
331
332
333
334
335
336
337
                if current_hidden_state is None:
                    current_hidden_state = current_state
                else:
                    current_hidden_state.add_(current_state)
            out_hidden_states[tok] = current_hidden_state
    return out_hidden_states


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
def _fused_moe_gguf_fake(
    x: torch.Tensor,
    w1: torch.Tensor,
    w2: torch.Tensor,
    topk_weights: torch.Tensor,
    topk_ids: torch.Tensor,
    qweight_type: int,
    qweight_type2: int,
    activation: str,
) -> torch.Tensor:
    return torch.empty_like(x)


try:
    direct_register_custom_op(
        op_name="_fused_moe_gguf",
        op_func=_fused_moe_gguf,
        fake_impl=_fused_moe_gguf_fake,
    )
    fused_moe_gguf = torch.ops.vllm._fused_moe_gguf

except AttributeError as error:
    raise error


def _apply_gguf_embedding(
    x: torch.Tensor,
    qweight: torch.Tensor,
    qweight_type: int,
    hidden_size: int,
368
    dtype: torch.dtype | None = None,
369
370
371
372
373
374
) -> torch.Tensor:
    if qweight_type in UNQUANTIZED_TYPES:
        return torch.embedding(qweight, x)
    elif qweight_type in DEQUANT_TYPES:
        block_size, type_size = gguf.GGML_QUANT_SIZES[qweight_type]
        x_flat = x.flatten()
375
        assert hidden_size == qweight.shape[1] // type_size * block_size
376
        quant = torch.index_select(qweight, dim=0, index=x_flat)
377
378
379
        dequant = ops.ggml_dequantize(
            quant, qweight_type, hidden_size, x_flat.shape[0], dtype
        )
380
381
382
        return dequant.view(*x.shape, hidden_size)
    else:
        qweight_type = WeightType(qweight_type)
383
        raise NotImplementedError(f"Unsupported GGUF quantization type: {qweight_type}")
384
385
386
387
388
389
390


def _apply_gguf_embedding_fake(
    x: torch.Tensor,
    qweight: torch.Tensor,
    qweight_type: int,
    hidden_size: int,
391
    dtype: torch.dtype | None = None,
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
) -> torch.Tensor:
    return torch.empty(x.shape[0], hidden_size, dtype=dtype, device=x.device)


try:
    direct_register_custom_op(
        op_name="_apply_gguf_embedding",
        op_func=_apply_gguf_embedding,
        fake_impl=_apply_gguf_embedding_fake,
    )
    apply_gguf_embedding = torch.ops.vllm._apply_gguf_embedding

except AttributeError as error:
    raise error


408
409
410
411
412
413
414
415
416
417
class GGUFLinearMethod(LinearMethodBase):
    """Linear method for GGUF.

    Args:
        quant_config: The GGUF quantization config.
    """

    def __init__(self, quant_config: GGUFConfig):
        self.quant_config = quant_config

418
419
420
421
422
423
424
425
426
427
    def create_weights(
        self,
        layer: torch.nn.Module,
        input_size_per_partition: int,
        output_partition_sizes: list[int],
        input_size: int,
        output_size: int,
        params_dtype: torch.dtype,
        **extra_weight_attrs,
    ):
428
        self.params_dtype = params_dtype
429
430
431
        output_size_per_partition = sum(output_partition_sizes)

        tensor_shape = (output_size_per_partition, input_size_per_partition)
432
        qweight = GGUFUninitializedParameter(requires_grad=False)
433
        set_weight_attrs(
434
435
            qweight,
            {
436
437
438
439
                "input_dim": 1,
                "output_dim": 0,
                "tensor_shape": tensor_shape,
                "is_gguf_weight": True,
440
                "data_container": [],
441
                "shard_id": [],
442
                "shard_id_map": {},
443
444
            },
        )
445
446
447
        set_weight_attrs(qweight, extra_weight_attrs)
        layer.register_parameter("qweight", qweight)

448
449
450
451
        qweight_type = Parameter(
            torch.empty(len(output_partition_sizes), dtype=torch.uint8),
            requires_grad=False,
        )
452
        set_weight_attrs(
453
454
            qweight_type,
            {
455
456
457
                "is_gguf_weight_type": True,
                "weight_type": 0,
                "shard_weight_type": {},
458
459
460
                "ignore_warning": True,
            },
        )
461
462
463
        set_weight_attrs(qweight_type, extra_weight_attrs)
        layer.register_parameter("qweight_type", qweight_type)

464
465
    def process_weights_after_loading(self, layer: torch.nn.Module):
        qweight_type = layer.qweight_type.weight_type
466
        if not (qweight_type in UNQUANTIZED_TYPES or qweight_type in DEQUANT_TYPES):
467
468
            qweight_type = WeightType(qweight_type)
            raise ValueError(
469
470
                f"Unsupported GGUF quantization type {qweight_type} in layer {layer}."
            )
471
472
473
474
475
476
477
478
479
480
481
482
        # For MergedColumnParallelLinear and QKVParallelLinear, we need to
        # materialize the padded weight parameter for CUDA Graph compatibility.
        self._create_padded_weight_param(layer)

    def _create_padded_weight_param(self, layer: torch.nn.Module):
        """Create padded weight parameter for GGUF MergedLinear layer."""
        qweight = layer.qweight
        shard_id_map = qweight.shard_id_map
        shard_id = qweight.shard_id
        if len(data_container := qweight.data_container) > 1:
            dtype = {data.dtype for data in data_container}
            assert len(dtype) == 1, ValueError(
483
484
                f"Data container has mixed dtypes: {dtype}"
            )
485
486
487
488
489
490
            dtype = next(iter(dtype))
            # concat dim0 and pad dim1
            padded_side = max(x.size(1) for x in data_container)
            concat_side = sum(x.size(0) for x in data_container)
            # Pad the quantized weights to dense tensor, and create a map
            # with the location of each shard in the padded tensor.
491
492
493
            padded_data = torch.zeros(
                (concat_side, padded_side), dtype=dtype, device=qweight.device
            )
494
495
496
497
            # (dim0_start, dim0_end, dim1_size)
            shard_offset_map = dict[str, tuple[int, int, int]]()
            for idx in shard_id:
                id_in_container = shard_id_map[idx]
498
                start = sum(x.size(0) for x in data_container[:id_in_container])
499
500
501
502
503
504
505
                end = start + data_container[id_in_container].size(0)
                size = data_container[id_in_container].size(1)
                padded_data[start:end, :size] = data_container[id_in_container]
                shard_offset_map[idx] = (start, end, size)
            qweight.data_container.clear()
            padded_param = Parameter(padded_data, requires_grad=False)
            set_weight_attrs(padded_param, vars(qweight))
506
            set_weight_attrs(padded_param, {"shard_offset_map": shard_offset_map})
507
508
            layer.register_parameter("qweight", padded_param)

509
510
511
512
    def apply(
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
513
        bias: torch.Tensor | None = None,
514
    ) -> torch.Tensor:
515
        shard_id = layer.qweight.shard_id
516

517
        if shard_id:
518
519
            # dequantize shard weights respectively
            shard_id = ["q", "k", "v"] if "q" in shard_id else shard_id
520
            qweight = layer.qweight
521
            result = []
522
            for idx in shard_id:
523
                start, end, offset = layer.qweight.shard_offset_map[idx]
524
                qweight_type = layer.qweight_type.shard_weight_type[idx]
525
526
                result.append(
                    fused_mul_mat_gguf(
527
528
529
                        x, qweight[start:end, :offset].contiguous(), qweight_type
                    )
                )
530
531
532
533
            out = torch.cat(result, axis=1)
        else:
            qweight = layer.qweight
            qweight_type = layer.qweight_type.weight_type
534
            out = fused_mul_mat_gguf(x, qweight, qweight_type)
535
536
537
538
539
        if bias is not None:
            out.add_(bias)
        return out


540
541
542
543
544
545
546
class GGUFMoEMethod(FusedMoEMethodBase):
    """MoE method for GGUF.

    Args:
        quant_config: The GGUF quantization config.
    """

547
548
549
550
551
552
    def __init__(
        self,
        quant_config: GGUFConfig,
        moe: FusedMoEConfig,
    ):
        super().__init__(moe)
553
554
        self.quant_config = quant_config

555
556
557
558
559
560
561
562
563
564
565
    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,
    ):
        tensor_shape = (num_experts, 2 * intermediate_size_per_partition, hidden_size)
        # gate up proj
566
567
        w13_qweight = GGUFUninitializedParameter(requires_grad=False)
        set_weight_attrs(
568
569
            w13_qweight,
            {
570
571
572
573
574
                "input_dim": 1,
                "output_dim": 0,
                "tensor_shape": tensor_shape,
                "is_gguf_weight": True,
                "data_container": [],
575
576
            },
        )
577
578
579
        set_weight_attrs(w13_qweight, extra_weight_attrs)
        layer.register_parameter("w13_qweight", w13_qweight)

580
581
582
583
584
585
586
        w13_qweight_type = Parameter(
            torch.empty(1, dtype=torch.uint8), requires_grad=False
        )
        set_weight_attrs(
            w13_qweight_type,
            {"is_gguf_weight_type": True, "weight_type": 0, "ignore_warning": True},
        )
587
588
589
        set_weight_attrs(w13_qweight_type, extra_weight_attrs)
        layer.register_parameter("w13_qweight_type", w13_qweight_type)

590
591
        tensor_shape = (num_experts, intermediate_size_per_partition, hidden_size)
        # gate down proj
592
593
        w2_qweight = GGUFUninitializedParameter(requires_grad=False)
        set_weight_attrs(
594
595
            w2_qweight,
            {
596
597
598
599
600
                "input_dim": 1,
                "output_dim": 0,
                "tensor_shape": tensor_shape,
                "is_gguf_weight": True,
                "data_container": [],
601
602
            },
        )
603
604
605
        set_weight_attrs(w2_qweight, extra_weight_attrs)
        layer.register_parameter("w2_qweight", w2_qweight)

606
607
608
609
610
611
612
        w2_qweight_type = Parameter(
            torch.empty(1, dtype=torch.uint8), requires_grad=False
        )
        set_weight_attrs(
            w2_qweight_type,
            {"is_gguf_weight_type": True, "weight_type": 0, "ignore_warning": True},
        )
613
614
615
616

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

617
    def get_fused_moe_quant_config(
618
        self, layer: torch.nn.Module
619
    ) -> FusedMoEQuantConfig | None:
620
621
        return None

622
623
624
625
626
627
628
629
    def apply(
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
        router_logits: torch.Tensor,
        top_k: int,
        renormalize: bool,
        use_grouped_topk: bool = False,
630
631
        topk_group: int | None = None,
        num_expert_group: int | None = None,
632
        global_num_experts: int = -1,
633
634
        expert_map: torch.Tensor | None = None,
        custom_routing_function: Callable | None = None,
635
        scoring_func: str = "softmax",
636
        routed_scaling_factor: float = 1.0,
637
        e_score_correction_bias: torch.Tensor | None = None,
638
        apply_router_weight_on_input: bool = False,
639
        activation: str = "silu",
640
        enable_eplb: bool = False,
641
642
643
644
        expert_load_view: torch.Tensor | None = None,
        logical_to_physical_map: torch.Tensor | None = None,
        logical_replica_count: torch.Tensor | None = None,
    ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
645
        if enable_eplb:
646
            raise NotImplementedError("EPLB not supported for `GGUFMoEMethod` yet.")
647

648
        assert activation == "silu", "Only SiLU activation is supported."
649
650
651
        if apply_router_weight_on_input:
            raise NotImplementedError(
                "Apply router weight on input is not supported for"
652
653
                "fused GGUF MoE method."
            )
654

XuruiYang's avatar
XuruiYang committed
655
        topk_weights, topk_ids, _ = FusedMoE.select_experts(
656
657
658
659
660
661
662
663
664
            hidden_states=x,
            router_logits=router_logits,
            use_grouped_topk=use_grouped_topk,
            top_k=top_k,
            renormalize=renormalize,
            topk_group=topk_group,
            num_expert_group=num_expert_group,
            custom_routing_function=custom_routing_function,
            scoring_func=scoring_func,
665
            routed_scaling_factor=routed_scaling_factor,
666
            e_score_correction_bias=e_score_correction_bias,
667
668
669
670
671
672
673
674
675
676
677
678
            indices_type=self.topk_indices_dtype,
        )
        return fused_moe_gguf(
            x,
            layer.w13_qweight,
            layer.w2_qweight,
            topk_weights,
            topk_ids,
            layer.w13_qweight_type.weight_type,
            layer.w2_qweight_type.weight_type,
            activation,
        )
679
680


681
682
683
684
685
686
687
class GGUFEmbeddingMethod(GGUFLinearMethod):
    """Embedding method for GGUF.

    Args:
        quant_config: The GGUF quantization config.
    """

688
    def embedding(self, layer: torch.nn.Module, x: torch.Tensor) -> torch.Tensor:
689
690
        qweight = layer.qweight
        qweight_type = layer.qweight_type.weight_type
691
        hidden_size = qweight.tensor_shape[1]
692

693
694
695
        return apply_gguf_embedding(
            x, qweight, qweight_type, hidden_size, dtype=self.params_dtype
        )
696
697
698
699


class GGUFUninitializedParameter(UninitializedParameter):
    cls_to_become = Parameter
700
    data_container: list[torch.Tensor]