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. Do SVD on GPU to be faster. You may read the source code in C:\nunchaku to understand howproj_down, proj_up, smooth_factorare used when inferencing Qwen-Image-Edit. 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
# 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 packeddef quantize_residual(residual): group_size = 64 N, K = residual.shape assert K % group_size == 0 assert residual.dtype == torch.float32
residual = residual.view(N, K // group_size, group_size) wscales = torch.abs(residual).amax(dim=-1, keepdim=True) wscales = wscales / 7 # Avoid zero division wscales = torch.clamp(wscales, min=1e-8) qweight = residual / wscales qweight = torch.clamp(torch.round(qweight).to(torch.int32), -8, 7) # Map -8..7 to 0..15 qweight = qweight & 0xF qweight = qweight.view(N, K) qweight = pack_svdq_qweight(qweight) wscales = wscales.squeeze(-1).T return qweight, wscalesdef quantize_svdq_layer(weight, smooth_factor, rank=128): N, K = weight.shape dtype = weight.dtype
# Upcast to float32 before quantization weight = weight.float() smooth_factor = smooth_factor.float() weight = weight * smooth_factor.view(1, -1) U, S, Vh = torch.svd_lowrank(weight, q=min(2 * rank, N, K), niter=10) Vh = Vh.T U = U[:, :rank] S = S[:rank] Vh = Vh[:rank, :] sqrt_S = torch.sqrt(S) proj_up = U * sqrt_S.view(1, -1) proj_down = Vh * sqrt_S.view(-1, 1) residual = weight - proj_up @ proj_down proj_up = proj_up.to(dtype) proj_down = proj_down.T.to(dtype) qweight, wscales = quantize_residual(residual) wscales = wscales.to(dtype) return proj_down, proj_up, qweight, wscales Assistant
I will start by listing the files in
C:\nunchaku\nunchaku\opsand readingC:\nunchaku\nunchaku\ops\quantize.pyto check for any existing quantization logic. Then, I will write a script to analyze the provided.ptfiles to understand the relationship betweenweight,smooth_factor,proj_up, andproj_down.Assistant
I will write a Python script named
analyze_tensors.pyto load and analyze the provided tensor files. This script will inspect the shapes, data types, and statistics ofweight,smooth_factor,proj_up, andproj_down, and then evaluate the reconstruction accuracy by comparing the product ofproj_upandproj_downagainst the smoothed weight. Finally, I will run this script to gather the necessary insights.Assistant
I will update
analyze_tensors.pyto correctly transposeproj_downbefore multiplication, ensuring the shapes align for reconstruction. I'll then calculate the reconstruction error and examine the Gram matrices ofproj_upandproj_downto estimate the singular valuesSand verify orthogonality. Finally, I will run the updated script.Assistant
I will search for the string "proj_down" within the
C:\nunchakudirectory to find where this tensor is utilized, which should help me infer the relationship betweenproj_upandproj_down.Assistant
I will update
analyze_tensors.pyto print detailed statistics (min, max, mean, std) forweight,smooth_factor,proj_up,proj_down,target, andreconto better understand their magnitudes and identify any discrepancies. Then, I will run the updated script.Assistant
I will add code to
analyze_tensors.pyto perform Singular Value Decomposition (SVD) onweight * smoothand print the top singular values. I'll then calculate the cosine similarity between the singular vectors and the providedproj_upandproj_downtensors to check for alignment. Finally, I will run the updated script.Assistant
I will update
analyze_tensors.pyto test ifrecon(calculated asproj_up @ proj_down.T) approximatesweightwhen scaled bysmooth_factor(either divided or multiplied). I'll also check ifreconapproximatesweightdirectly without any smoothing, calculating MSE and relative error for each case to identify the correct relationship. Finally, I will run the updated script.