Skip to main content

LLMs

laplacekit follows Laplace-LoRA: a Laplace approximation on the LoRA adapters of a fine-tuned language model, which calibrates its answers. We take a tiny random Llama-style causal LM with LoRA, built from a config, with the loss on the answer tokens only.

import torch
import transformers
from peft import LoraConfig, get_peft_model
from torch import nn
from transformers import LlamaConfig, LlamaForCausalLM

import hessiankit as hk

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

config = LlamaConfig(
    vocab_size=256,
    hidden_size=32,
    intermediate_size=64,
    num_hidden_layers=2,
    num_attention_heads=4,
    num_key_value_heads=2,
)
model = LlamaForCausalLM(config)
lora = LoraConfig(
    r=4, target_modules=["q_proj", "v_proj"], task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora).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=4, t=16, prompt=6):
    """Right-padded prompts and answers; the labels are the next tokens."""

    lengths = torch.randint(10, t + 1, (n,))
    mask = (torch.arange(t) < lengths[:, None]).long()
    ids = torch.randint(1, 256, (n, t)) * mask

    labels = ids.roll(-1, dims=1).where(mask.roll(-1, dims=1).bool(), -100)
    labels[:, -1] = -100  # nothing follows the last token
    labels[:, : prompt - 1] = -100  # no loss on the prompt

    return {"input_ids": ids, "attention_mask": mask}, labels


batches = [batch() for _ in range(4)]
likelihood = hk.Categorical(ignore_index=-100)
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 [4, 16, 256], event axes (2,), 16 positions per example
layer                                                            type    T   params  A   G   mask
base_model.model.model.layers.0.self_attn.q_proj.lora_A.default  Linear  16  128     32  4   position_mask and output
base_model.model.model.layers.0.self_attn.q_proj.lora_B.default  Linear  16  128     4   32  position_mask and output
base_model.model.model.layers.0.self_attn.v_proj.lora_A.default  Linear  16  128     32  4   position_mask and output
base_model.model.model.layers.0.self_attn.v_proj.lora_B.default  Linear  16  64      4   16  position_mask and output
base_model.model.model.layers.1.self_attn.q_proj.lora_A.default  Linear  16  128     32  4   position_mask and output
base_model.model.model.layers.1.self_attn.q_proj.lora_B.default  Linear  16  128     4   32  position_mask and output
base_model.model.model.layers.1.self_attn.v_proj.lora_A.default  Linear  16  128     32  4   position_mask and output
base_model.model.model.layers.1.self_attn.v_proj.lora_B.default  Linear  16  64      4   16  position_mask and output
fisher: mc, 4 samples (exact would take 4096 backward passes per batch, more than EXACT_MAX_PASSES = 64)
form: expand (reduce is opt-in: it cancels to zero when positions enter with opposite signs)
backward passes per batch: 4
memory: 53.0 KiB in float64

We shift the labels, not the logits: label \(t\) is token \(t + 1\), so the logits keep one position per token, the same as the adapters. Then the -100 labels mask the adapters’ positions too, and plan says position_mask and output: padding and prompt tokens add nothing to any factor.

The output now has 16 positions per sequence, and KFAC takes its expand form. The exact Fisher would take one backward pass per token and word of the vocabulary: \(16 \times 256 = 4096\) per batch here, and a real vocabulary has tens of thousands of words. So the default is Monte Carlo, with four sampled labels per token and four backward passes per batch.

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

name = "base_model.model.model.layers.0.self_attn.v_proj.lora_B.default"
print(len(result.kron), result.kron[name].total_weight)
8 tensor(16., dtype=torch.float64)

Are four samples per token enough? Each sampled label gives a noisy estimate of the Fisher, and the sum runs over every answer token in the data. We compare two seeds, with four samples and with 16:

for samples in (4, 16):
    a, b = (
        hk.kfac(
            model,
            batches,
            likelihood,
            mc_samples=samples,
            generator=torch.Generator().manual_seed(seed),
            **options,
        )
        .kron[name]
        .g
        for seed in (0, 1)
    )
    print(samples, ((a - b).norm() / a.norm()).item())
4 0.5364193927354041
16 0.25288603786821845

On four tiny batches, four samples still leave a relative difference of 0.54 between seeds, and 16 samples halve it, as \(\sqrt{16 / 4} = 2\) says. The noise falls as \(1 / \sqrt{\text{tokens} \times \texttt{mc\_samples}}\), so a real fine-tuning set, with many thousands of answer tokens, does fine with the default; on a small one, raise mc_samples.

When to override

  • Few answer tokens: mc_samples=16, say, at 16 backward passes per batch.
  • If the forward slices the logits (logits[:, :-1]) instead, the output has one position fewer than the adapters, and plan shows position_mask for them: the prompt tokens then count in each \(A\). Shift the labels instead, as here.
  • Full fine-tuning instead of LoRA: the defaults take every nn.Linear. An output layer tied to the embedding (tie_word_embeddings=True) shares its weight, so it is left out and listed under uncovered, with the embedding and the norms. An untied lm_head is taken, and its \(G\) is \(V \times V\): about 20 GB in float64 for \(V = 50{,}000\). The memory line of plan shows it; pass layers= without the head to leave it out.