I'm trying to reimplement Nunchaku SVDQ in @quantizenunchakuborrow.py but currently it…
- User
I'm trying to reimplement Nunchaku SVDQ in @quantize_nunchaku_borrow.py but currently it gives wrong result. I've verified that the AWQ part is correct. Your task is to analyze
weight.pt, smooth_factor.pt, proj_down.pt, proj_up.ptin the current folder, then write a new script that computesproj_down, proj_upgivenweight, smooth_factor, then verify your results against the given groundtruthproj_down, proj_up. To start with, you may investigate the magnitudes and singular values of the given data if needed. You may read the source code in C:\deepcompressor-ussoewwin to understand howproj_down, proj_upare computed in quantization (but this repo may not be the latest version that produced this model), and read C:\nunchaku to understand how they are used in inference (this repo is exacly the latest version). This weight istransformer_blocks.0.img_mlp.net.0.proj.weightin Qwen-Image-Edit. Check whether they need some permutation or swizzling (like in the AWQ part) before or after the SVD. For now we don't need to computeqweight, wscales. --- Content from referenced files --- Content from @quantize_nunchaku_borrow.py: #!/usr/bin/env python3import argparse
import safetensors import safetensors.torch import torch from tqdm import tqdm
def pack_svdq_qweight(weight): n, k = weight.shape device = weight.device assert weight.dtype == torch.int32
code# Parameters from NunchakuWeightPacker(bits=4, warp_n=128) mem_n = 128 mem_k = 64 num_k_unrolls = 2 assert n % mem_n == 0 assert k % (mem_k * num_k_unrolls) == 0 n_tiles = n // mem_n k_tiles = k // mem_k num_n_packs = 8 n_pack_size = 2 num_n_lanes = 8 reg_n = 1 num_k_packs = 1 k_pack_size = 2 num_k_lanes = 4 reg_k = 8 weight = weight.view( n_tiles, num_n_packs, n_pack_size, num_n_lanes, reg_n, k_tiles, num_k_packs, k_pack_size, num_k_lanes, reg_k, ) # (n_tiles, num_n_packs, n_pack_size, num_n_lanes, reg_n, k_tiles, num_k_packs, k_pack_size, num_k_lanes, reg_k) # -> (n_tiles, k_tiles, num_k_packs, num_n_packs, num_n_lanes, num_k_lanes, n_pack_size, k_pack_size, reg_n, reg_k) weight = weight.permute(0, 5, 6, 1, 3, 8, 2, 7, 4, 9).contiguous() weight = weight.view(n, k // 8, 8) packed = torch.zeros((n, k // 8), device=device, dtype=torch.int32) for i in range(8): packed |= weight[:, :, i] << (i * 4) packed = packed.view(torch.int8).view(n, k // 2) return packed Assistant
I will search for "proj_up" in the
C:\deepcompressor-ussoewwindirectory to understand how the projection matrices are computed in the reference implementation. Then, I will create a reproduction scriptreproduce_svd.pyto load the provided.ptfiles and attempt to reproduce theproj_upandproj_downtensors using the current logic to identify discrepancies.Assistant
I will search for "svd" in the
C:\deepcompressor-ussoewwindirectory to locate the SVD decomposition logic and also search for "smooth_factor" to understand how it is utilized in the codebase.Assistant
I will read
deepcompressor/app/diffusion/quant/weight.pyaround line 130 to examine the SVD implementation,deepcompressor/app/diffusion/ptq.pyaround line 287 for its relevance toexport_nunchaku_sdxl, anddeepcompressor/backend/nunchaku/convert.pyto check for logic related toproj_upandproj_down.Assistant
I will read the file
C:\deepcompressor-ussoewwin\deepcompressor\app\diffusion\quant\weight.py.Assistant
I will search for the definition of
DiffusionWeightQuantizerinC:\deepcompressor-ussoewwinto find thecalibrate_low_rankmethod, likely inC:\deepcompressor-ussoewwin\deepcompressor\app\diffusion\quant\quantizer\processor.py. I'll also check the imports inC:\deepcompressor-ussoewwin\deepcompressor\app\diffusion\quant\weight.pyto confirm the location ofDiffusionWeightQuantizer.Assistant
I'll look into
deepcompressor/app/diffusion/quant/quantizer.pyordeepcompressor/app/diffusion/quant/quantizer/__init__.pyto locate theDiffusionWeightQuantizerclass. I will check theC:\deepcompressor-ussoewwin\deepcompressor\app\diffusion\quant\quantizerdirectory.Assistant
I will read the file
C:\deepcompressor-ussoewwin\deepcompressor\app\diffusion\quant\quantizer\quantizer.py.Assistant
I will read the file
C:\deepcompressor-ussoewwin\deepcompressor\calib\lowrank.pyto examine the implementation ofQuantLowRankCalibrator.calibrate, as this appears to be the location of the core logic.Assistant
I will read the file
C:\deepcompressor-ussoewwin\deepcompressor\nn\patch\lowrank.pyto examine how the SVD is computed within theLowRankBranchclass.Assistant
I will examine
C:\nunchakuto see how the SVDQ linear layer is implemented, specifically looking forSVDorprojinC:\nunchaku\nunchaku\models\linear.pyor similar files, to determine howproj_downandproj_upare used in inference.Assistant
I will read the file
C:\nunchaku\nunchaku\models\linear.pyto examine theSVDQW4A4Linearclass definition.Assistant
I will search for "qwen" in the
C:\deepcompressor-ussoewwindirectory to determine if there is any special handling for Qwen models, particularly regardingimg_mlp.net.0.projand whether it requires permutation or swizzling like the AWQ part.Assistant
I will read
C:\deepcompressor-ussoewwin\deepcompressor\app\diffusion\nn\struct.pyaround line 785 to investigate theQwenImageTransformerBlockstructure.Assistant
I will create a reproduction script named
reproduce_svd.py. This script will implement thequantize_svdq_layerfunction using the DeepCompressor style fix:proj_upcalculated asU * Sandproj_downasV.T, utilizingweight.ptandsmooth_factor.ptas inputs. Afterward, I will compare the computedproj_upandproj_downwith the ground truth filesproj_up.ptandproj_down.ptto verify the implementation.Assistant
I am running the reproduction script.
- User
When checking the correctness, check both the absolute error and the relative error.
Assistant
I will update
reproduce_svd.pyto include multiple SVD projection strategies and calculate both absolute and relative errors. Then, I'll execute the script to compare these strategies against the ground truth.Assistant
I'm running the updated reproduction script.
Assistant
The errors are substantial, and the
proj_downMAE of6e-3with strategyUS_Vsuggests it's closer than others, though still not a match. I'll now investigate theweight.ptandgt_proj_down.ptmagnitudes and singular values, and re-examine thequantize_awq_layerpermutation inquantize_nunchaku_borrow.py. Given thatimg_mlp.net.0.proj.weightis 12288x3072 and the 6 blocks mention in the AWQ part suggests 2048x3072, it's possible this layer is also fused. I'll check if the 12288x3072 weight matches the 6 fused blocks (6 * 2048 = 12288) and updatereproduce_svd.pyto test SVD on the permuted weight.Assistant
I'm running the permutation test.
Assistant
The
proj_downMAE of6.1e-3across all permutations suggests a sign flip or ordering issue, common in SVD. I'll check ifgt_proj_downis approximately orthogonal and examine ifproj_up @ proj_down.Tmatchesgt_proj_up @ gt_proj_down.T. If the products match despite individual tensor differences, the decomposition is valid. I'll usetest_product.pyto verify this.Assistant
I'm running the product test.
Assistant
GT Proj Down Orthogonalityis tiny, suggestingproj_downmight be something else, perhapsV * Sor a different scaling. I'll search forpack_svdq_qweightinC:\deepcompressor-ussoewwinto find whereproj_downandproj_upare defined, as the currentquantize_svdq_layerinquantize_nunchaku_borrow.pyisn't matching. I suspect there's a specific permutation or normalization I'm missing.Assistant
I will search for
proj_downandproj_upin theC:\nunchakudirectory to understand how they are loaded and saved, which might reveal their expected structure. I'll checknunchaku\models\linear.pyandnunchaku\merge_safetensors.pyfor any transformation logic during loading or conversion.Assistant
I'll check
nunchaku\ops\quantize.pyto see howproj_downis used, specifically insvdq_quantize_w4a4_act_fuse_lora_cuda. I also want to find the source ofquantize_nunchaku_borrow.pyor similar scripts. I'll searchC:\deepcompressor-ussoewwinforSVDQW4A4Linearto find any conversion logic.Assistant
I will search for
quantize_svdq_layerinC:\deepcompressor-ussoewwinto find the exact implementation, as it was inquantize_nunchaku_borrow.py. I'll also readC:\deepcompressor-ussoewwin\deepcompressor\backend\nunchaku\convert.pyto see how the DeepCompressor model is converted to Nunchaku format.Assistant
I'll examine
C:\deepcompressor-ussoewwin\deepcompressor\backend\nunchaku\utils.pyto find the implementation ofconvert_to_nunchaku_w4x4y16_linear_weightand check how it handles the LoRA down projection, specifically if it appliessmooth.div_or other transformations. I'll also look forproj_downandproj_upin the Nunchaku repo, particularly innunchaku\csrc\pybind.cpp, to see how they are passed to CUDA.Assistant
NunchakuWeightPacker.pack_lowrank_weightperforms a complex swizzling of the low-rank weights, andconvert_to_nunchaku_w4x4y16_linear_state_dictfurther modifieslora_downusingsmooth. I'll updatereproduce_svd.pyto include these packing and smoothing functions, and then test if the packed results match the ground truth. I'll also verify ifgt_proj_downandgt_proj_upare already packed by checking for the presence of certain shapes and values.Assistant
I'm running the packing reproduction script.
Assistant
unpacked_downhas the wrong shape, possibly becauseNunchakuWeightPacker.unpack_lowrank_weightswaps dimensions or becausegt_proj_downis (3072, 128). I'll re-examine the packing logic: ifdown=True, it takes(r, c)and returns(c, r). I'll updatereproduce_packing.pyto check the actual shapes and investigate ifproj_downandproj_upare indeed permuted and scaled as I suspect.Assistant
I'm running the packing reproduction script again.
Assistant
The
proj_downMAE of3.5e-4is much improved, whileproj_up's8.3remains high. I suspect the permutation1, 0, 2forimg_mlp.net.0.proj.weightis correct, but there's a discrepancy in howproj_upis calculated or scaled. I'll test the "No Permutation" scenario inreproduce_packing.pyto compare and see if it yields better results.Assistant
I'm running the packing reproduction script.
Assistant
proj_downmatches well regardless of permutation, butproj_upis consistently off. I suspectproj_upmight be calculated differently, perhaps asU * sqrt(S)or scaled bysmooth_factor. I'll test these alternatives, includingU * SandU, and also check for permutations ofproj_upitself. I'll search forDiffusionWeightQuantizer.calibrate_low_rankinC:\deepcompressor-ussoewwinto find the exact code responsible for this.- User
Always remember to check both the absolute error and the relative error. Even if the absolute error is small, proj_down may be wrong because the values themselves are small.
Assistant
I will write
debug_svd.pyto analyze the relative errors and magnitudes of the tensors. This script will load the weights and ground truth, unpack the ground truth tensors, compute the SVD of the smoothed weights, and then compare the computed components with the unpacked ground truth using both absolute and relative error metrics. I'll also investigate the productunpacked_up @ unpacked_downto see if it reconstructs the smoothed weights.Assistant
I'm running the debug script.
Assistant
Assistant
I'm running
debug_svd_2.py.Assistant
Assistant
I'm running the diagnostic script.