I'm trying to load GGUF in transformers and dequantize the parameters on demand to save…
- User
I'm trying to load GGUF in transformers and dequantize the parameters on demand to save VRAM, rather than dequantize all parameters when loading. Currently the I can load the model using the new GGUF quantizer, but the results of forward are different from the original model, see @test_gguf_correctness.py . Your task is to fix the bug.
You have write permission to C:\transformers . It's installed as an editable package in my Python env. You can read transformer's source code, add debug logs, and run git there. But in the end all patched code should be in C:\transformers-qwen3-moe-fused .
You may need to add some debug logs and compare the intermediate results between the original model and the new quantizer. --- Content from referenced files --- Content from @test_gguf_correctness.py: import torch import os import time from transformers import AutoModelForCausalLM, AutoConfig from qwen3_moe_fused.quantize import load_gguf_to_model
def get_rtol_atol(actual, expect): actual = actual.float() expect = expect.float() diff = (actual - expect).abs() eps = torch.tensor(torch.finfo(actual.dtype).eps, device=actual.device, dtype=actual.dtype) # Avoid division by zero denom = torch.maximum(torch.maximum(actual.abs(), expect.abs()), eps) rdiff = diff / denom return ( f"mean_rtol={rdiff.mean().item():.3g} " f"max_rtol={rdiff.max().item():.3g} " f"mean_atol={diff.mean().item():.3g} " f"max_atol={diff.max().item():.3g}" )
def main(): gguf_path = r"C:\models\Qwen3-0.6B-UD-Q3_K_XL.gguf" device = "cuda" if torch.cuda.is_available() else "cpu" dtype = torch.bfloat16
code Assistant
I will start by running the reproduction script
test_gguf_correctness.pyto confirm the issue and observe the magnitude of the discrepancy. Then, I will inspect theqwen3_moe_fusedpackage structure, specifically focusing onqwen3_moe_fused/quantize/__init__.pyto locate theload_gguf_to_modelfunction.Assistant
I will read the contents of
qwen3_moe_fused/quantize/layer_gguf.pyto examine theforwardmethod ofGgufLinearand investigate why the output is all zeros.Assistant
I have identified a likely bug in
GgufEmbedding.forwardwhere the weights are incorrectly cast to the integer data type of the input indicesx. I need to confirm howGgufEmbeddingis initialized and where the correct data type should come from. Therefore, I will examineqwen3_moe_fused/quantize/quantizer_gguf.pyto understand howGgufEmbeddingis instantiated and if thedtypeis passed correctly.Assistant
I will modify
qwen3_moe_fused/quantize/layer_gguf.pyto fix theGgufEmbeddingimplementation. Specifically, I will update the__init__method to store thedtypeasself.compute_dtype, and theforwardmethod to use this storeddtype(or a fallback to the default float dtype) instead of casting to the input's integer dtype.Assistant
I made a mistake in the previous attempt by setting
expected_replacementsto 2, while the code block I am replacing occurs only once. I will now retry the replacement inC:\transformers-qwen3-moe-fused\qwen3_moe_fused\quantize\layer_gguf.pywithexpected_replacementsset to 1.Assistant
I will now modify
qwen3_moe_fused/quantize/quantizer_gguf.pyto ensure the correctdtypeis propagated. I'll updatereplace_with_gguf_linearto accept atarget_dtypeargument and use it when initializing modules. Then, I'll updateload_gguf_to_modelto pass itsdtypeargument astarget_dtypetoreplace_with_gguf_linear.Assistant
I will first update
load_gguf_to_modelinqwen3_moe_fused/quantize/quantizer_gguf.pyto pass thedtypeargument astarget_dtypewhen callingreplace_with_gguf_linear.Assistant
I will replace the
replace_with_gguf_linearfunction inC:\transformers-qwen3-moe-fused\qwen3_moe_fused\quantize\quantizer_gguf.pywith an updated version. This new version will accept atarget_dtypeparameter, use it to determine thedtypefor the new GGUF modules, and propagate it in the recursive call.Assistant
I have patched
layer_gguf.pyandquantizer_gguf.pyto fix theGgufEmbeddingissue where weights were being cast to integer types. I will now runtest_gguf_correctness.pyto verify that the fix works and that theGgufEmbeddingnow correctly computes values, producing output close to the reference model.Assistant
I will read
qwen3_moe_fused/quantize/gguf_utils.pyto inspectload_gguf_checkpoint_quantizedandGgufTensor, and to understand howdequantizeinteracts with the loaded data, as I suspect there might be an issue with how the weight matrix layout or dequantization is being handled inGgufLinear.Assistant
I will modify
qwen3_moe_fused/quantize/gguf_utils.pyto remove "attn" from the list of keywords inload_gguf_checkpoint_quantizedthat trigger keeping tensors quantized. This will ensure that attention layers, which may require permutation for RoPE handled by the original tensor processor, are dequantized and processed correctly.Assistant
I have removed
attnfrom the on-demand quantization list, allowing the standardOriginalProcessorClassto handle the necessary permutations for attention weights. I will now runtest_gguf_correctness.pyto confirm that this resolves the logits discrepancy.Assistant
I will verify if
GgufLinearis the source of the discrepancy by temporarily disabling all on-demand quantization. I'll modifyqwen3_moe_fused/quantize/gguf_utils.pyto setkeep_quantizedtoFalsefor all layers. If the results then match the reference model, it confirms thatGgufLinearor the partial quantization process is the issue.Assistant
I have temporarily disabled all on-demand quantization to isolate the issue. I will now run
test_gguf_correctness.pyagain. I expect the loading time to increase as everything is dequantized, but the results should perfectly match the reference model.Assistant
I will temporarily modify
test_gguf_correctness.pyto handle theAttributeErrorwhentensor_typeis missing. This will allow the script to proceed to the logits comparison, enabling me to verify if the output matches the reference model when all layers are dequantized.Assistant
I will run
test_gguf_correctness.pyagain, keepingkeep_quantized=Falseingguf_utils.py, to verify the logits comparison now that the test script handles the missingtensor_type.Assistant
I will investigate why the output differs even with quantization disabled. I suspect a discrepancy in how the
architectureis identified or processed compared to the standardtransformersloading. To verify this, I will add debug prints toqwen3_moe_fused/quantize/gguf_utils.pyto inspect thearchitecture,updated_architecture, and the resolvedOriginalProcessorClass.Assistant
I am running
test_gguf_correctness.pyagain to check the debug output I just added, which will reveal the architecture and processor class being used.- User
Don't try blindly. You can read the source code in C:\transformers and understand how the model loading works.
Assistant
I will list the files in
C:\transformers\src\transformersto locate themodeling_gguf_pytorch_utils.pyfile and other relevant GGUF loading components.Assistant
I see that
Architecture: qwen3is being used.I'll search for
modeling_gguf_pytorch_utils.pyinC:\transformers\src\transformers.Assistant
I forgot that I cannot directly access files outside the workspace via some tools, but
run_shell_commandshould work if I have permissions. However, the previouslist_directorycall failed because of the path restriction. I will try to read the file directly usingread_fileif allowed, or userun_shell_commandwithtype(Windows equivalent ofcat) to read it.But before that, I need to know where it is exactly. The
dircommand is safe.Wait, I am in
C:\transformers-qwen3-moe-fused.C:\transformersis outside. I can userun_shell_commandto cat the file.I'll check
C:\transformers\src\transformers\modeling_gguf_pytorch_utils.py.- User
Go on
- User
I've given you the write permission to C:\transformers . You can read the source code and add some debug log there. Go on.
Assistant
I will read
C:\transformers\src\transformers\modeling_gguf_pytorch_utils.pyto understand how the GGUF loading and tensor processing are implemented in thetransformerslibrary.Assistant
Assistant
I will run
test_gguf_correctness.pyagain to check for missing keys or weight discrepancies across the entire model.Assistant
Assistant
I will run
test_gguf_correctness.pyagain to check if embeddings are tied.Assistant
Assistant
I have applied the fix to update parameters in-place. Now I will run
test_gguf_correctness.pyagain. This should fix thelm_headissue whenkeep_quantized=False, becauseembed_tokensupdate will reflect inlm_head.Assistant
Great! With
keep_quantized=False, the logits now match EXACTLY (mean_atol=0). This confirms that the weights are correct and my in-place update fix resolved the tying issue.Now, I must re-enable on-demand quantization (
keep_quantized=True) and ensure that tying is also handled for the quantized case.For
keep_quantized=True:embed_tokensisGgufEmbedding(buffer).- is likely (parameter), as it is not in my "keep quantized" list (I removed it or didn't add it). Actually, let's check again.
Assistant
I will now update
qwen3_moe_fused/quantize/quantizer_gguf.pyto handle weight tying inload_gguf_to_modelby checkingtie_word_embeddingsand syncing the output embeddings with the input embeddings if necessary.Assistant
I will now run
test_gguf_correctness.pyone last time with on-demand quantization enabled and the weight tying fix in place. I expect the logits to match closely (with small quantization error, not huge random weight error).Assistant
Wait, now I have SHAPE MISMATCHES when using on-demand quantization!
codeShape mismatch for model.layers.25.mlp.up_proj.weight: Ref torch.Size([3072, 1024]), Test torch.Size([3072, 440]) Shape mismatch for model.embed_tokens.weight: Ref torch.Size([151936, 1024]), Test torch.Size([151936, 840])Ref shape
(3072, 1024)vs Test shape(3072, 440). Test shape is which is ? But ? That seems weird. The original dimension is .Assistant
I will run
test_gguf_correctness.pyagain. This time it should finish without errors and show the logits comparison. I'm expectingTest tied: False(because they are different objects now) butlm_headshould be correct, and logits should match.