I will search for the string "proj_down" in the codebase to identify the code responsible for generating this parameter.
Assistant
I will search for "SVD" in the codebase to find the relevant decomposition logic.
Assistant
I will read deepcompressor/calib/lowrank.py and deepcompressor/nn/patch/lowrank.py to understand how the low-rank branch is calibrated and stored, which should explain the computation of proj_down and proj_up.
Assistant
I will read deepcompressor/calib/smooth.py to understand how smooth_factor is computed and applied.
Assistant
I will read deepcompressor/quantizer/processor.py to find the quantize_with_low_rank method and understand how the weight is split into quantized and low-rank parts.
Assistant
I will read deepcompressor/backend/nunchaku/convert.py to understand how the internal representations are converted to the final keys like proj_down, proj_up, qweight, and wscales. I'll also look at deepcompressor/quantizer/impl/base.py to understand the QuantTensor structure.
Assistant
I will read deepcompressor/backend/nunchaku/utils.py to confirm how the weights are transformed, specifically looking for any transpositions or layout changes in convert_to_nunchaku_w4x4y16_linear_weight that would explain the shape [3072, 128] for proj_down.
Assistant
Based on the code analysis, specifically deepcompressor/calib/smooth.py, deepcompressor/quantizer/processor.py, deepcompressor/nn/patch/lowrank.py, and deepcompressor/backend/nunchaku/convert.py, here is how the parameters are computed.
The SVDQuant method decomposes the "smoothed" weight matrix into a low-rank component (captured by proj_up and proj_down) and a residual component (captured by qweight and wscales).
1. Smoothing (using smooth_factor)
First, the original weight matrix W (shape [Cout,C) is "smoothed" to reduce quantization difficulty. The (, shape ) acts as a scaling factor for input channels.
User
Read @quantize_nunchaku_borrow.py , which is a simplified quantization script that borrows smooth_factor from an alrady quantized model rather than computing it from input data. Is there any difference in computing proj_down, proj_up, qweight, wscales between DeepCompressor and this script?
--- Content from referenced files ---
Content from @quantize_nunchaku_borrow.py:
#!/usr/bin/env python3
import 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
def quantize_residual(residual):
group_size = 64
N, K = residual.shape
assert K % group_size == 0
assert residual.dtype == torch.float32
code
Assistant
There are significant differences between the official DeepCompressor implementation and the simplified @quantize_nunchaku_borrow.py script. The script fails to perform the specific memory layout permutations (packing) required by the Nunchaku inference kernel and uses a different integer encoding for quantized weights.
Here is a detailed breakdown of the differences:
1. Low-Rank Factors (proj_up, proj_down)
Singular Value Distribution:
DeepCompressor: Assigns the full singular values (S) to the "Up" projection.
proj_up: U⋅S
proj_down: V (before Nunchaku conversion adjustments)
User
I've fixed the mapping from -8..7 to 0..15, and we assume that the shapes do not need padding. The script does wscales = torch.clamp(wscales, min=1e-5). Does DeepCompressor do the same?
Assistant
I will search for the scale calculation logic in deepcompressor/data/scale.py to see if it includes a clamping operation similar to torch.clamp(wscales, min=1e-5).
Assistant
I will search for the scale quantization logic in deepcompressor/quantizer/impl/scale.py or similar files, as QuantScale.remove_zero only replaces zeros with ones. I'll start by listing the contents of deepcompressor/quantizer/impl/ to locate the relevant file.
Assistant
I'll examine deepcompressor/quantizer/impl/scale.py to understand how the scale is computed, since deepcompressor/quantizer/impl/ contains a file with that name.
Assistant
In deepcompressor/quantizer/impl/scale.py, the quantize_scale function calls scale.remove_zero() at the end, which, as previously seen in deepcompressor/data/scale.py, replaces all zeros with ones. This behavior is distinct from the script's torch.clamp(wscales, min=1e-5) and suggests a difference in how zero scales are handled. To confirm if there are any other clamping operations, I'll search the codebase for usages of clamp.
Assistant
Yes, DeepCompressor handles near-zero or zero scales differently than the script. Instead of using torch.clamp(wscales, min=1e-5), it uses scale.remove_zero(), which specifically replaces values exactly equal to zero with 1.0.
While both approaches aim to prevent division by zero, the script's 1e-5 floor is much more aggressive and affects very small (but non-zero) scales, whereas DeepCompressor only intervenes when a scale is exactly zero. Additionally, DeepCompressor uses clamping elsewhere (like tensor.clamp_) to ensure values stay within the legal range for the specific QuantDataType being used.
User
The script does wscales = wscales / 7 and qweight = torch.clamp(torch.round(qweight).to(torch.int32), -8, 7). Does it mean that qweight can never be -8 at this point, and 1/16 of the quantization space is wasted? Does DeepCompressor do the same?
Assistant
I will read deepcompressor/quantizer/impl/simple.py to see how simple_quantize works and how it utilizes the quantization range, specifically looking for how the quantization range is determined and applied. I will also check deepcompressor/quantizer/impl/scale.py to see how scales are calculated.
Assistant
Yes, DeepCompressor behaves similarly in that it clamps the quantized values to the target quantization range, but the implementation details differ slightly.
Here, the wscales are normalized by dividing by 7 (the max absolute value for a symmetric range like [−7,7]). However, the range is clamped to [−8,7]. Since the scale is derived based on the max value 7, the value -8 (=−1.14×7) is indeed unreachable under normal symmetric quantization where the max absolute value determines the scale. This effectively wastes the code point -8, or 1/16th of the 4-bit space.
It also clamps to the quant_range. If the quantization configuration specifies a standard symmetric 4-bit integer range ([−8,7]), but the scale is computed based on the symmetric maximum (7), then the outcome is the same: the value -8 is never produced for symmetric inputs.
However, DeepCompressor supports various quantization types (QuantDataType). If QuantDataType is set to an asymmetric mode or if the scale logic explicitly accounts for the full dynamic range including the minimum value (which it often does in range-based quantization), it might utilize the -8 value. But in the default symmetric quantization case typically used for weights, yes, this inefficiency (wasting the -8 code point) is a common characteristic shared by both implementations to preserve symmetry around zero.
So, in the context of standard symmetric 4-bit weight quantization: Yes, DeepCompressor also effectively "wastes" the -8 value to ensure a symmetric range around zero.
User
The script also does AWQ quantization for some layers, where it computes qweight, wscales, wzeros from weight. Does DeepCompressor do this? Is there any difference in computing qweight, wscales, wzeros between DeepCompressor and this script?
Assistant
I will search for "AWQ" in the codebase to see how it is implemented in DeepCompressor. Then I will look for the AWQ quantization kernel or configuration to see how qweight, wscales, and wzeros are computed. I'll compare this with the script's implementation.
Assistant
I will read examples/llm/configs/awq.yaml to see the configuration for AWQ. I'll also check deepcompressor/quantizer/kernel/ to see if there is an AWQ implementation. The search result didn't show an awq.py in deepcompressor/quantizer/kernel/, but there might be a related file. I'll list the directory first.
Assistant
I will check deepcompressor/quantizer/kernel/gptq.py and deepcompressor/quantizer/kernel/rtn.py to see if they support AWQ-like quantization. The awq.yaml file configures weight quantization (wgts) with uint4, PostScale zero point, and group shape [1, 128]. It also enables smoothing (enable_smooth: true). AWQ primarily relies on activation-aware scaling (smoothing) followed by weight quantization.
The script quantize_nunchaku_borrow.py uses quantize_awq_layer which computes wscales and wzeros from weights, then quantizes weights. It uses pack_awq_qweight for packing.
I need to find where the packing happens in DeepCompressor for AWQ compatibility. The search results pointed to deepcompressor/backend/tinychat/linear.py and deepcompressor/backend/tinychat/utils.py. I'll check deepcompressor/backend/tinychat/utils.py for packing logic. I'll also read deepcompressor/backend/tinychat/convert.py if it exists, as convert.py usually handles model conversion and packing.
Assistant
Yes, DeepCompressor also computes qweight, wscales, and wzeros (often referred to as scaled_zeros in its output), but there are differences in implementation details compared to the script, primarily due to the specific packing requirements of the target inference engine (TinyChat).
Differences in Implementation:
Zero Point Handling (wzeros):
DeepCompressor: Explicitly handles zero points (zero tensor), which can be pre-scaled or post-scaled. The convert_to_tinychat_w4x16y16_linear_weight function converts these zeros into a format compatible with TinyChat (scaled_zeros). It calculates _zero (which becomes scaled_zeros) as zero.view(oc, ng).t().to(dtype=dtype).neg_(). This implies it stores the negative of the zero point, potentially pre-multiplied by the scale if zero_pre_scaled is True.
Script: Calculates wzeros simply as w_min (the minimum value of the weight group). It then subtracts this wzeros from the weight before scaling: qweight = (weight - wzeros) / wscales.
Packing (qweight):
DeepCompressor: Uses a specific pack_w4 function in deepcompressor/backend/tinychat/utils.py. This function reorders 4-bit elements within 32-bit integers using a complex permutation:
While both target 4-bit packing, the of the packed integers will likely differ, making weights packed by the script incompatible with the standard TinyChat kernel expected by DeepCompressor's backend.
User
In DeepCompressor, what code computes wscales and wzeros from the weight matrix?
Assistant
I will read deepcompressor/data/range.py to understand the DynamicRange.measure method and deepcompressor/quantizer/impl/info.py to see how quantization information is constructed, which will help identify the code that computes wscales and wzeros from the weight matrix.
Assistant
In DeepCompressor, the computation of wscales and wzeros from the weight matrix is handled by the QuantScaleInfo.quantize method (found in deepcompressor/quantizer/impl/scale.py). This method follows a specific sequence of logic:
1. Dynamic Range Measurement (DynamicRange.measure)
If scales are not pre-provided, the code first measures the dynamic range of the weight matrix (reshaped into quantization groups) using DynamicRange.measure (found in deepcompressor/data/range.py):
It also supports a ratio (e.g., for AWQ-style clipping/scaling) that can shrink or expand these measured ranges.
2. Computing wscales
Back in QuantScaleInfo.quantize, the dynamic_span is converted into a quantization scale by dividing it by the target quantization range's span:
python
# dynamic_span = (max - min) if asymmetric else max
linear_scale = dynamic_span / self.linear_tensor_quant_span
This linear_scale is then further quantized if multiple levels of scales (e.g., float scales quantized to integers) are configured.
3. Computing wzeros
The zero point is calculated based on the zero_domain. For standard asymmetric quantization:
Pre-Scale Domain (standard integer quantization):
python
zero = self.tensor_quant_range.min - dynamic_range.min / s.data
Post-Scale Domain:
python
zero = self.tensor_quant_range.min * s.data - dynamic_range.min
The resulting zero is then rounded/quantized using simple_quantize.
Summary Comparison with the Script
wscales: While the script uses amax / 7, DeepCompressor uses amax / linear_tensor_quant_span (where the span is derived from the QuantDataType's max value).
wzeros: The script uses w_min, whereas DeepCompressor computes a zero point that maps the minimum value to the target range's minimum (e.g., 0 for uint4).
Flexibility:DeepCompressor's version is much more generic, handling different ZeroPointDomains and hierarchical/quantized scales, whereas the script is hardcoded for a single specific use case.
smooth_factor is computed during calibration using activation and weight statistics (spans) to balance outliers between them. It is calculated as s=span(W)βspan(X)α (where α,β are hyperparameters).
2. SVD Decomposition (proj_down, proj_up)
The smoothed weight matrix is decomposed using Singular Value Decomposition (SVD), keeping only the top-r ranks (e.g., r=128).
U,S,VT=SVD(Wsmooth)
proj_up corresponds to the left singular vectors scaled by the singular values.
Computation: proj_up=U[:,:r]⋅diag(S[:r])
Shape: [Cout,r] (e.g., [9216,128])
This maps the low-rank intermediate state back to the output dimension.
proj_down corresponds to the right singular vectors, but un-smoothed so it can be applied directly to the original input X.
Computation: proj_down_internal=V[:r,:]T
3. Quantization (qweight, wscales)
The low-rank approximation is subtracted from the smoothed weight to get the residual, which is then quantized.
Wresidual=Wsmooth−(U[:,:r]⋅S[:r])⋅V[:r,:]T
wscales are the quantization scales computed for Wresidual.
Computation: Scales are typically derived from the max absolute value of Wresidual within each quantization group (e.g., group size 64 or 128).
Storage: Packed/reordered for the Nunchaku kernel. The shape [48,9216] in your example likely represents [Cin/group_size,C (or a similar packed layout).
qweight is the integer-quantized residual.
Computation: qweight=round(Wresidual/wscales)
Storage: The 4-bit integers are packed into larger integer types (e.g., INT8 or INT32) and reordered for the hardware kernel.
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model-a", type=str, help="SVDQ model to borrow")
parser.add_argument("--model-b", type=str, help="BF16 model to quantize")
parser.add_argument("--output", type=str)
args = parser.parse_args()
code
tensors_c = {}
with (
safetensors.safe_open(args.model_a, framework="pt") as f_a,
safetensors.safe_open(args.model_b, framework="pt") as f_b,
):
# Copy non-transformer block parameters from B to C
for k in f_b.keys():
if not k.startswith("transformer_blocks."):
tensors_c[k] = f_b.get_tensor(k)
# Process 60 transformer blocks
for i in tqdm(range(60)):
block_prefix = f"transformer_blocks.{i}."
def get_a(name):
return f_a.get_tensor(block_prefix + name)
def get_b(name):
return f_b.get_tensor(block_prefix + name)
# Quantize SVDQ layers
svdq_layers = [
(
"attn.to_qkv",
[
"attn.to_q.weight",
"attn.to_k.weight",
"attn.to_v.weight",
],
[
"attn.to_q.bias",
"attn.to_k.bias",
"attn.to_v.bias",
],
),
(
"attn.add_qkv_proj",
[
"attn.add_q_proj.weight",
"attn.add_k_proj.weight",
"attn.add_v_proj.weight",
],
[
"attn.add_q_proj.bias",
"attn.add_k_proj.bias",
"attn.add_v_proj.bias",
],
),
(
"attn.to_out.0",
["attn.to_out.0.weight"],
["attn.to_out.0.bias"],
),
(
"attn.to_add_out",
["attn.to_add_out.weight"],
["attn.to_add_out.bias"],
),
(
"img_mlp.net.0.proj",
["img_mlp.net.0.proj.weight"],
["img_mlp.net.0.proj.bias"],
),
(
"img_mlp.net.2",
["img_mlp.net.2.weight"],
["img_mlp.net.2.bias"],
),
(
"txt_mlp.net.0.proj",
["txt_mlp.net.0.proj.weight"],
["txt_mlp.net.0.proj.bias"],
),
(
"txt_mlp.net.2",
["txt_mlp.net.2.weight"],
["txt_mlp.net.2.bias"],
),
]
for target_name, src_weights, src_biases in svdq_layers:
if len(src_weights) > 1:
weight = torch.cat([get_b(x) for x in src_weights], dim=0)
bias = torch.cat([get_b(x) for x in src_biases], dim=0)
else:
weight = get_b(src_weights[0])
bias = get_b(src_biases[0])
smooth_factor = get_a(f"{target_name}.smooth_factor")
device = "cuda"
outs = quantize_svdq_layer(weight.to(device), smooth_factor.to(device))
outs = [x.to("cpu") for x in outs]
proj_down, proj_up, qweight, wscales = outs
base = block_prefix + target_name
tensors_c[f"{base}.bias"] = bias
tensors_c[f"{base}.proj_down"] = proj_down.contiguous()
tensors_c[f"{base}.proj_up"] = proj_up.contiguous()
tensors_c[f"{base}.qweight"] = qweight.contiguous()
tensors_c[f"{base}.wscales"] = wscales.contiguous()
tensors_c[f"{base}.smooth_factor"] = smooth_factor
# Quantize AWQ layers
awq_layers = ["img_mod.1", "txt_mod.1"]
for name in awq_layers:
weight = get_b(f"{name}.weight")
bias = get_b(f"{name}.bias")
device = "cuda"
outs = quantize_awq_layer(weight.to(device))
outs = [x.to("cpu") for x in outs]
qweight, wscales, wzeros = outs
base = block_prefix + name
tensors_c[f"{base}.bias"] = bias
tensors_c[f"{base}.qweight"] = qweight.contiguous()
tensors_c[f"{base}.wscales"] = wscales.contiguous()
tensors_c[f"{base}.wzeros"] = wzeros.contiguous()
# Copy other parameters
norms = [
"attn.norm_k.weight",
"attn.norm_q.weight",
"attn.norm_added_k.weight",
"attn.norm_added_q.weight",
]
for name in norms:
tensors_c[block_prefix + name] = get_b(name)
print(f"Saving model to {args.output}...")
safetensors.torch.save_file(tensors_c, args.output, metadata=f_a.metadata())
print("Done")
if name == "main":
main()
--- End of content ---
T
Script: Splits the singular values (S) evenly between both projections.
proj_up: U⋅S
proj_down: VT⋅S
Note: Mathematically, the product UVT remains the same, but the individual tensor values differ.
Packing & Layout (Critical):
DeepCompressor: Uses packer.pack_lowrank_weight to apply complex padding and permutations (tiling) to optimize for Tensor Core access patterns.
Script: Merely transposes proj_down (.T) and leaves proj_up as is. This will likely lead to garbage output in the Nunchaku kernel.
Smoothing Adjustment:
DeepCompressor: In convert.py, it explicitly un-smooths the down projection (divides by smooth_factor) if smoothing is not fused in the kernel. This ensures proj_down works correctly on the input activation.
Script: Calculates SVD on the smoothed weight (W⋅s) and saves the resulting factors directly. It effectively produces factors that expect a smoothed input (or produces a scaled result), but it does not account for the specific input scaling convention (s−1X) used in the main branch of the Nunchaku kernel.
2. Weight Quantization (qweight)
Integer Encoding:
DeepCompressor: Uses standard 2's complement representation for 4-bit integers.
Result: The integer values stored in the bit-packed tensor are completely different.
Packing:
Both scripts use similar permutation indices (0, 5, 6, 1, ...) for the 4-bit packing, so the block layout of the quantized integers appears compatible, provided the integer values themselves were correct.
3. Scales (wscales)
Packing & Layout (Critical):
DeepCompressor: Uses packer.pack_scale which performs an intricate reshape and permutation to align scales with the specific threads/lanes loading them in the Nunchaku CUDA kernel.
Script: Simply computes the max value and transposes the result (.squeeze(-1).T).
Result: The scales will be read incorrectly by the inference kernel, leading to incorrect dequantization.
Summary
The @quantize_nunchaku_borrow.py script is incomplete and incompatible with the Nunchaku inference engine. While it correctly identifies the layers and borrows the smooth_factor, it fails to:
Pack the low-rank and scale tensors into the hardware-optimized layout.
Encode the 4-bit integers using the correct 2's complement format.
Distribute SVD singular values and handle un-smoothing according to the official convention.
layout and order
Scale Layout (wscales):
DeepCompressor: Transposes scales (scale.view(oc, ng).t()) to match the kernel's expectation where scales are often loaded column-wise or in a specific tiled format corresponding to the packed weights.
Script: Also performs a transpose (wscales.squeeze(-1).T), so this part might be similar in intent, but given the differences in weight packing, the alignment with weight groups must be verified against the specific kernel version.
Summary:
While both methods aim to produce qweight, wscales, and wzeros for AWQ, DeepCompressor's implementation is strictly coupled to the TinyChat inference engine's kernel data layout. The script uses a simplified packing scheme that is likely incompatible with the official TinyChat kernels used by DeepCompressor. The handling of zero points also differs slightly in terms of storage (negative vs. positive values).
⋅
diag(1/s)
Storage: The Nunchaku backend packs this tensor in a transposed and tiled format for efficiency. The stored shape [Cin,r] (e.g., [3072,128]) represents the transpose of the logical projection matrix [r,Cin].
Logical Operation: It maps the original input (dimension Cin) down to rank r.