When a pretrained model needs to handle a new task, retraining the whole model can be costly. Low-rank adaptation (LoRA) instead trains small update matrices while leaving the original weights fixed. The resulting adapter can be saved separately and applied to the base model. section 5.3.5 section 9.3.2
LoRA represents a weight update as ΔW = A × B. For a 100 × 100 update, choosing rank 2 gives matrices of 100 × 2 and 2 × 100: 400 trainable elements instead of 10,000. The update can run in parallel with the original layer rather than replacing its weights. section 5.3.5 section 3.3.1
Listing 9.6 Low-rank adaptation
class LoRALayer(nn.Module): #1
def __init__(self, in_dim, out_dim, rank, alpha):
super().__init__()
standard_deviation = 1 / torch.sqrt(torch.tensor(rank).float())
self.A = nn.Parameter(
torch.randn(in_dim, rank) * standard_deviation
)
self.B = nn.Parameter(torch.zeros(rank, out_dim))
self.alpha = alpha
def forward(self, x):
x = self.alpha * (x @ self.A @ self.B)
return x
class LinearWithLoRA(nn.Module):
def __init__(self, linear, rank, alpha):
super().__init__()
self.linear = linear
self.lora = LoRALayer(
linear.in_features, linear.out_features, rank, alpha
)
def forward(self, x):
return self.linear(x) + self.lora(x)
class LlamaBlock(nn.Module): #2
def __init__(self, config):
super().__init__()
self.config = config
self.rms = RMSNormalization(
(config["d_model"], config["d_model"])
).to(device)
self.attention = RoPEMaskedMultiheadAttention(config).to(device)
self.feedforward = nn.Sequential(
LinearWithLoRA(config["d_model"], config["d_model"]), #3
SwiGLU(config["d_model"]),
).to(device)
def forward(self, x):
x = self.rms(x)
x = x + self.attention(x)
x = self.rms(x)
x = x + self.feedforward(x)
return x
class SimpleLlama(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.embedding = nn.Embedding(
config["vocab_size"], config["d_model"]
)
self.llama_blocks = nn.Sequential(
OrderedDict(
[
(f"llama_{i}", LlamaBlock(config))
for i in range(config["n_layers"])
]
)
)
self.ffn = nn.Sequential(
LinearWithLoRA(config["d_model"], config["d_model"]), #4
SwiGLU(config["d_model"]),
LinearWithLoRA(config["d_model"], config["vocab_size"]), #5
)
print(
f"model params: {sum([m.numel() for m in self.parameters()])}"
)
def forward(self, idx, targets=None):
x = self.embedding(idx)
x = self.llama_blocks(x)
logits = self.ffn(x)
if targets is None:
return logits
else:
loss = F.cross_entropy(
logits.view(-1, self.config["vocab_size"]),
targets.view(-1),
ignore_index=tokenizer.pad_token_id,
reduction="sum",
)
return logits, loss
dataset = load_dataset( #6
"text",
data_files={
"train": ["../../data/Lima-train.csv"],
"val": ["../../data/Lima-test.csv"],
},
streaming=True,
)
encoded_dataset = dataset.map(
lambda examples: tokenizer(
examples["text"],
padding=True,
max_length=128,
truncation=True,
\]] return_tensors="pt",
),
batched=True,
)
train_data = iter(encoded_dataset["train"].shuffle())
val_data = iter(encoded_dataset["val"].shuffle())
train_data = cycle(train_data)
val_data = cycle(val_data)
llama.to("cpu") #7
add_lora(llama)
llama.to(device)
parameters = [{"params": list(get_lora_params(llama))}] #8
lora_optimizer = torch.optim.AdamW(parameters, lr=1e-3) #9
train( #10
llama,
lora_optimizer,
scheduler,
data=train_data,
config=MASTER_CONFIG,
lora=True,
print_logs=True,
)
state_dict = llama.state_dict() #11
lora_state_dict = {k: v for k, v in state_dict.items() if name_is_lora(k)}
torch.save(llama.state_dict(), "./llama.pth")
torch.save(lora_state_dict, "./lora.pth")
A PyTorch LoRA layer computes a scaled low-rank update and adds it to a linear layer’s output. section 9.3.2
Practical choices:
- Choose the rank as a trade-off. A higher rank allows a more complex update but saves less memory; evaluate the result for the task rather than assuming it will preserve accuracy. section 5.3.5
- Keep task or domain adapters separate when their changes should not bleed into one another. The base model remains the shared starting point. section 5.3.5
- For inference, either load the adapter on top of the base model or merge its layers into the model. Separate state dictionaries make the first option possible. section 9.3.2
- Use a parameter-efficient fine-tuning library such as Hugging Face PEFT to get started, or implement the adapter directly when you need control over the model layers. section 3.3.1 section 9.3.2
Updating a Llama-style model
A model that has fallen short on a task can be adapted using a new instruction dataset rather than retrained from scratch. One implementation uses rank 16, saves the model and adapter separately, and merges the adapter for inference. Its generated text changes but remains incoherent—a reminder to check output quality, not just whether training ran. section 9.3.2









