5/31
Part 1 of 6 · What LoRA trainsLearn and do

A squeezes the input to r numbers, and B expands it back

Here is the layer as a module, with the branch and the scale you just met, wrapped around a small nn.Linear(16, 12):

import math

import torch
from torch import nn


class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r: int, alpha: float) -> None:
        super().__init__()
        # W and b stay frozen
        self.base = base.requires_grad_(False)
        d_in, d_out = base.in_features, base.out_features
        self.A = nn.Parameter(torch.randn(r, d_in) / math.sqrt(d_in))
        self.B = nn.Parameter(torch.zeros(d_out, r))
        self.scale = alpha / r

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """x: (..., in). Returns (..., out)."""
        return self.base(x) + self.scale * (x @ self.A.T @ self.B.T)


torch.manual_seed(0)
lora = LoRALinear(nn.Linear(16, 12), r=4, alpha=8.0)
# 5 rows of input
x = torch.randn(5, 16)
print(tuple(lora.A.shape), tuple(lora.B.shape))
(4, 16) (12, 4)

Every shape, with ... for any leading axes such as batch and time:

TensorShapeWhat it is
x(..., in)the layer's input
base.weight(out, in)the pretrained WW, frozen
A(r, in)trainable, random at the start
B(out, r)trainable, zero at the start
x @ A.T(..., r)the input squeezed to rr numbers
x @ A.T @ B.T(..., out)the update's output, added to base(x)
B @ A(out, in)ΔW\Delta W itself, built only to merge

PyTorch stores the weight as (out, in). The paper calls it d×kd \times k, so dd is out and kk is in. BABA has the same shape as WW.

The paper works on a column vector xx. PyTorch works on rows, x @ W.T + b. On rows, the forward pass reads:

y=xW⊤+b+αr xA⊤B⊤y = xW^\top + b + \frac{\alpha}{r}\, xA^\top B^\top

In the editor is the LoRALinear from above, wrapped around a layer with 64 inputs and 48 outputs, at rank 8. x is a batch of 10 rows. Set squeezed: x after A alone. Set out: the wrapped layer's output for x, and trainable: how many numbers A and B hold together.