Skip to content

SVD-LLM low-rank compression

At a glance

SVD-LLM / truncated-SVD factorization of linear maps (see LowRankConfig).

Registered name Family Saves Lossless Trainable Configuration
lowrank weight-compression weight memory or compute no no LowRankConfig

Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: real · sglang: no · trtllm: no · vllm: real

lowrank replaces each selected linear map W (m outputs, n inputs) of the decoder layers by two thin maps, down from n to k features and up from k to m, with the original bias on up. The rank is k = floor((1 - c) m n / (m + n)), so every map loses at least the fraction c = compression of its parameters. A map whose rank would save nothing stays dense. SVD-LLM (Wang et al., 2025) chooses the factors from the calibration inputs: with S the Cholesky factor of the input Gram matrix X^T X, it truncates the singular value decomposition of W S and folds S^-1 back into the factors. The output error ||(W - W') X^T||_F^2 is then the sum of the dropped squared singular values, which makes truncation optimal for the calibration inputs. The svd method truncates W itself and reads no data. Nothing is trained, and the result is lossy.

The saving is real: the two factors are plain nn.Linear maps with fewer parameters, on transformers, on vLLM and in an ONNX export, which writes the two factors as two MatMul nodes (MatMulNBits when they are quantized). SGLang, llama.cpp, MLX and TensorRT-LLM build each linear map from one weight, so their exports refuse the technique instead of multiplying the factors out. The time saved follows the parameter count only when the two thin matrix products are not bound by kernel launches, which holds for large models more than for small ones. Factorization rewrites the base model in place, so the technique cannot be detached.

Setup

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

import economize

device = "cuda" if torch.cuda.is_available() else "cpu"
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map=device)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
ids = tokenizer("Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. "
                "How many clips did Natalia sell altogether?", return_tensors="pt").input_ids.to(device)

Training data is a flat file of uint32 token ids, the format of nanoGPT-style pretraining shards, and calibration data is a [N, S] tensor of token ids. Both are made here from GSM8K:

import numpy as np
from datasets import load_dataset

texts = [f"{row['question']}\n{row['answer']}" for row in load_dataset("openai/gsm8k", "main", split="train")]
tokens = np.concatenate([tokenizer(t + tokenizer.eos_token).input_ids for t in texts]).astype(np.uint32)
tokens[: len(tokens) * 9 // 10].tofile("train.bin")
tokens[len(tokens) * 9 // 10 :].tofile("val.bin")

calibration = torch.from_numpy(tokens[: 128 * 2048].astype(np.int64)).view(128, 2048)

Factorization changes the base model, so measure the perplexity and the parameter count of the full model first:

from economize.train import fixed_windows

windows = fixed_windows("val.bin", 64, 1024).cuda()


@torch.no_grad()
def perplexity(model, windows):
    return torch.stack([model(w[None], labels=w[None]).loss for w in windows]).float().mean().exp().item()


dense_ppl, dense_params = perplexity(base, windows), base.num_parameters()

Quick start

SVD-LLM at 20% compression factorizes every linear map of the decoder layers:

from economize.techniques.lowrank import LowRankConfig

model = economize.apply(base, LowRankConfig(method="svd_llm", compression=0.2), calibration=calibration)

summary = model.techniques["lowrank"].summary
print(summary["params_before"], summary["params_after"])   # parameters of the factorized maps
print(summary["ranks"]["12.mlp.down_proj"], summary["kept_dense"])
print(dense_params, model.unwrap().num_parameters())
print(dense_ppl, perplexity(model, windows))

summary["ranks"] maps every factorized map ("<layer>.<name>", 1-indexed layers) to its rank, and summary["kept_dense"] counts the maps left dense.

Options

targets, exclude and layers restrict the factorization. The MLP holds most of the parameters, and the attention projections of small models are often too narrow to save anything. rank_multiple rounds every rank down to a multiple, for tensor-core friendly shapes or for a following quant with groups of the same size. sequential=True computes each layer's Gram matrix on the outputs of the already factorized layers instead of the original model's:

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, LowRankConfig(compression=0.2, targets=("mlp.*",), rank_multiple=8, sequential=True),
                        calibration=calibration)
print(perplexity(model, windows))

Quality falls quickly with the compression ratio, so measure it over a range before choosing one.

Saving and loading

A checkpoint stores the configuration. Loading factorizes an unmodified base model again with the same calibration data:

model.save_pretrained("qwen-svdllm")

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.load(base, "qwen-svdllm", calibration=calibration)

Combining with other techniques

Low rank runs after pruning and before quantization, so quant sees the two factors as two plain linear maps. With rank_multiple=128, every up factor has a whole number of groups of 128 input columns:

from economize.techniques.quant import QuantConfig

print(economize.compatible("lowrank", "quant"))
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, LowRankConfig(compression=0.2, targets=("mlp.*",), rank_multiple=128),
                        QuantConfig(format="int4", method="gptq", group_size=128), calibration=calibration)
print(perplexity(model, windows))

Serving

vLLM runs the factorized maps with economize's linear method, which computes x @ down^T @ up^T:

from economize.backends.vllm import serving

plan = serving.to_vllm(model, "out/qwen-svdllm")
llm = plan.llm()

Configuration

LowRankConfig dataclass

LowRankConfig(method: str = 'svd_llm', compression: float = 0.2, targets: tuple[str, ...] = ('*',), exclude: tuple[str, ...] = (), layers: tuple[int, ...] = (), rank_multiple: int = 1, sequential: bool = False, offload: bool = False)

Replace linear maps of the decoder layers by two low-rank factors.

Parameters:

Name Type Description Default
method str

Registered factorization: "svd_llm" (default, needs calibration data) or "svd".

'svd_llm'
compression float

Fraction of each matrix's parameters removed (SVD-LLM's "compression ratio"; 0.2 keeps 80%).

0.2
targets tuple[str, ...]

Globs over linear-module names inside a layer.

('*',)
exclude tuple[str, ...]

Globs removed from targets.

()
layers tuple[int, ...]

1-indexed layers to compress; empty means all.

()
rank_multiple int

Round every rank down to a multiple of this (e.g. 128 so that a following quant with group_size=128 can quantize the up factor, or 8/16 for tensor-core friendly shapes).

1
sequential bool

Profile each layer on the compressed model's activations instead of the original model's (the paper profiles the original model).

False
offload bool

Keep calibration activations on the CPU between layers.

False

References

  • Wang, X., Zheng, Y., Wan, Z., & Zhang, M. (2025). SVD-LLM: Truncation-aware singular value decomposition for large language model compression. In International Conference on Learning Representations. https://doi.org/10.48550/arXiv.2403.07378