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
Assistant
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)
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
The error you're encountering stems from attempting to convert a QuantState object into a torch.tensor. Specifically, during the deserialization process, k_absmax and v_absmax are being loaded as QuantState instances instead of simple float values, which leads to the TypeError.
To resolve this issue, you should extract the actual float values from the QuantState objects before saving them. This ensures that when you load the data, you're working with plain floats, avoiding the deserialization of complex objects that aren't intended to be tensors.
Here's a step-by-step guide to modifying your code:
Extract Float Values During Quantization and Saving:
Modify the quantize_and_save function to extract the float values from k_absmax and v_absmax before saving them. This ensures that only primitive data types are serialized, avoiding the complexities of handling QuantState objects during deserialization.
Adjust the Deserialization Process:
Since you're now saving plain float values for k_absmax and v_absmax, you can safely convert them to tensors without encountering type errors.
Updated Code with Explanations
python
import torch
import bitsandbytes as bnb
from transformers.cache_utils import DynamicCache
# Ensure that DynamicCache and set are safe during serialization
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:
# Convert tensors to float16 for quantization
k, v = k.to(torch.float16), v.to(torch.float16)
# Perform 4-bit quantization using NF4
k_quant, k_absmax = bnb.functional.quantize_4bit(k, quant_type="nf4")
v_quant, v_absmax = bnb.functional.quantize_4bit(v, quant_type="nf4")
# Extract float values from QuantState
# Assuming `QuantState` has an attribute or method to retrieve the absmax value
# This may vary based on bitsandbytes' implementation
# Replace `.absmax()` with the correct method if different
k_absmax_value = k_absmax.absmax().item() if hasattr(k_absmax, 'absmax') else float(k_absmax)
v_absmax_value = v_absmax.absmax().item() if hasattr(v_absmax, 'absmax') else float(v_absmax)
# Append quantized tensors and their corresponding absmax values
quantized_past_key_values.append(((k_quant, k_absmax_value), (v_quant, v_absmax_value)))
# Save the quantized data to disk
torch.save(quantized_past_key_values, save_path)
print("Cache saved successfully with NF4 quantization and absmax.")
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):
# Convert absmax values back to tensors
k_absmax_tensor = torch.tensor(k_absmax, dtype=torch.float32, device=device)
v_absmax_tensor = torch.tensor(v_absmax, dtype=torch.float32, device=device)
# Define output shapes based on quantized tensor dimensions
key_out_shape = (k_quant.shape[0] * 8, k_quant.shape[1])
value_out_shape = (v_quant.shape[0] * 8, v_quant.shape[1])
# Dequantize the key and value tensors
key_states = bnb.functional.dequantize_4bit(
k_quant,
absmax=k_absmax_tensor,
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_tensor,
out=torch.empty(value_out_shape, dtype=torch.float16, device=device),
quant_type="nf4"
)
# Update the DynamicCache with the dequantized tensors
past_key_values.update(key_states, value_states, layer_idx)
print("DynamicCache populated with dequantized float16 past_key_values.")
return past_key_values
# Example usage:
# Make sure `past_key_values` is defined before calling `quantize_and_save`
# quantize_and_save(past_key_values)
# Load the quantized cache
past_key_values = load_and_dequantize()
Key Changes and Explanations:
Extracting Float Values:
python
k_absmax_value = k_absmax.absmax().item() if hasattr(k_absmax, 'absmax') else float(k_absmax)
v_absmax_value = v_absmax.absmax().item() if hasattr(v_absmax, 'absmax') else float(v_absmax)
This code checks if k_absmax and v_absmax have an .absmax() method (common in PyTorch tensors). If they do, it extracts the float value using .item(). Otherwise, it attempts to directly convert them to floats.
Note: The exact method to extract the float value might vary based on the implementation of QuantState in bitsandbytes. Ensure that you're using the correct attribute or method to retrieve the float value representing the absolute maximum.
Deserialization Adjustments:
After saving, during the loading process, k_absmax and v_absmax are now simple floats. Therefore, they can be easily converted back into tensors without any type conflicts.
Security Considerations:
Your initial approach to add DynamicCache and set to torch.serialization.add_safe_globals is correct. Since you're no longer serializing complex objects like QuantState, you don't need to add them to the safe globals, which enhances the security of the deserialization process.
Future-Proofing:
The warning you received about weights_only being set to True in future versions of PyTorch is addressed by ensuring that only safe and necessary data types are serialized and deserialized. By extracting and storing only primitive data types (like floats), you mitigate potential security risks associated with loading arbitrary objects.
Final Notes:
Testing: After making these changes, thoroughly test the serialization and deserialization processes to ensure that the quantization and dequantization steps work as expected.
Dependencies: Ensure that all necessary dependencies, especially the bitsandbytes and transformers libraries, are up-to-date to avoid compatibility issues.
Error Handling: You might want to add additional error handling to manage scenarios where the extraction of float values from QuantState fails or behaves unexpectedly.
By implementing these changes, you should be able to eliminate the TypeError and successfully serialize and deserialize your quantized cache using NF4 quantization.
If you continue to encounter issues or if the QuantState extraction doesn't behave as expected, please provide additional details or consult the bitsandbytes library documentation for specific methods to retrieve quantization parameters.