Lesson 05 · 30 minutes
Fine-tune a model and average three sites, and ask what each one trusts
- Fine-tune a trained model and measure what it forgets
- Average the weights of three sites and compare the result with training on all rows
- Say what fine-tuning and federated learning trust and what a defender asks
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The vendor's sheet of lesson 4 ends with two more claims: the detector was "fine-tuned on your data and kept fresh by federated learning". Your manager asks: "Does that make it better, or just different?" You build both in miniature, measure what changes, and write down the question that a defender asks of each.
Recall
In lesson 1, what are the parameters of a model, and where does scikit-learn keep them for a linear model?
The numbers that training sets: the weights and the bias. A linear model keeps them in coef_ and intercept_.
In lesson 4, what did the bandit learn from, and what made it close almost every alert in the proxy run?
It learned from a reward. In the proxy run the reward paid for removed alerts, so the agent closed them. The code was the same; the reward was wrong.
The idea
Both kinds start from weights that already exist, or end with weights that come from many places. In both, the question is who controls the data behind the weights.
- Server → Site 1: send the current weights
- Server → Site 2: send the current weights
- Server → Site 3: send the current weights
- Site 1: train locally
- Site 2: train locally
- Site 3: train locally
- Site 1 → Server: send the new weights
- Site 2 → Server: send the new weights
- Site 3 → Server: send the new weights
- Server: average, weighted by rows
Fine-tuning reuses what a model learned on one task for another: you keep the trained weights and train a little more on the new data. The base model is then part of your supply chain, and the new data can change the whole model, not only the part that you meant to change. A defender pins the base model, vets the new data and runs the old tests again after the tuning.
Federated learning trains one model across several sites that do not share their data. Each site trains on its own rows, and only the trained weights go to a server, which averages them. The rows stay at the sites, but the server trusts every set of weights that it receives, so a defender admits only known sites and limits each update. Lesson 4 has the one-line map of all five kinds.
Worked example
Go to the lab folder and activate the environment. Each step saves one whole file.
1. Fine-tune a model and see what moves
LogisticRegression.fit starts again from nothing every time. The new parts, in the order of the code:
SGDClassifieris a linear model that learns in small steps. Itspartial_fitdoes one more pass over the data you give it, starting from the weights it has. That is fine-tuning in its smallest form.loss="log_loss"makes it learn like logistic regression.X / 16.0scales the pixels to the range 0 to 1.copy.deepcopymakes an independent copy, so the base model stays as it was.np.isin(y, [3, 8])is a mask that is true where the label is 3 or 8.~focusflips it to pick the other digits.[:FIRST]keeps the firstFIRSTrows, and.ljust(5)pads a name to five characters (details of layout).
The new data is 60 examples of the digits 3 and 8 only. Create tune.py.
tune.py
import copy
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
base = SGDClassifier(loss="log_loss", random_state=0).fit(X_train, y_train)
tuned = copy.deepcopy(base)
FIRST = 60
rows = np.isin(y_train, [3, 8])
X_new, y_new = X_train[rows][:FIRST], y_train[rows][:FIRST]
print("new data:", len(y_new), "rows")
for _ in range(20):
tuned.partial_fit(X_new, y_new)
focus = np.isin(y_test, [3, 8])
for name, model in (("base", base), ("tuned", tuned)):
print(
name.ljust(5),
"all", round(model.score(X_test, y_test), 2),
"digits 3 and 8", round(model.score(X_test[focus], y_test[focus]), 2),
"other digits", round(model.score(X_test[~focus], y_test[~focus]), 2),
)
changed = int((base.predict(X_test) != tuned.predict(X_test)).sum())
print("test predictions that changed:", changed)python tune.pynew data: 60 rows
base all 0.96 digits 3 and 8 0.97 other digits 0.95
tuned all 0.91 digits 3 and 8 1.0 other digits 0.88
test predictions that changed: 37On the new task the model got better (0.97 to 1.0). On everything else it got worse (0.95 to 0.88), and 37 of the 450 test predictions changed. The tuning on 60 rows moved the whole model, and it forgot part of what it knew. A defender learns two things. First, a model that passes its new test can still fail its old one, so the old tests run again after every tuning. Second, small new data moves the model (5 rows are enough, as "Your turn" shows), so a defender vets the new data.
2. Average the weights of three sites
The new parts, in the order of the code:
np.random.default_rng(3).permutation(n)shuffles the numbers 0 to n-1 with a fixed seed.np.split(order, [600, 1000])cuts the list into three parts at those places.enumerate(sites, start=1)gives each site with its number, counting from 1.[len(rows) for rows in sites]builds a list from a list: the length of each site.np.average(..., weights=sizes)averages with weights, so a site with more rows counts for more.axis=0averages across the models, one number at a time: the first weight of every model, then the second, and so on.- Assigning to
average.coef_andaverage.intercept_puts the new weights into a copy of a trained model.
The last model trains on all rows.
Create federated.py.
federated.py
import copy
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
order = np.random.default_rng(3).permutation(len(y_train))
sites = np.split(order, [600, 1000])
models = []
for number, rows in enumerate(sites, start=1):
model = LogisticRegression(max_iter=2000).fit(X_train[rows], y_train[rows])
models.append(model)
print("site", number, "rows", len(rows), "test accuracy", round(model.score(X_test, y_test), 2))
sizes = [len(rows) for rows in sites]
average = copy.deepcopy(models[0])
average.coef_ = np.average([m.coef_ for m in models], axis=0, weights=sizes)
average.intercept_ = np.average([m.intercept_ for m in models], axis=0, weights=sizes)
print("average of the three", round(average.score(X_test, y_test), 2))
pooled = LogisticRegression(max_iter=2000).fit(X_train, y_train)
print("pooled data ", round(pooled.score(X_test, y_test), 2))python federated.pysite 1 rows 600 test accuracy 0.94
site 2 rows 400 test accuracy 0.96
site 3 rows 347 test accuracy 0.94
average of the three 0.95
pooled data 0.96The average of the weights (0.95) is nearly as good as a model trained on all the rows together (0.96), and no site gave away a row. Averaging works this well because logistic regression has one best answer, so the three sites end near the same weights. Averaged weights of a neural network are not as safe. A real system repeats the round of the diagram: the server sends the average back to the sites, each site trains a little more, and the server averages again. federated.py does only the second half of one round. The trust sits in the server's rule: site 3 holds 347 of the 1,347 rows, so its weights carry about a quarter of the result. If a client sends bad weights, they move the average by that share. A defender admits only known sites and limits each update.
3. Finish the note for your manager
Write the whole note again, now with all five kinds. The same cat > ... <<'EOT' command replaces the file from lesson 4, so the file stays whole.
cat > vendor-questions.txt <<'EOT'
Supervised: labels teach the model. Ask how the labels were checked.
Unsupervised: the shape of the data teaches it. Ask who named the groups.
Reinforcement: a reward teaches it. Ask what the reward measures.
Fine-tuning: new data teaches a trained model. Ask which base model, and whether the old tests ran again.
Federated: averaged updates of several sites teach it. Ask which sites may join.
EOT
cat vendor-questions.txtSupervised: labels teach the model. Ask how the labels were checked.
Unsupervised: the shape of the data teaches it. Ask who named the groups.
Reinforcement: a reward teaches it. Ask what the reward measures.
Fine-tuning: new data teaches a trained model. Ask which base model, and whether the old tests ran again.
Federated: averaged updates of several sites teach it. Ask which sites may join.Your turn
Use the same code on new data. There are no steps: adapt tune.py and federated.py. Keep the line X = X / 16.0 in both.
- Run
tune.pyagain withFIRST = 5: tune on only the first 5 rows of the digits 3 and 8. Read how many test predictions change. - Cut the training rows of the digits (the same split as in
federated.py) into four nearly equal sites: shuffle withnp.random.default_rng(5).permutation, thennp.array_split(order, 4). Train oneLogisticRegression(max_iter=2000)for each site. Average the fourcoef_and the fourintercept_with equal weights and score the average model on the test part.
Check yourself
A tuned model scores higher on the new task. Do you ship it?
Not yet. Run the old tests too. In step 1 the score on the other digits fell by 7 points.
Federated learning keeps every row at its site. Does that make the training safe?
No. It keeps the rows from being copied to a central place. The server still trusts the weights that it receives, and one bad client can move the average. Weights can also leak facts about the rows.
Five rows were enough to change 17 predictions. What does that mean for the data that you use to fine-tune?
A tiny amount of new data moves the model, so the new data is as important as the first training data. Vet where it comes from, and run the old tests after every tuning.
Field notes
- The OWASP Top 10 for LLM Applications (2025 edition) lists Data and Model Poisoning, for the data of pre-training, fine-tuning and embeddings. NIST AI 100-2, "Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations", sorts attacks by the stage of the life cycle. Both are revised, so take the current text from the source.
- Record where the base model and every dataset came from, with a hash of each, and check the hash before you load a file (lessons 11 and 12 show how). A fine-tuned model inherits every flaw of its base.
- Production federated systems add two checks that this lesson does not build: they clip the size of each update, and they use secure aggregation, so that the server sees only the sum and not the update of one site.
- Large language models use several kinds in sequence: training on text with no labels (the course "How LLMs and agents work", lesson 1), fine-tuning, and then reinforcement learning, where people score the answers. Ask which stage each flaw came from.