import torch
import bitsandbytes as bnb
from transformers.cache_utils import DynamicCache

torch.serialization.add_safe_globals([DynamicCache, set])

def quantize_and_save(past_key_values, save_path="cache_nf4.pth"):
    quantized_past_key_values = []
    for k, v in past_key_values:
        k, v = k.to(torch.float16), v.to(torch.float16)
        k_quant, k_absmax = bnb.functional.quantize_4bit(k, quant_type="nf4")
        v_quant, v_absmax = bnb.functional.quantize_4bit(v, quant_type="nf4")
        quantized_past_key_values.append(((k_quant, k_absmax), (v_quant, v_absmax)))

    torch.save(quantized_past_key_values, save_path)
    print("Cache saved successfully with NF4 quantization and absmax.")

quantize_and_save(past_key_values)

def load_and_dequantize(save_path="cache_nf4.pth"):
    try:
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        loaded_past_key_values = torch.load(save_path, map_location=device)
        print("NF4-quantized cache loaded successfully.")
    except FileNotFoundError:
        print("No NF4 quantized cache file found.")
        loaded_past_key_values = []

    past_key_values = DynamicCache()

    if loaded_past_key_values:
        for layer_idx, ((k_quant, k_absmax), (v_quant, v_absmax)) in enumerate(loaded_past_key_values):
            k_absmax = torch.tensor(k_absmax, dtype=torch.float32, device=device) if not torch.is_tensor(k_absmax) else k_absmax.to(device)
            v_absmax = torch.tensor(v_absmax, dtype=torch.float32, device=device) if not torch.is_tensor(v_absmax) else v_absmax.to(device)

            key_out_shape = (k_quant.shape[0] * 8, k_quant.shape[1])
            value_out_shape = (v_quant.shape[0] * 8, v_quant.shape[1])

            key_states = bnb.functional.dequantize_4bit(
                k_quant,
                absmax=k_absmax,
                out=torch.empty(key_out_shape, dtype=torch.float16, device=device),
                quant_type="nf4"
            )
            value_states = bnb.functional.dequantize_4bit(
                v_quant,
                absmax=v_absmax,
                out=torch.empty(value_out_shape, dtype=torch.float16, device=device),
                quant_type="nf4"
            )

            past_key_values.update(key_states, value_states, layer_idx)

    print("DynamicCache populated with dequantized float16 past_key_values.")
    return past_key_values

past_key_values = load_and_dequantize()
















Cache saved successfully with NF4 quantization and absmax.
NF4-quantized cache loaded successfully.
/tmp/ipykernel_600/3020563291.py:23: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
  loaded_past_key_values = torch.load(save_path, map_location=device)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[8], line 57
     54     print("DynamicCache populated with dequantized float16 past_key_values.")
     55     return past_key_values
---> 57 past_key_values = load_and_dequantize()

Cell In[8], line 33, in load_and_dequantize(save_path)
     31 if loaded_past_key_values:
     32     for layer_idx, ((k_quant, k_absmax), (v_quant, v_absmax)) in enumerate(loaded_past_key_values):
---> 33         k_absmax = torch.tensor(k_absmax, dtype=torch.float32, device=device) if not torch.is_tensor(k_absmax) else k_absmax.to(device)
     34         v_absmax = torch.tensor(v_absmax, dtype=torch.float32, device=device) if not torch.is_tensor(v_absmax) else v_absmax.to(device)
     36         key_out_shape = (k_quant.shape[0] * 8, k_quant.shape[1])

TypeError: must be real number, not QuantState