Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 05 · 30 minutes

Fine-tune a model and average three sites, and ask what each one trusts

After this lesson you can
  • 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
Lab files of this lesson (13)

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.

One round of federated learning
ServerSite 1Site 2Site 3send the current weightssend the current weightssend the current weightstrain locallytrain locallytrain locallysend the new weightssend the new weightssend the new weightsaverage, weighted by rowsServerSite 1Site 2Site 312345678910
  1. Server → Site 1: send the current weights
  2. Server → Site 2: send the current weights
  3. Server → Site 3: send the current weights
  4. Site 1: train locally
  5. Site 2: train locally
  6. Site 3: train locally
  7. Site 1 → Server: send the new weights
  8. Site 2 → Server: send the new weights
  9. Site 3 → Server: send the new weights
  10. 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:

  • SGDClassifier is a linear model that learns in small steps. Its partial_fit does 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.0 scales the pixels to the range 0 to 1.
  • copy.deepcopy makes 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. ~focus flips it to pick the other digits.
  • [:FIRST] keeps the first FIRST rows, 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.py
new 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: 37
Accuracy before and after tuning
Base, digits 3 and 80.97Tuned, digits 3 and 81.0Base, other digits0.95Tuned, other digits0.88Base, digits 3 and 80.97Tuned, digits 3 and 81.0Base, other digits0.95Tuned, other digits0.88

On 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=0 averages across the models, one number at a time: the first weight of every model, then the second, and so on.
  • Assigning to average.coef_ and average.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.py
site 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.96
Test accuracy of each model
Site 1, 600 rows0.94Site 2, 400 rows0.96Site 3, 347 rows0.94Average of the three0.95Pooled data0.96Site 1, 600 rows0.94Site 2, 400 rows0.96Site 3, 347 rows0.94Average of the three0.95Pooled data0.96

The 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.txt
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.

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.

  1. Run tune.py again with FIRST = 5: tune on only the first 5 rows of the digits 3 and 8. Read how many test predictions change.
  2. Cut the training rows of the digits (the same split as in federated.py) into four nearly equal sites: shuffle with np.random.default_rng(5).permutation, then np.array_split(order, 4). Train one LogisticRegression(max_iter=2000) for each site. Average the four coef_ and the four intercept_ 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.