kv_cache.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import torch
  2. from aphrodite.common.utils import print_warning_once
  3. from aphrodite.quantization.base_config import (QuantizationConfig,
  4. QuantizeMethodBase)
  5. class BaseKVCacheMethod(QuantizeMethodBase):
  6. """
  7. Quant method that adds `_k_scale` and `_v_scale` attributes to the
  8. Attention layer to support loading those scaling factors from checkpoints.
  9. The k/v_scale will be used to:
  10. - quantize k/v_cache entries before saving them to the cache
  11. - dequantize k/v_cache entries before fetching them from the cache
  12. :param quant_config: the appropriate QuantizationConfig
  13. """
  14. def __init__(self, quant_config: QuantizationConfig):
  15. self.quant_config = quant_config
  16. def create_weights(self, layer: torch.nn.Module):
  17. """
  18. Create "weight" (aka k_scale and v_scale) for an attention layer.
  19. """
  20. # Initialize the KV cache scales to -1.0, which is an invalid value.
  21. # If the k/v_scale appears in the checkpoint, it will be
  22. # overwritten when loading weights.
  23. layer.k_scale = torch.nn.Parameter(torch.tensor(-1.0),
  24. requires_grad=False)
  25. layer.v_scale = torch.nn.Parameter(torch.tensor(-1.0),
  26. requires_grad=False)
  27. def apply(self, layer: torch.nn.Module) -> torch.Tensor:
  28. raise RuntimeError(
  29. f"{self.__class__.__name__}.apply should not be called.")
  30. def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
  31. # If the kv-cache dtype is auto, we enforce the k/v_scale to be 1.0
  32. # regardless whether the kv-scale is available in the checkpoint.
  33. if layer.kv_cache_dtype != "auto":
  34. if layer.k_scale > 0.0 and layer.v_scale > 0.0:
  35. # We prefer to use separate k_scale and v_scale if present
  36. k_scale = layer.k_scale.to("cpu").tolist()
  37. v_scale = layer.v_scale.to("cpu").tolist()
  38. elif layer.k_scale < 0.0 and layer.v_scale < 0.0:
  39. # If no scales were loaded (both scales are invalid negative
  40. # values), use the default value of 1.0
  41. k_scale = 1.0
  42. v_scale = 1.0
  43. else:
  44. # If we find a single kv_scale in the checkpoint, we remap
  45. # kv_scale to k_scale during weight loading, and duplicate
  46. # k_scale to v_scale here
  47. assert layer.k_scale > 0.0
  48. scale_to_duplicate = max(layer.k_scale, layer.v_scale)
  49. k_scale = scale_to_duplicate.to("cpu").tolist()
  50. v_scale = scale_to_duplicate.to("cpu").tolist()
  51. if not isinstance(k_scale, float) or not isinstance(
  52. v_scale, float):
  53. raise ValueError("Only support per-tensor scaling factor "
  54. "for fp8 KV cache")
  55. # These are used in the final Attention.forward()
  56. layer._k_scale = k_scale
  57. layer._v_scale = v_scale
  58. if (layer._k_scale == 1.0 and layer._v_scale == 1.0
  59. and "e5m2" not in layer.kv_cache_dtype):
  60. print_warning_once(
  61. "Using KV cache scaling factor 1.0 for fp8_e4m3. This "
  62. "may cause accuracy issues. Please make sure k/v_scale "
  63. "scaling factors are available in the fp8 checkpoint.")
  64. del layer.k_scale
  65. del layer.v_scale