On-Device Adaptation and Personalization › Worked Example: A Deterministic CPU-Sized Experiment

Michael BrenndoerferDecember 1, 202613 min read
Language AI HandbookAll chapters
Part 43 of 67Small and On-Device Language Models
Chapter 329On-Device Adaptation and Personalization › Worked Example: A Deterministic CPU-Sized Experiment
Reading section 8 of 11 · Worked Example: A Deterministic CPU-Sized Experiment · 13 minSection 8 of 11 · 13 min

Section 8 of 11 · 13 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

To make the mechanics concrete without needing a phone, we will run a tiny, fully deterministic experiment on a small synthetic dataset. We will:

  1. Build a frozen linear classifier and a small store of synthetic records.
  2. Show how a retrieved record changes the classifier's prediction, and report the record ID and origin.
  3. Fit two adapter candidates and compare baseline preservation on seen and held-out topics.
  4. Detach a demonstration adapter and delete one retrieval record in separate operations.

The example runs on CPU. Seeded feature vectors and model initialization make the result reproducible in the tested environment.

First, the setup.

PythonIn [6]
CollapseExpand
from dataclasses import dataclass
from datetime import datetime, timedelta

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

SEED = 7
np.random.seed(SEED)
torch.manual_seed(SEED)

We create a frozen base "model": a linear map from a small hand-built feature space to a vocabulary of pseudo-words. Each topic is represented by a seeded random feature vector. We initialize the scorer with random weights and freeze them. Its predictions stand in for baseline behavior without simulating pretraining or token sequences.

PythonIn [7]
CollapseExpand
VOCAB = [
    "alpha",
    "beta",
    "gamma",
    "delta",
    "epsilon",
    "zeta",
    "eta",
    "theta",
    "report",
    "list",
]
V = len(VOCAB)
D = 32


# Frozen base model: linear scorer over a generic feature space.
class FrozenBase(nn.Module):
    def __init__(self, d_in, v_out):
        super().__init__()
        self.W = nn.Linear(d_in, v_out, bias=False)

    def forward(self, x):
        return self.W(x)


torch.manual_seed(SEED)
base = FrozenBase(D, V)
# Pretend this was trained on generic text; we just fix its weights.
with torch.no_grad():
    base.W.weight.normal_(0.0, 0.3)
for p in base.parameters():
    p.requires_grad = False


def make_features(topic_id: int) -> torch.Tensor:
    """Return a seeded D-dimensional vector for this topic."""
    g = torch.Generator().manual_seed(1000 + topic_id)
    return torch.randn(1, D, generator=g)


# Generic "base behavior": for each topic, the argmax word.
def base_argmax(topic_id: int) -> str:
    with torch.no_grad():
        logits = base(make_features(topic_id))
    return VOCAB[int(logits.argmax())]

The toy retriever counts shared lowercase whitespace-delimited terms. If rows have the same positive score, the sort keeps their relative order in the list.

PythonIn [8]
CollapseExpand
def lexical_score(query: str, text: str) -> int:
    q, t = set(query.lower().split()), set(text.lower().split())
    return len(q & t)


@dataclass
class Memory:
    record_id: str
    text: str
    provenance: str
    consent: bool = False
    created: datetime | None = None


memory_store: list[Memory] = [
    Memory(
        "style", "favorite style: bullet lists", "user_explicit", consent=True
    ),
    Memory("manager", "manager is Dale", "user_correction", consent=True),
    Memory(
        "spelling",
        "uses british spelling: colour",
        "user_explicit",
        consent=True,
    ),
    Memory("address", "candidate address 42 oak street", "model_extracted"),
]


def retrieve(query: str, max_items: int = 2) -> list[Memory]:
    if max_items <= 0:
        return []
    allowed = [m for m in memory_store if m.consent]
    ranked = sorted(
        allowed, key=lambda m: lexical_score(query, m.text), reverse=True
    )
    return [m for m in ranked if lexical_score(query, m.text) > 0][:max_items]

An important detail is already visible: the model_extracted address has consent=False, so retrieve filters it out entirely. The filter excludes the entry before computing its rank.

ConsoleOut [9]
CollapseExpand
Query: format as bullet lists
  retrieved style: 'favorite style: bullet lists' [provenance=user_explicit, consent=True]
Address retrievable? False

The synthetic address exists in the in-memory list but cannot pass the consent filter. This example checks the query path only. A production design also needs consent and deletion controls for storage, indexing, and copies.

To show retrieval changing behavior, we use the selected record to steer the frozen scorer's input features. One way to supply retrieved text to a language model is to insert it into the prompt. Here we add the feature vector of the topic matched by a keyword. The first recognized topic in ranked record order determines the direction. Within a record, compare the lowercase whitespace-delimited terms with the keyword table and use its first match. A keyword inside another word does not match. The scorer returns the IDs and origins of the records whose recognized topic matched that direction.

PythonIn [10]
CollapseExpand
TOPIC_BY_KEYWORD = {
    "list": 3,
    "bullet": 3,
    "format": 3,  # formatting/style topic
    "spelling": 5,
    "colour": 5,  # spelling topic
}


def topic_from_memory(items: list[Memory]) -> int | None:
    for m in items:
        terms = set(m.text.lower().split())
        for kw, topic in TOPIC_BY_KEYWORD.items():
            if kw in terms:
                return topic
    return None


def respond(
    query: str, topic_id: int, use_memory: bool = True
) -> tuple[str, list[tuple[str, str]]]:
    x = make_features(topic_id)
    used = []
    if use_memory:
        hits = retrieve(query)
        mt = topic_from_memory(hits)
        if mt is not None:
            # Retrieve "steers" the feature space toward the memory topic.
            x = x + 1.5 * make_features(mt)
            used = [
                (m.record_id, m.provenance)
                for m in hits
                if topic_from_memory([m]) == mt
            ]
    with torch.no_grad():
        return VOCAB[int(base(x).argmax())], used

Let's compare the base behavior with the memory-steered behavior for a formatting query.

ConsoleOut [11]
CollapseExpand
without memory: gamma
with memory   : report
Records matching selected topic (ID, origin): [('style', 'user_explicit')]

The query shares the words “bullet” and “lists” with the consented style record. The fixed scorer switches from “gamma” to “report” after feature injection. The result includes the record ID style and its origin user_explicit, which the application could show next to the prediction.

Now the adapter half. We add a LoRA-style low-rank correction to the frozen linear layer and train it on synthetic "pattern" examples, where the target is a behavioral transformation: map topic tt to a new preferred word for all tt in a set. This stands in for "learn a formatting habit." We use a synthetic target so the experiment is deterministic and self-contained.

PythonIn [12]
CollapseExpand
class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r: int, alpha: float):
        super().__init__()
        self.base = base
        for p in self.base.parameters():
            p.requires_grad = False
        self.r = r
        self.scale = alpha / r
        self.A = nn.Parameter(torch.zeros(r, base.in_features))
        self.B = nn.Parameter(torch.zeros(base.out_features, r))
        nn.init.kaiming_uniform_(
            self.A, a=np.sqrt(5)
        )  # deterministic under global seed

    def forward(self, x):
        return self.base(x) + self.scale * (x @ self.A.T @ self.B.T)


def make_lora(r=2, alpha=4.0, seed=SEED):
    torch.manual_seed(seed)
    return LoRALinear(base.W, r=r, alpha=alpha)

For three style topics, the synthetic training target is “list.” For the other seven topics, the target is the frozen scorer’s output. Including those seven examples gives the rehearsed candidate a baseline behavior to match during training.

PythonIn [13]
CollapseExpand
STYLE_TOPICS = {3, 5, 8}
KEEP_TOPICS = {0, 1, 2, 4, 6, 7, 9}


def target_word(topic_id: int) -> int:
    return (
        VOCAB.index("list")
        if topic_id in STYLE_TOPICS
        else int(base(make_features(topic_id)).argmax())
    )


# Twelve style rows and fourteen rehearsal rows.
topics = (
    sorted(STYLE_TOPICS) * 4 + sorted(KEEP_TOPICS) * 2
)  # more style, some rehearsal
X = torch.cat([make_features(t) for t in topics], dim=0)
y = torch.tensor([target_word(t) for t in topics])

print(
    "training examples:", X.shape[0], "| features:", X.shape[1], "| classes:", V
)
print(
    "style examples:",
    sum(t in STYLE_TOPICS for t in topics),
    "| rehearsal examples:",
    sum(t in KEEP_TOPICS for t in topics),
)

Both adapter candidates use the same frozen layer. Each has its own trainable factors. Fit the rank-2 candidate for the fixed 80 Adam steps shown below. The learning rate is a toy setting.

PythonIn [14]
CollapseExpand
torch.manual_seed(SEED)
lora = make_lora(r=2, alpha=4.0)
opt = torch.optim.Adam(lora.parameters(), lr=0.1)

steps = 80
for step in range(steps):
    opt.zero_grad()
    logits = lora(X)
    loss = F.cross_entropy(logits, y)
    loss.backward()
    opt.step()

final_loss = float(loss.detach())
print(f"training loss before the last update: {final_loss:.4f}")
n_lora = sum(p.numel() for p in lora.parameters() if p.requires_grad)
n_base = sum(p.numel() for p in base.parameters())
print(
    f"adapter params: {n_lora} vs base params: {n_base}  ({100 * n_lora / n_base:.1f}% of base)"
)

The rank-2 factors contain 84 trainable entries and the frozen layer 320. The ratio is 26.25%, which follows from the small dimensions chosen for this experiment.

Now measure behavior: how many style topics now produce "list", and did the rehearsal topics survive?

PythonIn [15]
CollapseExpand
def predict(module, topic_id):
    with torch.no_grad():
        return VOCAB[int(module(make_features(topic_id)).argmax())]


style_before = sum(predict(base, t) == "list" for t in STYLE_TOPICS)
style_after = sum(predict(lora, t) == "list" for t in STYLE_TOPICS)
keep_before = sum(predict(base, t) == predict(lora, t) for t in KEEP_TOPICS)
print(
    f"style topics now 'list': {style_before} -> {style_after} / {len(STYLE_TOPICS)}"
)
print(
    f"rehearsal topics preserved behavior: {keep_before} / {len(KEEP_TOPICS)}"
)
ConsoleOut [15]
CollapseExpand
style topics now 'list': 0 -> 3 / 3
rehearsal topics preserved behavior: 7 / 7

The adapter predicts “list” for all three training style topics and preserves the base prediction on all seven rehearsed topics. These topics were used for fitting, so the counts describe behavior on the training topics. To test whether the preference transfers, use separate topics or contexts.

Screen for loss of baseline behavior

The seen-topic screen asks whether at least 75% of the designated generic probes match the frozen scorer and whether the classifier predicts more than one word across the ten seen topics. This can flag a collapsed classifier on those inputs. A memorization audit needs separate probes for reproducing training examples. The style-topic hit is a separate diagnostic. The frozen base passes the preservation screen without learning the preference. The function counts each canary topic once. It requires at least one distinct canary to compute agreement.

PythonIn [16]
CollapseExpand
def seen_preservation_screen(module, canary_topics=KEEP_TOPICS, style_topic=3):
    canary_topics = tuple(dict.fromkeys(canary_topics))
    if not canary_topics:
        raise ValueError("Supply at least one canary topic")
    # (1) General behavior must survive: predict the base's word on canary topics.
    preserved = sum(
        predict(module, t) == predict(base, t) for t in canary_topics
    )
    general_ok = preserved >= 0.75 * len(canary_topics)
    # (2) Check for a constant classifier on the ten seen topics.
    all_preds = {predict(module, t) for t in range(10)}
    collapsed = len(all_preds) <= 1
    # (3) Report a seen style hit separately from the gate.
    seen_style_hit = predict(module, style_topic) == "list"
    return {
        "general_ok": general_ok,
        "collapsed_on_seen_topics": collapsed,
        "seen_style_hit": seen_style_hit,
        "passes_seen_screen": general_ok and not collapsed,
    }


# Deliberately overfit adapter: train ONLY on style topics for many steps.
torch.manual_seed(SEED)
lora_overfit = make_lora(r=4, alpha=8.0)
opt2 = torch.optim.Adam(lora_overfit.parameters(), lr=0.5)
Xs = X[torch.tensor([t in STYLE_TOPICS for t in topics])]
ys = y[torch.tensor([t in STYLE_TOPICS for t in topics])]
for step in range(400):
    opt2.zero_grad()
    F.cross_entropy(lora_overfit(Xs), ys).backward()
    opt2.step()

base_screen = seen_preservation_screen(base)
screen_rehearsed = seen_preservation_screen(lora)
screen_stress = seen_preservation_screen(lora_overfit)
print("Frozen base:", base_screen)
print("Rehearsed:", screen_rehearsed)
print("Stress test:", screen_stress)
ConsoleOut [16]
CollapseExpand
Frozen base: {'general_ok': True, 'collapsed_on_seen_topics': False, 'seen_style_hit': False, 'passes_seen_screen': True}
Rehearsed: {'general_ok': True, 'collapsed_on_seen_topics': False, 'seen_style_hit': True, 'passes_seen_screen': True}
Stress test: {'general_ok': False, 'collapsed_on_seen_topics': False, 'seen_style_hit': True, 'passes_seen_screen': False}

The rehearsed candidate passes the preservation screen on the seven generic topics it saw during fitting. The stress candidate fails it while still predicting several distinct words. It uses only style examples, a different rank and learning rate, and more steps. The run tests a joint stress condition. Its results cannot isolate the effect of rehearsal.

Now compare both candidates on twenty generic topic IDs that were absent from the fitting sets. To pass these baseline-preservation checks, a candidate must pass the seen screen and match at least 75% of the base decisions on the held-out probes.

PythonIn [17]
CollapseExpand
held_out_topics = range(10, 30)
held_out_agreements = [
    sum(predict(model, t) == predict(base, t) for t in held_out_topics)
    for model in (base, lora, lora_overfit)
]
for name, count in zip(
    ("Frozen base", "Rehearsed", "Stress test"), held_out_agreements
):
    print(f"{name}: {count}/{len(held_out_topics)} base matches")

held_out_floor = 0.75
passes_preservation = {
    name: screen["passes_seen_screen"]
    and count / len(held_out_topics) >= held_out_floor
    for name, screen, count in zip(
        ("Rehearsed", "Stress test"),
        (screen_rehearsed, screen_stress),
        held_out_agreements[1:],
    )
}
print("Passes both preservation checks:", passes_preservation)
ConsoleOut [17]
CollapseExpand
Frozen base: 20/20 base matches
Rehearsed: 4/20 base matches
Stress test: 4/20 base matches
Passes both preservation checks: {'Rehearsed': False, 'Stress test': False}

Both candidates match the base on 4 of 20 held-out topics and fail baseline preservation. The seen style hit cannot tell you whether either candidate learns the desired behavior on new inputs. These independent random vectors are useful as a check on this classifier. Testing style transfer in a language model needs labeled held-out examples of the intended style and of unrelated behavior that should stay intact.

PythonIn [18]
CollapseExpand
policy_names = ["Frozen base", "Rehearsed", "Stress test"]
policy_models = [base, lora, lora_overfit]
style_success = [
    sum(predict(model, topic) == "list" for topic in STYLE_TOPICS)
    / len(STYLE_TOPICS)
    for model in policy_models
]
canary_agreement = [
    sum(predict(model, topic) == predict(base, topic) for topic in KEEP_TOPICS)
    / len(KEEP_TOPICS)
    for model in policy_models
]
VisualizationOut [19]
CollapseExpand
Paired bars compare style success and canary agreement for three policies.
Three style topics and seven generic topics used for fitting the rehearsed adapter. Left bars show the style hit fraction. Right bars show baseline agreement on the seven generic topics.
PythonIn [20]
CollapseExpand
candidate_names = policy_names[1:]
gate_seen = canary_agreement[1:]
gate_unseen = [hits / len(held_out_topics) for hits in held_out_agreements[1:]]
gate_threshold = held_out_floor
VisualizationOut [21]
CollapseExpand
Seen and held-out agreement bars sit beside the dashed 75% preservation threshold.
Base agreement on seven generic training topics (left) and twenty disjoint generic probe topics (right). Both candidates fail the illustrative 75% held-out preservation requirement.

To test the reset path, attach the rehearsed candidate temporarily in the notebook. Then clear the active adapter and fall back to the frozen base. Delete the retrieval record separately by ID, so the effect of each action is visible.

PythonIn [22]
CollapseExpand
active_adapter = lora


def serving_model():
    return base if active_adapter is None else active_adapter


comparison_topic = 3
with_adapter = predict(serving_model(), comparison_topic)
active_adapter = None
without_adapter = predict(serving_model(), comparison_topic)
back_to_base = all(
    predict(serving_model(), t) == predict(base, t) for t in range(10)
)

format_query = "format as bullet lists"
before_removing_record = respond(format_query, 0)
memory_store[:] = [m for m in memory_store if m.record_id != "style"]
after_removing_record = respond(format_query, 0)
ConsoleOut [23]
CollapseExpand
With a temporarily attached adapter: list
After detaching the adapter: report
Same predictions as the frozen base: True
Before deleting the style record: ('report', [('style', 'user_explicit')])
After deleting the style record: ('gamma', [])

Detaching the adapter changes the style-topic token from “list” to “report.” The adapter-serving path now uses the base for every prediction. The candidate objects still exist in the notebook for comparison. The later retrieval operation removes the record with ID style from the in-memory list. The format query then returns “gamma” with an empty record list. A deployed reset may also need to remove checkpoints, index entries or copies, depending on what the app promises to clear.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy