In @test_gguf_dequant.py , write a utility function to quantize the data using GGUF DLL rather than numpy. Read @..\llama.cpp\gguf-py\tests\test_quants.py for how to implement it. On Windows, the DLL to load is C:\llama.cpp\build\bin\ggml-base.dll.
--- Content from referenced files ---
Content from @..\llama.cpp\gguf-py\tests\test_quants.py:
#!/usr/bin/env python3
Test gguf.quants so that it exactly matches the C implementation of the (de)quantization
NOTE: this is kind of a mess, but at least it worked for initially testing the Python implementations.
from future import annotations
import argparse
from math import prod
import os
import sys
from pathlib import Path
import ctypes
import logging
import numpy as np
Necessary to load the local gguf package
if "NO_LOCAL_GGUF" not in os.environ and (Path(file).parent.parent.parent / 'gguf-py').exists():
sys.path.insert(0, str(Path(file).parent.parent))
import gguf
from gguf.constants import GGMLQuantizationType
I will update test_gguf_dequant.py to include the GGMLQuants class and modify the main function to use ggml-base.dll for quantization, as requested.
Assistant
I will read qwen3_moe_fused/quantize_gguf/dequant.py to check for CPU support or fallbacks, which will help determine if I can run the verification script without a GPU.
Assistant
I will verify if CUDA is available by running a small script that checks torch.cuda.is_available(). This will help determine if I can run the verification script as is or if I need to modify it to use the CPU.
Assistant
I will now run the updated test_gguf_dequant.py script to verify the changes, since CUDA is available.
Assistant
I have successfully updated test_gguf_dequant.py to include the GGMLQuants class and the ggml_init_params structure, allowing the script to use the ggml-base.dll for quantization. The main function has been modified to prioritize using the DLL, falling back to the NumPy implementation if necessary.
I verified the changes by running the script, which successfully loaded the DLL and performed quantization for various types. Note that IQ3_XXS dequantization validation failed, which was likely skipped previously due to lack of NumPy support, indicating a potential issue in the dequantization logic for that specific type (which is outside the scope of this task).
np.set_printoptions(precision=None, threshold=(4 * 256) + 1, formatter={"int": lambda n: "0x%02X" % n})
r = np.random.randn(8, 1024, 1024).astype(np.float32, copy=False)
# test zero blocks
r[0, 0, :] = 0
## Maybe test infinities? (can make NANs, not really useful in practice)
# r[0, 1, 0] = np.inf
# r[0, 2, 0] = -np.inf
# r[0, 3, 0] = np.inf
# r[0, 3, 1] = -np.inf
for qtype in ((GGMLQuantizationType.F16, *gguf.quants._type_traits.keys()) if user_type is None else (user_type,)):
has_dequantize = False
has_quantize = False
try:
gguf.dequantize(np.zeros((gguf.GGML_QUANT_SIZES[qtype][1]), dtype=np.uint8), qtype)
has_dequantize = True
except (NotImplementedError, AssertionError) as e:
if isinstance(e, AssertionError):
logger.error(f"Error with {qtype.name}: {e}")
raise e
try:
gguf.quantize(np.zeros((gguf.GGML_QUANT_SIZES[qtype][0]), dtype=np.float32), qtype)
has_quantize = True
except (NotImplementedError, AssertionError) as e:
if isinstance(e, AssertionError):
logger.error(f"Error with {qtype.name}: {e}")
raise e
if not has_dequantize and not has_quantize:
continue
logger.info(f"Testing {qtype.name}")
rc = r.copy(order="C")
pyq = None
ggq = None
if has_quantize:
logger.debug(f"Quantizing to {qtype.name} with Python")
pyq = gguf.quants.quantize(rc, qtype)
logger.debug(f"Quantizing to {qtype.name} with C")
ggq = ggml_quants.quantize(rc, qtype)
if qtype == GGMLQuantizationType.F16:
pyq = pyq.view(np.uint8)
quant_equal = compare_tensors(pyq, ggq, qtype)
if not quant_equal:
logger.error(f"Quantization to {qtype.name} does not match ❌")
else:
logger.info(f"Quantization to {qtype.name} matches exactly ✅")
if has_dequantize:
if ggq is None and not quick:
logger.debug(f"Quantizing to {qtype.name} with C")
ggq = ggml_quants.quantize(rc, qtype)
if ggq is not None:
logger.debug(f"Dequantizing from {qtype.name} with Python")
pydq = gguf.quants.dequantize(ggq, qtype)
logger.debug(f"Dequantizing from {qtype.name} with C")
ggdq = ggml_quants.dequantize(ggq, qtype)
dequant_equal = compare_tensors(pydq, ggdq, qtype)
if not dequant_equal:
logger.error(f"Dequantization from {qtype.name} does not match ❌")
else:
logger.info(f"Dequantization from {qtype.name} matches exactly ✅")
rq_shape = gguf.quants.quant_shape_to_byte_shape((8, 1024, 1024 // 2), qtype)
rq = np.random.random(rq_shape).astype(np.float16).view(np.uint8)
logger.debug(f"Dequantizing random f16 data as {qtype.name} with Python")
pydq = gguf.quants.dequantize(rq, qtype)
logger.debug(f"Dequantizing random f16 data as {qtype.name} with C")
ggdq = ggml_quants.dequantize(rq, qtype)
dequant_equal = compare_tensors(pydq, ggdq, qtype)
if not dequant_equal:
logger.error(f"Dequantization from random f16 data as {qtype.name} does not match ❌")
else:
logger.info(f"Dequantization from random f16 data as {qtype.name} matches exactly ✅")
if name == "main":
parser = argparse.ArgumentParser(description="Test Python (de)quantization against the reference C implementation")
parser.add_argument("--libggml", type=Path, default=Path(file).parent.parent.parent / "build" / "bin" / "libggml.so", help="The path to libggml.so")
parser.add_argument("--quick", action="store_true", help="Don't quantize with C when it's not strictly necessary")
parser.add_argument("--type", type=str, help="The quant type to test (all by default)")
code
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG)
do_test(args.libggml, args.quick, GGMLQuantizationType[args.type.upper()] if args.type is not None else None)
Content from @test_gguf_dequant.py:
import gguf
import numpy as np
import torch
from qwen3_moe_fused.quantize_gguf.dequant import dequantize, dequantize_functions
from test_model import get_rtol_atol
def main():
n_blocks = 32
device = "cuda"
code
for qtype in dequantize_functions.keys():
block_size, type_size = gguf.GGML_QUANT_SIZES[qtype]
numel = n_blocks * block_size
weights = np.random.uniform(-1, 1, numel).astype(np.float32)
try:
quantized = gguf.quants.quantize(weights, qtype)
except NotImplementedError:
print(f"{qtype.name} does not support quantize using numpy")
continue
print("quantized", qtype.name, quantized.shape, quantized.dtype)
out_ref = gguf.quants.dequantize(quantized, qtype)
out_ref = torch.from_numpy(out_ref)
quantized_gpu = torch.from_numpy(quantized).to(device)
out = dequantize(quantized_gpu, qtype, (numel,), torch.float32).cpu()
if torch.isnan(out).any():
print("out contains NaN")
if torch.isnan(out_ref).any():
print("ref contains NaN")
rtol = 1e-2
atol = 1e-2
print(torch.allclose(out, out_ref, rtol=rtol, atol=atol))
print(get_rtol_atol(out, out_ref))