On-Device Adaptation and Personalization
Build a private personalization loop with local retrieval and LoRA adapters on a frozen base model. Learn update budgets, gates, and safe deletion.
Language AI HandbookAll chapters On-Device Adaptation and Personalization
Suppose your writing assistant starts a meeting summary with an old manager’s name. Changing the name should change the next summary. It should also be possible to inspect and delete the saved name. A local datastore can expose that entry directly. If the name was also used to train an adapter, changing the entry does not remove that second path.
This chapter builds a personalization loop around a frozen base model. Retrieval can supply an explicit fact or preference at inference time. An adapter can change how the model behaves across requests. Either mechanism can be used on its own. Combining them is useful when the app needs both editable records and a learned behavior.
The worked example uses synthetic data and a small CPU classifier. You will see a retrieval hit change an output, compare two adapter candidates against the base, and check whether a candidate that passes on rehearsed topics still passes on independent inputs.
The Budget and Trust Envelope
Write down both where the data may go and how much work the device can sustain. A design can fit the hardware while exporting data the user expected to stay local.
The privacy constraint
In this chapter, a local-only personalization path keeps raw examples, derived records and personalized weights on the device. That is a design boundary. Check backups, sync, logs, diagnostics and any cloud fallback as separate flows. A local-only path removes the server copy for those flows only when they are disabled or keep the same boundary. It does not protect data from access on a compromised device.
Keep private evaluation examples local as well. You can still use public or synthetic cases in a shared test suite. An explicit opt-in research or sync flow is a different data path. Give it its own purpose, permissions and retention policy.
Show users which editable records the app stores, and give them a way to disable and reset the parts that are not represented as individual records. A settings screen is one control. The deletion and export paths must enforce the same policy.
The compute and memory budget
Separate disk storage, peak runtime memory, update compute and energy, and time spent answering requests. An adapter checkpoint may fit on disk even when its backward pass does not fit in RAM. Retrieval can add lookup time and prefill tokens without changing how the model decodes one token at an unchanged prefix length.
The example below isolates trainable-state memory for an FP32 Adam accounting model. It counts the parameter, its gradient and two Adam moment arrays, each at four bytes per trainable parameter. Kingma and Ba, Algorithm 1 describes the two moments. It does not count frozen weights, saved activations, allocator overhead or temporary buffers. Mixed-precision layouts vary. The QLoRA paper illustrates backpropagation through a frozen quantized base to trainable adapters, so freezing the base does not eliminate the backward pass.
A 100-million-parameter update costs 1,600 decimal MB under this accounting. An illustrative adapter with 0.5% as many trainable entries costs 8 MB for the same parts. The ratio is 200 to 1 for the counted arrays. It is not a measured peak-memory ratio.
PythonIn [3]Expand
import numpy as np
base_params = 100_000_000 # frozen 100M-parameter base model
bytes_fp32 = 4 # full-precision training copy
adapter_fraction = 0.005 # 0.5% trainable, LoRA-style
# Memory per parameter in fp32 Adam full fine-tuning:
# parameter + gradient + first moment + second moment = 4 copies.
def training_bytes(n_trainable):
return 4 * bytes_fp32 * n_trainable
full_trainable = base_params
lora_trainable = int(base_params * adapter_fraction)
memory_mb = {
"Full fine-tuning": training_bytes(full_trainable) / 1e6,
"LoRA adapter": training_bytes(lora_trainable) / 1e6,
}
print({k: round(v, 1) for k, v in memory_mb.items()})VisualizationOut [4]Expand

Set a separate ceiling for peak memory and time per update. Schedule heavier work when foreground responsiveness and power are acceptable. Measure on the supported hardware. A memory figure by itself does not tell you whether an update will finish before the app loses its opportunity to run.
Check where your stack performs training. Apple’s Core ML personalization sample updates an updatable drawing classifier on the user’s device. Apple lists an Apple silicon Mac with at least 32 GB of memory or a Linux GPU machine for its Foundation Models adapter training toolkit 26.0.0. That final toolkit release targets macOS, iOS, iPadOS and visionOS 26. The hardware you train on and the devices that load the finished adapter can differ.
The data you actually get
Separate deliberate instructions from observed actions. A person who asks the app to remember a name provides a different signal from someone who happens to leave a suggested name unchanged. An unedited suggestion may be correct, or the user may have chosen not to check it.
Collect examples for a stated purpose. Store user-editable facts and explicit preferences where they can be changed. If you train on examples of a style, remove identifiers and other unnecessary content before fitting. This reduces what enters training. It is not a privacy guarantee.
Two Families of Adaptation
The practical question is whether the behavior should depend on a record selected for this request or on parameters that apply whenever the adapter is loaded.
Local retrieval: the model reads from a store
Local retrieval selects records at inference and passes their content to the model. The base weights stay unchanged. The original retrieval-augmented generation paper used a dense index as explicit nonparametric memory. The local design here consults a private store instead.
A record can contain a fact, an instruction or a style example. The user can edit it without retraining. Keep identifiers for the records included in each prompt so a user can see and correct the selected inputs. A record’s presence in the prompt does not prove the model used it correctly.
Retrieval can miss a relevant record or select the wrong one. The supplied records also consume context. A concise stored style instruction may be enough for some tasks. Test instructions and examples before committing to training.
Parameter adaptation: the model learns into weights
LoRA freezes the existing weight matrix and trains two factors of a low-rank update. Applying an adapter as a separate term makes it easy to choose a different adapter at load time. With a compatible weight representation, merging the update ahead of inference avoids running that separate matrix product for each input. The original LoRA paper describes the merged form. If the base is quantized, re-quantization and the inference kernel can affect both accuracy and performance.
Keeping the base and adapter separate also makes disabling the adaptation straightforward. It does not enable record-level edits inside the weight arrays. The route for deleting a training example is to discard any affected adapter or rebuild from an eligible snapshot and dataset.
Why they compose
Consider an assistant that needs a recent project name and a consistent summary format. A locally stored label helps supply the project name. A stored formatting instruction may already work. An adapter is an option when the instruction alone fails to produce the desired behavior and the app has suitable examples.
Use the current user-confirmed record for a factual field. Keep the adapter’s scope separate, for example output structure or tone. The application derives the factual value from the confirmed record even if the adapter still favors the old wording.
Local Retrieval: A Store You Can Trust
Local retrieval is straightforward to describe but surprisingly subtle to implement well enough to ship. The subtlety is that on-device retrieval must be correctable, private, small, and honest about misses. Each property deserves attention.
What to store
An item might come from a deliberate “remember this” action, a correction, or an extractor’s suggestion. Treat provenance and permission as separate fields. A correction can fix this draft without giving the app permission to keep it for later. In the schema below, every record starts with consent disabled unless the caller supplies it explicitly.
PythonIn [5]Expand
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
class Provenance(Enum):
USER_EXPLICIT = "user_explicit"
USER_CORRECTION = "user_correction"
MODEL_EXTRACTED = "model_extracted"
@dataclass
class MemoryItem:
text: str
provenance: Provenance
created: datetime
last_used: datetime | None = None
uses: int = 0
consent: bool = False
tags: list[str] = field(default_factory=list)Use provenance to show where the item came from. Use consent to decide whether it can be stored or used under this design. Keep a bounded expiry policy even for unconfirmed candidates. Tags can restrict which tasks may see a record, and the last-use timestamp can support eviction. A pin can exempt an item from ordinary eviction without overriding revocation or any hard store limit.
Indexing under a tight footprint
For an exact identifier, try a normalized key lookup. It depends on correct indexing, normalization and access to the record. A lexical index handles token overlap, such as a term that appears in both the request and note. SQLite FTS5 is one example with a built-in BM25 ranking function.
An embedding can help connect a paraphrase to a note that uses different words. Similarity is not authority. For a name or ID, confirm the exact field instead of silently choosing a near match. On a small collection, compare a linear scan against an approximate index before spending memory on the index. A scan over vectors of width computes component products for dot-product scoring. Index overhead and latency depend on data size and hardware.
The miss problem
If the app cannot find an eligible record for a personal fact, ask the user or omit the detail. An explicit miss is easier to correct than a plausible invention. Keep candidate access controls active before ranking and again when assembling the context. A pin changes sorting priority within the scope for which the user authorized the entry.
The injection budget
Reserve space for the system prompt, the user’s request, and the planned answer before adding optional records. With a 4,000-token context, a 2,000-token prompt and a 500-token answer allowance leave at most 1,500 tokens for records and their separators under that accounting. Item count alone is a poor measure because records vary in length. Use the target model’s tokenizer for the actual count.
Adapters Under a Tight Budget
Keep the update small enough to train and separate enough to replace. Which matrices to adapt is a capacity and deployment decision.
Why adapters and not full fine-tuning
For a frozen layer matrix with rows and columns, LoRA parameterizes a layer update as
Here has shape , has shape , and is the chosen inner dimension. The product fits the original matrix and has rank at most . The scalar scales its contribution. It does not guarantee that two trained adapters with different ranks have the same update norm.
The adapter holds trainable entries for this layer. At and , that is 65,536 entries versus 16,777,216 dense entries. At two bytes per entry, the factors are 128 KiB before metadata. Each separately adapted projection adds its own entries.
Specify which projections and what rank you train. Also specify the maximum sequence length and microbatch size. A smaller microbatch can reduce activation memory per forward and backward pass. If you accumulate gradients across microbatches, count both microbatches and optimizer steps in the update budget.
The local training loop
- Collect consented examples that match the training purpose. Split before training and group related examples if the intended evaluation is transfer to new situations.
- Optionally include rehearsal examples that represent baseline behavior you want to retain. Keep the final canaries separate from rehearsal.
- Fit a separate candidate adapter for a bounded number of optimizer steps. Track wall time and peak memory as well as the count.
- Evaluate both adaptation success and preservation of baseline behavior on local held-out cases. Inspect behavior after a reset and include targeted checks for any sensitive information the training pipeline could have admitted.
- Activate the candidate only if it passes the acceptance criteria. Keep the current version until the new version and its metadata are ready to swap together.
A step limit bounds the amount of optimization you run. It is not a differential-privacy parameter.
Keeping it private
Carlini et al. found that a trained language model could retain examples verbatim. Treat the adapter, any merged copies, and intermediate checkpoints as potentially sensitive artifacts. Under the local-only design, none of these are uploaded. Sync needs a separate threat model and consent choice. Aggregation for a population-level update and syncing an individual adapter are different operations.
Abadi et al. describe training with differential privacy. A formal claim needs a defined unit of privacy, a mechanism such as clipping and adding calibrated noise, and accounting for the released outputs. Local execution, a small adapter or a short training run alone does not establish such a claim.
The overfitting cliff
A lower training loss can accompany worse behavior on independent examples. Compare two things before installing a candidate. First, does it improve the intended behavior on cases that were not used to fit it? Second, does it preserve behavior on other tasks? These tests can fail independently.
A test that checks whether a classifier returns one output for every input detects collapse on those probes. It does not measure whether a generative model reproduces training text. Run a dedicated audit if that failure mode matters, and report its coverage. The toy below uses both seen probes and independent inputs, which exposes what a gate built only from training topics can miss.
When to Update: The Update Policy
An update policy decides which state changes, how often updates run, and what evidence is required before activating them.
What triggers an update
A deliberate request is a reasonable trigger. Another option is to wait for a batch of approved examples. If repeated edits suggest a change, ask the user to confirm rather than inferring permission to store or train. Keep a minimum interval where the device budget or repeated examples make per-event training unsuitable.
How often, and what changes
Allow immediate edits to the retrieval source and plan separately for index refresh or invalidation. Fit adapters in bounded batches. A base-model upgrade is a separate version change. Check any adapter’s target layers, shapes and base version before loading, and rerun the behavior checks when that version changes.
Conflict resolution
Imagine the user confirms a new manager’s name while the adapter still tends to use an earlier spelling. Resolve the field from the confirmed store entry. If the application needs exact factual output, populate that field with application logic. A prompt preference alone does not guarantee the generator will follow it.
Deletion, Rollback, and User Control
Choose what the delete control promises and test that outcome. Preventing future retrieval and erasing every copy are different operations.
Deleting a fact
Deleting the authoritative record prevents future use through that source once any derived index and cache no longer serve it. Apply the same operation to dependent records. Remove cached contexts that can include the text. A prior draft is a separate artifact and will not change retroactively.
Plan for restored backups. A restored copy that reactivates a deleted row can make deletion look successful until the next restore. Test restore against your retention and deletion policy. If the user’s example influenced an adapter or merged weights, removing the row does not alter those weights. Disable affected artifacts and use a clean base or rebuild from data that excludes the example and its copies.
Rollback
Keep candidate training separate from the active version. If a candidate does not pass the gate, discard it and keep serving the current version. This prevents activation rather than undoing an applied update.
For rollback after activation, retain only the approved number of eligible versions and their provenance. Restoring a previous version is appropriate only when it is compatible with the current base and does not contain data whose use has since been revoked. Prefer provenance identifiers to duplicating sensitive training examples inside each checkpoint.
Consent and the settings surface
Let users see and edit retained records, change retention, and disable retrieval or adapter training as appropriate. State what happens when each feature is disabled. Stopping future training alone leaves a previously trained adapter in place. Offer a separate reset that clears or detaches the relevant versions, and state whether that reset also clears the retrieval store.
Worked Example: A Deterministic CPU-Sized Experiment
To make the mechanics concrete without needing a phone, we will run a tiny, fully deterministic experiment on a small synthetic dataset. We will:
- Build a frozen linear classifier and a small store of synthetic records.
- Show how a retrieved record changes the classifier's prediction, and report the record ID and origin.
- Fit two adapter candidates and compare baseline preservation on seen and held-out topics.
- 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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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())], usedLet's compare the base behavior with the memory-steered behavior for a formatting query.
ConsoleOut [11]Expand
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 to a new preferred word for all 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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand

PythonIn [20]Expand
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_floorVisualizationOut [21]Expand

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]Expand
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]Expand
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.
Limitations and Impact
The experiment uses a randomly initialized classifier, ten fitted topics and twenty separate probe topics. It uses neither text generation nor a real device workload. The measured outcomes therefore describe this scorer and the two synthetic fitting procedures. They do not estimate production quality, privacy, battery use or training memory.
For an app, test the frozen default, retrieval alone and any proposed adapter on the same held-out tasks. Include changes to user facts, opt-out, deletion and a backup restoration in the evaluation. Run latency and resource measurements separately from accuracy. Track both successful personalization and regressions, since a better score on one does not imply a better score on the other.
Summary
- Retrieval supplies editable records at inference. Check permissions and context size before inserting them.
- A LoRA adapter learns a low-rank weight update while preserving the base weights. Measure peak memory as well as the checkpoint’s size.
- Keep deployment versions separate and check both intended behavior and regressions before activation. Use a held-out evaluation that matches what you expect to transfer.
- Deletion has to cover active records and derived copies. Resetting an adapter detaches a set of learned weights and does not erase other records.
Quiz
On-Device Adaptation and Personalization
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


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!