Skip to main content

Encoders with LoRA

laplacekit puts a Laplace approximation on the LoRA adapters of a fine-tuned encoder, a BERT sequence classifier say, and leaves the frozen weights alone. Here we build a tiny random BERT from a config, so nothing downloads, and ask for KFAC on its adapters and head.

import torch
import transformers
from peft import LoraConfig, get_peft_model
from torch import nn
from transformers import BertConfig, BertForSequenceClassification

import hessiankit as hk

transformers.logging.set_verbosity_error()
torch.manual_seed(0)

config = BertConfig(
    vocab_size=100,
    hidden_size=32,
    num_hidden_layers=2,
    num_attention_heads=2,
    intermediate_size=64,
    num_labels=3,
)
model = BertForSequenceClassification(config)
lora = LoraConfig(r=4, target_modules=["query", "value"], task_type="SEQ_CLS")
model = get_peft_model(model, lora).double().eval()

# peft starts lora_B at zero; a fine-tuned adapter isn't.
for name, p in model.named_parameters():
    if "lora_B" in name:
        nn.init.normal_(p, std=0.1)


def batch(n=8, t=12):
    """Right-padded token ids, the attention mask and labels."""

    lengths = torch.randint(4, t + 1, (n,))
    mask = (torch.arange(t) < lengths[:, None]).long()
    ids = torch.randint(1, 100, (n, t)) * mask
    return {"input_ids": ids, "attention_mask": mask}, torch.randint(0, 3, (n,))


batches = [batch() for _ in range(4)]
likelihood = hk.Categorical()
options = dict(
    forward=lambda m, x: m(**x).logits,
    position_mask=lambda x: x["attention_mask"],
)

print(hk.plan(model, batches[0], likelihood, **options))
hk.plan: kfac on output [8, 3], event axes (1,), 1 position per example
layer                                                                      type    T   params  A   G   mask
base_model.model.bert.encoder.layer.0.attention.self.query.lora_A.default  Linear  12  128     32  4   position_mask
base_model.model.bert.encoder.layer.0.attention.self.query.lora_B.default  Linear  12  128     4   32  position_mask
base_model.model.bert.encoder.layer.0.attention.self.value.lora_A.default  Linear  12  128     32  4   position_mask
base_model.model.bert.encoder.layer.0.attention.self.value.lora_B.default  Linear  12  128     4   32  position_mask
base_model.model.bert.encoder.layer.1.attention.self.query.lora_A.default  Linear  12  128     32  4   position_mask
base_model.model.bert.encoder.layer.1.attention.self.query.lora_B.default  Linear  12  128     4   32  position_mask
base_model.model.bert.encoder.layer.1.attention.self.value.lora_A.default  Linear  12  128     32  4   position_mask
base_model.model.bert.encoder.layer.1.attention.self.value.lora_B.default  Linear  12  128     4   32  position_mask
base_model.model.classifier.modules_to_save.default                        Linear  1   99      33  3   none
fisher: exact (3 backward passes per batch, at most EXACT_MAX_PASSES = 64)
form: expand (reduce is opt-in: it cancels to zero when positions enter with opposite signs)
backward passes per batch: 3
memory: 73.6 KiB in float64

A Hugging Face model takes a dict and returns an object, so forward picks the logits out. position_mask returns the attention mask, so padded tokens add nothing to any factor.

The layers are the nn.Linear inside each adapter and the head that peft trains; the frozen BERT weights aren’t trainable, so they aren’t listed at all. The adapters see 12 tokens per sequence while the output has one position. KFAC takes its expand form, which treats the tokens as examples, and three classes keep the Fisher exact.

The call itself:

result = hk.kfac(model, batches, likelihood, **options)

head = "base_model.model.classifier.modules_to_save.default"
print(len(result.kron), result.kron[head].total_weight, result.uncovered)
9 tensor(32., dtype=torch.float64) {}

A check that the padding stays out: we change the token ids at every padded position and compute again. The attention mask hides them from the real tokens and position_mask hides them from the factors, so nothing changes:

noisy = []

for x, y in batches:
    ids = x["input_ids"].where(x["attention_mask"].bool(), 7)
    noisy.append(({**x, "input_ids": ids}, y))

again = hk.kfac(model, noisy, likelihood, **options)

same = [
    torch.allclose(again.kron[k].a, result.kron[k].a)
    and torch.allclose(again.kron[k].g, result.kron[k].g)
    for k in result.kron
]
print(all(same))
True

When to override

  • Without position_mask, the padded tokens count in every adapter’s \(A\) and in its number of positions. Always pass the attention mask when there is padding.
  • form="reduce" sums each sequence’s tokens before the outer product, which is cheaper and is the form Eschenhagen et al. (2023) derive for one loss per sequence. It is opt-in, since it cancels to zero when positions enter the output with opposite signs (Reward models).
  • nn.MultiheadAttention, nn.Embedding, norms and GPT-2’s Conv1D have no rule; trainable parameters in them are listed under uncovered. Pass rules= with a rule of your own to cover them.