gguf.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. from typing import Any, Dict, List, Optional
  2. import torch
  3. from torch.nn.parameter import Parameter
  4. from aphrodite import _custom_ops as ops
  5. from aphrodite.modeling.layers.linear import LinearBase, LinearMethodBase
  6. from aphrodite.modeling.utils import set_weight_attrs
  7. from aphrodite.quantization.base_config import QuantizationConfig
  8. GGML_QUANT_SIZES = {
  9. 0: (1, 4), # F32
  10. 1: (1, 2), # F16
  11. 2: (32, 2 + 16), # Q4_0
  12. 3: (32, 2 + 2 + 16), # Q4_1
  13. 6: (32, 2 + 4 + 16), # Q5_0
  14. 7: (32, 2 + 2 + 4 + 16), # Q5_1
  15. 8: (32, 2 + 32), # Q8_0
  16. 9: (32, 4 + 4 + 32), # Q8_1
  17. 10: (256, 2 + 2 + 256 // 16 + 256 // 4), # Q2_K
  18. 11: (256, 2 + 256 // 4 + 256 // 8 + 12), # Q3_K
  19. 12: (256, 2 + 2 + 256 // 2 + 12), # Q4_K
  20. 13: (256, 2 + 2 + 256 // 2 + 256 // 8 + 12), # Q5_K
  21. 14: (256, 2 + 256 // 2 + 256 // 4 + 256 // 16), # Q6_K
  22. 15: (256, 4 + 256 + 256 // 8), # Q8_K
  23. 16: (256, 2 + 256 // 4), # IQ2_XXS
  24. 17: (256, 2 + 256 // 4 + 256 // 32), # IQ2_XS
  25. 18: (256, 2 + 3 * 256 // 8), # IQ3_XXS
  26. 19: (256, 2 + 256 // 8 + 256 // 16), # IQ1_S
  27. 20: (32, 2 + 32 // 2), # IQ4_NL
  28. 21: (256, 2 + 256 // 4 + 256 // 32 + 256 // 8 + 256 // 64), # IQ3_S
  29. 22: (256, 2 + 256 // 4 + 256 // 32 + 256 // 32), # IQ2_S
  30. 23: (256, 2 + 2 + 256 // 64 + 256 // 2), # IQ4_XS
  31. }
  32. class GGUFConfig(QuantizationConfig):
  33. """Config class for GGUF"""
  34. def __repr__(self) -> str:
  35. return ("GGUFConfig()")
  36. def get_name(self) -> str:
  37. return "gguf"
  38. def get_supported_act_dtypes(self) -> List[torch.dtype]:
  39. return [torch.half]
  40. def get_min_capability(self) -> int:
  41. return 61
  42. @staticmethod
  43. def get_config_filenames() -> List[str]:
  44. return []
  45. @classmethod
  46. def from_config(cls, config: Dict[str, Any]) -> "GGUFConfig":
  47. return cls()
  48. def get_quant_method(
  49. self, layer: torch.nn.Module) -> Optional["GGUFLinearMethod"]:
  50. if isinstance(layer, LinearBase):
  51. return GGUFLinearMethod(self)
  52. return None
  53. def get_scaled_act_names(self) -> List[str]:
  54. return []
  55. def merge_weight(self) -> bool:
  56. return False
  57. def rope_style(self) -> Optional[bool]:
  58. return False
  59. def quant_vocab(self) -> List[bool]:
  60. return [True, True]
  61. def support_fused_moe(self) -> bool:
  62. return False
  63. class GGUFLinearMethod(LinearMethodBase):
  64. """Linear method for GGUF.
  65. Args:
  66. quant_config: The GGUF quantization config.
  67. """
  68. def __init__(self, quant_config: GGUFConfig):
  69. self.quant_config = quant_config
  70. def create_weights(self, layer: torch.nn.Module,
  71. input_size_per_partition: int,
  72. output_partition_sizes: List[int], input_size: int,
  73. output_size: int, params_dtype: torch.dtype,
  74. **extra_weight_attrs):
  75. # The type of weight is unknown until load state dict
  76. weight = torch.nn.parameter.UninitializedParameter(requires_grad=False)
  77. # No need for pack_factor because we don't fuse qkv layers anyway.
  78. set_weight_attrs(weight, {
  79. "input_dim": 1,
  80. "output_dim": 0,
  81. })
  82. layer.register_parameter("weight", weight)
  83. weight_type = Parameter(
  84. torch.tensor((1), dtype=torch.int, device="cuda"),
  85. requires_grad=False,
  86. )
  87. set_weight_attrs(weight_type, {"ignore_warning": True})
  88. layer.register_parameter("weight_type", weight_type)
  89. def apply(self,
  90. layer: torch.nn.Module,
  91. x: torch.Tensor,
  92. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  93. if isinstance(layer.weight_type, torch.Tensor):
  94. layer.weight_type = int(layer.weight_type)
  95. # Check tensor parallel shape here on first pass
  96. block_size = GGML_QUANT_SIZES[layer.weight_type][1]
  97. if layer.weight.shape[1] % block_size != 0:
  98. raise ValueError("Size is not aligned with the quantized "
  99. "weight shape.")
  100. weight = layer.weight
  101. weight_type = layer.weight_type
  102. infeatures = x.shape[-1]
  103. outfeatures = weight.shape[0]
  104. out_shape = x.shape[:-1] + (weight.shape[0], )
  105. reshaped_x = x.reshape(-1, x.shape[-1])
  106. xshape = x.view(-1, x.shape[-1])
  107. if xshape.shape[0] == 1:
  108. out = ops.ggml_mul_mat_vec_a8(weight, reshaped_x, weight_type,
  109. outfeatures)
  110. elif xshape.shape[0] < 8 and weight_type < 16:
  111. out = ops.ggml_mul_mat_a8(weight, reshaped_x, weight_type,
  112. outfeatures)
  113. else:
  114. weight = ops.ggml_dequantize(weight, weight_type, outfeatures,
  115. infeatures)
  116. out = reshaped_x @ weight.T
  117. if bias is not None:
  118. out = out + bias
  119. return out.reshape(out_shape)
  120. def apply_embedding(self, layer: torch.nn.Module,
  121. x: torch.Tensor) -> torch.Tensor:
  122. if isinstance(layer.weight_type, torch.Tensor):
  123. layer.weight_type = int(layer.weight_type)
  124. weight = layer.weight
  125. weight_type = layer.weight_type
  126. dim, block_size = GGML_QUANT_SIZES[weight_type]
  127. vocab_size = weight.shape[0]
  128. hidden_size = weight.shape[1] // block_size * dim
  129. if weight_type < 2:
  130. return torch.embedding(weight.view(vocab_size, -1), x)
  131. x_flat = x.flatten()
  132. quant = torch.index_select(weight.view(vocab_size, -1),
  133. dim=0,
  134. index=x_flat)
  135. dequant = ops.ggml_dequantize(quant, weight_type, hidden_size,
  136. x_flat.shape[0])
  137. return dequant.view(*x.shape, hidden_size)
  138. def apply_moe_weights(self, w1: Dict[str,
  139. torch.Tensor], w2: Dict[str,
  140. torch.Tensor],
  141. x: torch.Tensor, gating_output: torch.Tensor,
  142. topk: int, renormalize: bool) -> torch.Tensor:
  143. raise NotImplementedError