AI Logic

Model Compression

Low-Rank Factorization

Updated๏ผš

How low-rank factorization works. The left side shows a fully connected layer: the m ร— n weight W is decomposed with singular value decomposition, the top t components are kept, and the layer is replaced with two linear layers of size t ร— n and m ร— t, reducing parameters from mยทn to tยท(m + n). The right side shows a convolutional layer: a d ร— d convolution is split into two stages, d ร— 1 and 1 ร— d, along with the change in computation

Background and Overview

Low-rank factorization is a model compression method that approximates a trained weight matrix (or tensor) with a product of thin matrices or a combination of small tensors, replacing one layer with a stack of lighter layers. It reduces both the number of parameters and the amount of computation.

The weights of deep networks are known to be highly redundant. Denil et al. (2013) showed that about 5% of the weights of a layer are enough to predict the rest quite accurately. If a weight matrix "does not carry as much information as it appears to," it should be possible to re-express it with fewer numbers. Low-rank factorization extracts this redundancy as the linear structure of the matrix.

Its application to convolutional neural networks (CNN) is typically traced to the work that Denton et al. and Jaderberg et al. presented independently in 2014. The survey by Cheng et al. divides model compression methods into four groups: pruning and quantization, low-rank factorization, compact convolutional filter design, and knowledge distillation. Within that taxonomy, low-rank factorization is described as applicable to both fully connected and convolutional layers, and as something that can be derived from a trained model or trained in factorized form from the start.

The idea of expressing a matrix as the product of two thin matrices is also used in other methods. ALBERT splits the vocabulary embedding matrix into two to reduce parameters, and LoRA represents only the change in weights during fine-tuning with a low rank.

Theory (Matrix and Tensor Decomposition)

Fully Connected Layers: Two Layers via Singular Value Decomposition

The weights of a fully connected layer y=Wxy = Wx (WโˆˆRmร—nW \in \mathbb{R}^{m \times n}) are decomposed with singular value decomposition (SVD).

W=USVโŠคW = U S V^\top

The diagonal of SS holds the singular values in descending order. If the singular values decay quickly, an approximation that keeps only the top tt of them is sufficient (Section 3.2.1 of Denton et al.).

W~=UtStVtโŠค,UtโˆˆRmร—t,ย StโˆˆRtร—t,ย VtโˆˆRnร—t\tilde{W} = U_t S_t V_t^\top, \qquad U_t \in \mathbb{R}^{m \times t},\ S_t \in \mathbb{R}^{t \times t},\ V_t \in \mathbb{R}^{n \times t}

The procedure is as follows (left side of the figure at the top).

  1. Compute the singular value decomposition of the trained layer's weight WW.
  2. Choose the rank tt to keep, and extract only the top tt singular values and singular vectors.
  3. Replace the original layer with two layers: an nโ†’tn \to t linear layer (weights StVtโŠคS_t V_t^\top) and a tโ†’mt \to m linear layer (weights UtU_t). No activation function is inserted between them.
  4. Repeat the same for the other layers.
  5. Recover the lost accuracy with fine-tuning.

The number of parameters drops from mnmn to t(m+n)t(m + n), and the number of multiplications per input drops by the same ratio. A reduction is only achieved when t<mnm+nt < \frac{mn}{m + n}, so tt must be sufficiently small.

The approximation error is determined by the magnitude of the discarded singular values. The maximum error is bounded by the largest discarded singular value st+1s_{t+1}.

โˆฅW~xโˆ’Wxโˆฅโ‰คst+1โˆฅxโˆฅ\| \tilde{W}x - Wx \| \le s_{t+1} \| x \|

Singular value decomposition rearranges a matrix in order of its "most influential directions." Keeping only the top tt corresponds to keeping only the main directions and discarding fine components, similar to keeping only the main components in image compression.

Convolutional Layers: Splitting Along Spatial and Channel Directions

The weights of a convolutional layer form a 4D tensor with CC input channels, NN output channels, height dd, and width dd. Scheme 2 of Jaderberg et al. replaces a dร—dd \times d convolution with two stages: a vertical dร—1d \times 1 convolution (Cโ†’KC \to K channels) and a horizontal 1ร—d1 \times d convolution (Kโ†’NK \to N channels) (Eq. (1) in the paper).

Wnโˆ—zโ‰ˆโˆ‘k=1Khnkโˆ—(vkโˆ—z)W_n * z \approx \sum_{k=1}^{K} h_n^k * (v_k * z)

vkv_k are the vertical filters and hnkh_n^k are the horizontal filters. The computation per output pixel drops from NCd2NCd^2 to K(N+C)dK(N + C)d. If KK, NN, and CC are of similar size, this amounts to a speedup of about dd times (right side of the figure at the top).

Lebedev et al. (2015) used CP decomposition, which approximates a 4D tensor with a sum of RR rank-1 tensors.

K(i,j,s,t)โ‰ˆโˆ‘r=1RKx(i,r)โ€‰Ky(j,r)โ€‰Ks(s,r)โ€‰Kt(t,r)K(i, j, s, t) \approx \sum_{r=1}^{R} K^x(i, r)\, K^y(j, r)\, K^s(s, r)\, K^t(t, r)

i,ji, j are the vertical and horizontal positions, ss is the input channel, and tt is the output channel; Kx,Ky,Ks,KtK^x, K^y, K^s, K^t are matrices of size dร—Rd \times R, dร—Rd \times R, Sร—RS \times R, and Tร—RT \times R, respectively (Eq. (4) in the paper). This turns one convolutional layer into a stack of four small convolutions: a 1ร—11 \times 1 that mixes input channels, a vertical one, a horizontal one, and a 1ร—11 \times 1 that produces the output channels. The number of stored values is not the total number of tensor elements but RR times the sum of the lengths along each direction.

Decomposition Choices and Techniques for Preserving Accuracy

Minimizing the error in the weights does not by itself preserve the accuracy of the model. The papers propose techniques that put more weight on the directions that matter for accuracy.

  • Minimize the output error: Jaderberg et al. learned the decomposition to minimize not the difference from the original weights but the difference from the original layer's output when training data is passed through (Eq. (4) in the paper). This avoids spending capacity on directions that are meaningless for the data, and also allows adjustment that accounts for approximation errors already introduced in earlier layers.
  • Weight by the input distribution: Denton et al. showed methods that find the approximation using a distance based on the covariance of the layer inputs, or a distance that emphasizes directions where predictions are likely to go wrong.
  • Fine-tune the upper layers: Denton et al. froze the approximated layer and the layers below it and retrained the upper layers to recover accuracy. Lebedev et al. fine-tuned the entire network, including the decomposed layers, with the original classification loss.
  • Decompose one layer at a time: Decompose one layer and fine-tune, then decompose the next layer once accuracy has recovered. This makes errors less likely to accumulate.

As for the type of decomposition, singular value decomposition is used for fully connected layers, and the scheme above, CP decomposition, Tucker decomposition, and others for convolutional layers. According to the survey by Cheng et al., CP decomposition can be unstable to compute because a best rank-KK approximation may not exist, whereas the decomposition of Tai et al., which uses batch normalization, always has a solution.

Experimental Results

Denton et al. examined the parameter reduction and the increase in error per layer for a 15-layer CNN (4 convolutional layers and 3 fully connected layers) trained on ImageNet (Table 2 of the paper, after fine-tuning).

LayerMethodWeight reductionIncrease in error
Conv layer 1Projection of the color dimension to 6 dimensions3x0.43%
Conv layer 2Clustering + sum of outer products5.3x0.68%
FC layer 1Singular value decomposition (K=250K = 250)13.4x0.84%
FC layer 2Singular value decomposition (K=350K = 350)5.8x0.19%
FC layer 3Singular value decomposition (K=250K = 250)8.1x0.67%

The computation of conv layers 1 and 2 became 2โ€“2.5 times faster on both CPU and GPU while keeping the accuracy drop below 1%. Since most of the parameters are in the fully connected layers, decomposing them is what reduces model size.

Results from other papers are as follows.

PaperTargetResult
Jaderberg et al. (2014)CNN for scene text recognition2.5x speedup with no loss of accuracy, 4.5x with less than 1% drop
Lebedev et al. (2015)CNN for character recognition (36 classes)8.5x speedup of the whole network (CPU), accuracy from 91% to 90.2%
Lebedev et al. (2015)Conv layer 2 of AlexNet3.6x at rank 200 (0.5% drop), 4.5x at rank 140 (about 1% drop)

In Table II of the survey by Cheng et al., VGG-16 achieves a 2.05x speedup and 2.75x compression, at the cost of top-5 accuracy dropping from 90.60% to 90.31% (CP decomposition).

Practical Considerations

  • Choose the rank per layer. The required rank varies greatly between layers. In the experiments of Lebedev et al. as well, conv layer 2 of AlexNet needed a larger rank than the character recognition CNN. Lower the rank gradually and decide based on validation accuracy.
  • The speedup is smaller than the reduction in computation suggests. Denton et al. note that it is often difficult to bring the actual speed close to the theoretical speedup estimated from operation counts. This is because splitting into two layers adds memory traffic and launch overhead. Measure the speed on the actual hardware.
  • The decomposition itself takes effort. Decomposing large layers and optimizing CP decompositions is heavy, and since it proceeds layer by layer, global optimization across layers is not possible (survey by Cheng et al.).
  • It can be combined with quantization and pruning. The matrices after decomposition remain dense, so they can be further quantized.

Accuracy can drop noticeably right after decomposition. Especially with a small rank, use it on the assumption that accuracy will be recovered through fine-tuning. The survey by Cheng et al. also points out that a decomposed model requires extensive retraining to converge to the same point as the original model.

Comparison with Other Methods

The following table compares representative methods for shrinking models from the same perspectives.

MethodWhat it reducesForm of computationCan be built from a trained modelRetraining
Low-rank factorizationMatrix size (into a product of thin matrices)Stays dense; fast with ordinary librariesYesUsually needed
PruningNumber of weights or channelsSparse for weight-level, dense for channel-levelYesUsually needed
QuantizationNumber of bits per valueRequires hardware that supports low-bit computationYesOften not needed
Knowledge distillationOverall model sizeStays as the student modelTrains a new studentNeeded
Depthwise separable convolutionComputation of convolutionsStays denseDesigned and trained from the startTrained from scratch

Depthwise separable convolution is conceptually close to low-rank factorization in that it splits a convolution into spatial and channel directions, and it is used from the start in models such as MobileNet. Low-rank factorization can be seen as a way to reshape an already trained model into a similar form after the fact.

  • To reduce the parameters of a model with large fully connected layers (such as the latter part of older CNNs or the linear layers of a Transformer), low-rank factorization via singular value decomposition is easy to apply.
  • To reliably speed up actual inference, choose low-rank factorization, which speeds things up while keeping dense computation, or channel-level pruning.
  • Since it reduces something different from quantization, which reduces bit width, the two can be combined.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# 1. Turn a fully connected layer into two linear layers via SVD (Section 3.2.1 of Denton et al.)
def factorize_linear(layer: nn.Linear, t: int) -> nn.Sequential:
    W = layer.weight.data                      # (m, n): y = W x
    U, S, Vh = torch.linalg.svd(W, full_matrices=False)
    first = nn.Linear(layer.in_features, t, bias=False)      # n โ†’ t, weights S_t V_tแต€
    second = nn.Linear(t, layer.out_features, bias=layer.bias is not None)  # t โ†’ m, weights U_t
    first.weight.data = S[:t, None] * Vh[:t]   # (t, n)
    second.weight.data = U[:, :t].clone()      # (m, t)
    if layer.bias is not None:
        second.bias.data = layer.bias.data.clone()
    return nn.Sequential(first, second)        # no activation function in between


fc = nn.Linear(1024, 512)
low = factorize_linear(fc, t=64)
x = torch.randn(8, 1024)
print("Parameters:", fc.weight.numel(), "โ†’", sum(p.weight.numel() for p in low))  # 524288 โ†’ 98304
print("Relative error:", ((low(x) - fc(x)).norm() / fc(x).norm()).item())   # random weights have slowly decaying singular values, so the error is large


# 2. Split a convolutional layer into two stages, dร—1 and 1ร—d (Scheme 2 of Jaderberg et al.)
#    the decomposed layers are trained to minimize the difference from the original layer's output (Eq. (4), data reconstruction)
def factorize_conv(conv: nn.Conv2d, K: int) -> nn.Sequential:
    C, N, d = conv.in_channels, conv.out_channels, conv.kernel_size[0]
    p = conv.padding[0]
    vertical = nn.Conv2d(C, K, kernel_size=(d, 1), padding=(p, 0), bias=False)    # C โ†’ K
    horizontal = nn.Conv2d(K, N, kernel_size=(1, d), padding=(0, p), bias=True)   # K โ†’ N
    return nn.Sequential(vertical, horizontal)


conv = nn.Conv2d(48, 64, kernel_size=9, padding=4)
approx = factorize_conv(conv, K=16)
opt = torch.optim.Adam(approx.parameters(), lr=1e-3)
for step in range(200):                        # in practice, use feature maps from training data
    z = torch.randn(4, 48, 24, 24)
    with torch.no_grad():
        target = conv(z)                       # output of the original layer
    loss = (approx(z) - target).pow(2).mean()  # minimize the squared error of the output
    opt.zero_grad(); loss.backward(); opt.step()

print("Conv parameters:", conv.weight.numel(), "โ†’", sum(m.weight.numel() for m in approx))  # 248832 โ†’ 16128
# then insert the decomposed layers into the original network and fine-tune the upper layers

FAQ

Q. How should the rank $t$ be chosen?
A.

There is no fixed value; decide it per layer based on validation accuracy. One rule of thumb is to look at the singular values and check how many of the top ones account for most of the total. However, parameters are reduced only when t<mnm+nt < \frac{mn}{m+n}, and if speed matters, it must be even smaller. In the papers as well, the required rank varied greatly between layers and models.

Q. What is the difference between low-rank factorization and [LoRA](/model-compression/lora)?
A.

Both represent a matrix as a product of thin matrices, but they differ in what is represented. Low-rank factorization replaces the trained weights themselves with a product of thin matrices to make the model smaller. LoRA keeps the weights frozen and represents only the change added during fine-tuning as a product of thin matrices, reducing the number of trainable parameters. LoRA does not make the model itself smaller.

Q. Can it be used for Transformer language models?
A.

Yes. The weights of linear layers are matrices, so they can be turned directly into two linear layers with singular value decomposition. There are also designs like ALBERT that split the large vocabulary embedding matrix into two matrices from the start. However, the rank at which accuracy can be preserved depends on the model and task, so pair it with fine-tuning and evaluation.

References

  1. E. Denton, W. Zaremba, J. Bruna, Y. LeCun, and R. Fergus, "Exploiting Linear Structure Within Convolutional Networks for Efficient Evaluation," arXiv:1404.0736, 2014.
  2. M. Jaderberg, A. Vedaldi, and A. Zisserman, "Speeding up Convolutional Neural Networks with Low Rank Expansions," arXiv:1405.3866, 2014.
  3. V. Lebedev, Y. Ganin, M. Rakhuba, I. Oseledets, and V. Lempitsky, "Speeding-up Convolutional Neural Networks Using Fine-tuned CP-Decomposition," ICLR 2015, arXiv:1412.6553.
  4. Y. Cheng, D. Wang, P. Zhou, and T. Zhang, "A Survey of Model Compression and Acceleration for Deep Neural Networks," IEEE Signal Processing Magazine, arXiv:1710.09282.
  5. M. Gupta and P. Agrawal, "Compression of Deep Learning Models for Text: A Survey," arXiv:2008.05221, 2020.