Lesson 04 · 30 minutes
Train without labels and from a reward, and ask what each one trusts
- Group data without labels with KMeans and say who must name the groups
- Train a bandit from a reward and show reward hacking
- Say what each of the first three kinds of training trusts 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
A vendor's sheet says that its detector was "trained with supervised, unsupervised and reinforcement learning, fine-tuned on your data and kept fresh by federated learning". Your manager asks: "Which of those words should worry us?" This lesson builds the first three kinds in miniature. The next lesson builds the last two. For each kind you read what it learns from and write down the one question that a defender asks of it.
Recall
In lesson 2, what is a label, and which kind of training needs labels?
A label is the right answer for one example, for example the digit that a picture shows. Supervised training needs labels: the model learns to match them.
In lesson 3, why is the score on the training data not the score you report?
The model may have memorised the training examples. Only the score on a test part that the model never saw says how it works on new data.
The idea
Every kind of training answers one question: what tells the model that it is right? The answer shows what an attacker can reach, and so what a defender must check.
| Kind | What teaches the model | How it is attacked | What a defender asks or does |
|---|---|---|---|
| Supervised | Labelled examples. Lessons 1 to 3 did this. | Poisoned labels (lesson 2). | Audit a sample of the labels and read the score of each class. |
| Unsupervised | The shape of the data, with no labels. | Poisoned clusters: planted points move or merge the groups. | Log the group sizes at every run. A person names and reviews the groups. |
| Reinforcement | A reward after each action. | Reward hacking: the model learns to raise the score, not to reach the goal. | Ask what the reward measures. Test the policy against the real goal. |
| Fine-tuning | New data, on a model that is already trained. | Poisoned fine-tuning data. | Pin the base model and vet the new data. Run the old tests again after the tuning. |
| Federated | Several sites train on their own data. A server averages the results. | A malicious client sends bad weights. | Admit only known sites. Limit and check each update. |
This lesson builds the unsupervised and the reinforcement rows. Lesson 5 builds the last two. Only the first three kinds get a program in this course: lesson 2 poisons labels, and the bandit below shows reward hacking. The other attacks in the table are a map. The course "AI security fundamentals" attacks a model in practice.
Worked example
Go to the lab folder and activate the environment. Each step saves one whole file.
1. Group data without labels
Unsupervised learning looks for structure in data that has no labels. KMeans is one such method: you give it a number of groups k, and it places k centres and puts each point with its nearest centre. make_blobs makes seeded points that cluster around centres: here, 500 sessions with two measures each. n_init=10 repeats the start ten times and keeps the best result. km.labels_ holds the group number of each point. np.bincount counts the points of each number.
Create cluster.py.
cluster.py
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
X, _ = make_blobs(
n_samples=[300, 150, 50],
centers=[[2, 2], [8, 3], [5, 9]],
cluster_std=[1.0, 1.0, 0.8],
random_state=7,
)
print("sessions:", X.shape)
for k in (2, 3, 4):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
sizes = np.bincount(km.labels_)
print("k =", k, "sizes:", sizes)python cluster.pysessions: (500, 2)
k = 2 sizes: [299 201]
k = 3 sizes: [300 150 50]
k = 4 sizes: [146 150 50 154]With k=3 the sizes are the three groups that the generator made. With k=2 two groups are merged, and with k=4 the big group is split. KMeans cannot say which k is right, because it has no answer to compare with. A person chooses k and names the groups. That is where the trust sits. A few planted points can pull a centre, so a defender logs the sizes of every run and looks into a change.
2. Learn from a reward
Reinforcement learning trains an agent, a program that chooses actions. After each action it gets a reward, a number. The policy is its rule for choosing. A bandit is the smallest case: the same choice again and again. This one is epsilon-greedy: with the chance epsilon (0.1) it tries a random action, and otherwise it takes the action with the best average reward so far.
The story: a triage bot picks one of three actions for an alert. The list chance holds the chance that each action earns a reward of 1. In the true run the reward comes from analysts who confirmed the outcome. In the proxy run it comes from a dashboard that rewards "alerts removed", so closing pays almost always.
Read these parts of the program first.
random.Random(11)is a random generator with the fixed seed 11. Itsrandom()gives a number from 0 up to 1, andint(rng.random() * 3)turns that into a random pick of 0, 1 or 2.valueholds the average reward of each action. All averages start at 0.0, so the first pick is action 0,close:value.index(max(value))is the number of the action with the highest average, and for equal averages it gives the first.value[action] += (reward - value[action]) / count[action]is the learning. After each try it moves the average towards the new reward by a step of 1 divided by the number of tries._infor _ in range(steps)is a loop counter that the code does not use.[round(v, 2) for v in value]builds a new list from an old one: each average, rounded to two decimals.
Create bandit.py.
bandit.py
import random
ACTIONS = ["close", "ask", "block"]
def learn(chance, steps=500, seed=11, epsilon=0.1):
rng = random.Random(seed)
count = [0, 0, 0]
value = [0.0, 0.0, 0.0]
for _ in range(steps):
if rng.random() < epsilon:
action = int(rng.random() * 3)
else:
action = value.index(max(value))
reward = 1 if rng.random() < chance[action] else 0
count[action] += 1
value[action] += (reward - value[action]) / count[action]
return count, [round(v, 2) for v in value]
for name, chance in (("true", [0.2, 0.7, 0.5]), ("proxy", [0.95, 0.7, 0.5])):
count, value = learn(chance)
print(name, "tries", count, "value", value, "-> policy:", ACTIONS[count.index(max(count))])python bandit.pytrue tries [30, 452, 18] value [0.23, 0.69, 0.56] -> policy: ask
proxy tries [473, 11, 16] value [0.95, 0.64, 0.56] -> policy: closeThe learning code is the same in both runs. Only the reward changed. With the true reward the policy asks an analyst (452 of 500 tries). With the proxy it closes the alert (473 of 500). The agent did what the score paid for. This is reward hacking in miniature.
3. Write the question for each kind
Your manager wants a short note: what teaches the model, and the one question to ask the vendor. cat > vendor-questions.txt <<'EOT' writes the lines up to the closing EOT into a file. The quotes around EOT make the shell write the text exactly as printed. cat vendor-questions.txt prints the file.
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.
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.Lesson 5 adds the last two lines.
Your turn
Use the same code on new data. There are no steps: adapt cluster.py and bandit.py.
- Make the points with
make_blobs(n_samples=[200, 120, 80], centers=[[0, 0], [6, 1], [3, 7]], cluster_std=1.2, random_state=21). Cluster them withKMeans(n_clusters=k, n_init=10, random_state=0)forkof 3 and of 4. Read the sizes. - Call
learnfor a new reward,chance = [0.3, 0.4, 0.8], with its other settings unchanged. Read how many tries each action gets. - Call
learnagain for the samechance, withepsilon=0.0: the agent never tries a random action. Read the tries.
Check yourself
KMeans gave you three groups. Can you report its accuracy like the score of a classifier?
No. There are no labels, so there is no right answer to compare with. Check the sizes, whether the groups stay the same when the data changes, and whether a person can name each group.
The proxy run closed almost every alert. Is the learning code wrong?
No. The same code chose "ask" under the true reward. The reward was wrong: it paid for removed alerts, not for caught attacks. Fix the reward, and test the policy against the real goal.
With epsilon 0.0 the agent tried "close" 500 times, although "block" pays more. Why?
All averages start at 0.0, so the first pick is "close". The other averages then stay at 0.0, because those actions are never tried, and "close" wins every tie or lead. Without random tries the agent never learns that another action pays more.
Field notes
- Reward hacking is Goodhart's law in a program: a measure that becomes the target stops measuring what you cared about. Pair every reward with a check that the agent cannot change.
- Real reinforcement learning has many states and long chains of actions. The bandit keeps only the part that matters here: the reward defines the behaviour, so whoever controls the reward controls the policy.
- KMeans measures distance, so a feature with large numbers counts for more than one with small numbers. Scale the features first (lesson 8 does this for pixels), and keep the seed,
kand the group sizes of every run in a log. - An unlabelled model gives no score that proves it is right. Keep a small labelled sample of real cases and compare the groups with it.