Lesson 05 · 45 minutes
Spot model extraction by its query pattern
- Name the features of an extraction run that the log can show
- Write a detector that combines them and exempts a known integration
- Measure the detector with precision and recall on data with a known truth
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 product owner of Orbit Parcels fears that someone is copying Orbi: sending thousands of inputs, collecting the answers and training a cheaper copy on them. "If it happened last week, would the logs show it? And how many honest users would your detector accuse?" The rate alarm of lesson 4 caught the two fast bursts. You now look for a pattern that stays under every rate limit, and you measure your detector, not only run it. "Securing models and the ML supply chain" (lesson 7) copies a model and watches the rate. Here you work from the log, with precision and recall and an allow-list.
Recall
Lesson 4: the rate alarm found a user with 100 requests in each of two hours. Why would it miss a user with 20 requests a day for a week?
A rate rule compares one hour or one day with a limit, and 20 a day is below any sensible limit. A slow run of 140 requests in a week is a pattern over days, so you need a feature that adds up the whole week.
Lesson 2: what did the quiet week give you that a busy week does not?
A count of false alerts without doubt. This lesson does the same with a truth file: you know who really extracted, so you can count right and wrong alerts for every rule.
The idea
Model extraction is the collection of many input and output pairs from a model's interface to rebuild its behaviour in another model. The OWASP Top 10 for LLM Applications (2025) covers it inside Unbounded Consumption (LLM10:2025). MITRE ATLAS names a technique "Train Proxy via Replication" (AML.T0005.001), and the channel "Exfiltration via AI Inference API" (AML.T0024): take the current wording from atlas.mitre.org. You cannot see the copy. You see only how the extractor asks. In the log these features stand out:
| Feature | Extraction run | Normal user |
|---|---|---|
| Volume | Many requests in the week (100 or more here) | A few requests |
| Repeats | Almost none: each input is new, to cover the input space | Often the same question again |
| Same start | Neighbouring requests share one template and change the content | Different tasks follow each other |
None of the three is proof. A help-desk team sends many requests but repeats itself. A cost attack sends many different long prompts but does not use one template. A batch integration of a partner shows all three features, and it is allowed. So the detector ends with an allow-list of known integrations, taken from the access file audit/access.json (lesson 8 uses it again). Every alert about a user off the list goes to a person.
You measure a detector with two numbers. Precision is the share of alerts that are right: right alerts divided by all alerts. Recall is the share of real events that were found: right alerts divided by all real events. A rule that accuses everyone has recall 1 and a very low precision. A rule that accuses nobody has a perfect precision and no recall.
- Extractor → Orbi: 140 requests, one template, short answers
- Extractor → Copy model: trains a cheaper copy
- Orbi → Log file: one record for each request
- Detector → Log file: reads volume, repeats, start
The log never shows step 2, the copy. It shows only how the extractor asks.
Worked example
1. Write the detector
extract.py computes the features and keeps the five rules in a dictionary, so that you can compare them. A lambda (lesson 2) is a small function without a name: lambda f, u: f["requests"] >= 100 takes the features f and the user u and returns true or false. Counter(...).values() gives the counts per day, and max takes the busiest day. zip(rs, rs[1:]) pairs each record with the next one. precision_recall compares the set of users that a rule found with the set of real extractors.
extract.py
"""extract.py: features of a model-extraction run, a detector, and its precision and recall."""
import json
from collections import Counter, defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parent
MIN_REQUESTS = 100 # requests in the week
MAX_REPEAT = 0.2 # share of requests that repeat an earlier prompt of the same user
MIN_SWEEP = 0.6 # share of neighbouring requests that start with the same 16 characters
PREFIX = 16
def features(records):
"""For each user: requests, busiest day, repeat share and sweep share. Records must be in time order."""
by_user = defaultdict(list)
for r in records:
by_user[r["user"]].append(r)
out = {}
for user, rs in by_user.items():
seen, repeats = set(), 0
for r in rs:
repeats += r["prompt_sha"] in seen
seen.add(r["prompt_sha"])
pairs = list(zip(rs, rs[1:]))
same = sum(a["excerpt"][:PREFIX] == b["excerpt"][:PREFIX] for a, b in pairs)
out[user] = {"requests": len(rs), "busiest_day": max(Counter(r["ts"][:10] for r in rs).values()),
"repeat": round(repeats / len(rs), 2), "sweep": round(same / len(pairs), 2) if pairs else 0.0}
return out
def allowed_users(path=ROOT / "audit" / "access.json"):
"""Users with the role partner: a known integration that is meant to send many requests."""
return {u for u, role in json.load(open(path))["users"].items() if role == "partner"}
RULES = {
"100 in one day": lambda f, u: f["busiest_day"] >= MIN_REQUESTS,
"100 in the week": lambda f, u: f["requests"] >= MIN_REQUESTS,
"+ few repeats": lambda f, u: f["requests"] >= MIN_REQUESTS and f["repeat"] <= MAX_REPEAT,
"+ same start": lambda f, u: f["requests"] >= MIN_REQUESTS and f["repeat"] <= MAX_REPEAT and f["sweep"] >= MIN_SWEEP,
"+ not on allow-list": lambda f, u: (f["requests"] >= MIN_REQUESTS and f["repeat"] <= MAX_REPEAT
and f["sweep"] >= MIN_SWEEP and u not in allowed_users()),
}
def flagged(feats, rule):
return {u for u, f in feats.items() if rule(f, u)}
def precision_recall(found, truth):
"""(true positives, false positives, missed, precision, recall) as numbers, with 1.0 for an empty division."""
tp, fp, fn = len(found & truth), len(found - truth), len(truth - found)
return tp, fp, fn, round(tp / (tp + fp), 2) if found else 1.0, round(tp / (tp + fn), 2) if truth else 1.02. Print the table
run_extract.py shows the features of every user with 100 requests or more, and then the precision and recall of each rule for week 2. The truth is in logs/truth-week2.json. It lists the two users who really extracted. Save the file and run it.
run_extract.py
"""run_extract.py: the features of the users with the most requests, and the table of precision and recall."""
import json
import extract
from logrec import load
week1, week2 = load("logs/week1.jsonl"), load("logs/week2.jsonl")
truth = set(json.load(open("logs/truth-week2.json"))["extractors"])
feats = extract.features(week2)
print("users with 100 requests or more in week 2")
print(f"{'user':12}{'requests':>9}{'busiest day':>12}{'repeat':>8}{'sweep':>7}")
for user, f in sorted(feats.items(), key=lambda kv: -kv[1]["requests"]):
if f["requests"] >= extract.MIN_REQUESTS:
print(f"{user:12}{f['requests']:9}{f['busiest_day']:12}{f['repeat']:8.2f}{f['sweep']:7.2f} {'EXTRACTOR' if user in truth else ''}")
print(f"\n{'rule':22}{'found':>6}{'right':>6}{'wrong':>6}{'missed':>7}{'precision':>10}{'recall':>8}")
for name, rule in extract.RULES.items():
found = extract.flagged(feats, rule)
tp, fp, fn, p, r = extract.precision_recall(found, truth)
print(f"{name:22}{len(found):6}{tp:6}{fp:6}{fn:7}{p:10.2f}{r:8.2f}")
print("week 1, last rule:", len(extract.flagged(extract.features(week1), extract.RULES["+ not on allow-list"])), "users flagged")python3 run_extract.pyusers with 100 requests or more in week 2
user requests busiest day repeat sweep
u_bc5bfb76 200 200 0.00 1.00 EXTRACTOR
u_2df2ce2b 150 30 0.00 1.00
u_3ca43ca6 150 150 0.00 0.05
u_d59edd3b 140 20 0.00 1.00 EXTRACTOR
u_1b458063 120 24 0.93 0.14
u_8d550810 120 24 0.93 0.13
u_f29a99ff 120 24 0.93 0.12
rule found right wrong missed precision recall
100 in one day 2 1 1 1 0.50 0.50
100 in the week 7 2 5 0 0.29 1.00
+ few repeats 4 2 2 0 0.50 1.00
+ same start 3 2 1 0 0.67 1.00
+ not on allow-list 2 2 0 0 1.00 1.00
week 1, last rule: 0 users flagged3. Read the features
Seven users have 100 requests or more. Look at them one by one:
u_bc5bfb76sent 200 requests in one day, none repeated, all with the same start. It is an extractor, a fast one.u_d59edd3bsent 140 requests, only 20 on its busiest day. Nothing repeated, the same start every time. It is an extractor too, a slow one, below every daily limit.u_2df2ce2bhas the same three signs. This is the batch integration of the partner, which is allowed.u_3ca43ca6sent 150 long prompts in one hour: it is the cost attack of lesson 4. Its prompts are all different (repeat 0.00) but begin differently (same start 0.05).- The last three users have 120 requests each, with a repeat share of 0.93. They are the three users of the help desk, who ask the same eight questions.
4. Read the table of rules
Each row adds one condition to the row above.
- "100 in one day" finds the fast extractor and the cost attack, and misses the slow one. Precision 0.50, recall 0.50.
- "100 in the week" finds both extractors, but it accuses five others: precision 0.29.
- "+ few repeats" clears the help desk. Precision 0.50.
- "+ same start" clears the cost attack. The partner is left. Precision 0.67.
- "+ not on allow-list" clears the partner. Both extractors are found and nobody else: precision 1.00, recall 1.00.
The result looks perfect, so be careful. The lab was built with the answer in mind. In real data the thresholds (100, 0.2, 0.6) come from your own baseline, and the precision will be lower. The last line shows that the same rule flags 0 users in week 1.
5. Look at what the extractor sent
Print the first request of each extractor and of the partner. This is the template that the "same start" feature found.
python3 -c "
from logrec import load
rs = load('logs/week2.jsonl')
for u in ('u_bc5bfb76', 'u_d59edd3b', 'u_2df2ce2b'):
r = next(x for x in rs if x['user'] == u)
print(u, r['prompt_len'], 'chars, answer', r['resp_len'], 'chars:', r['excerpt'])
"u_bc5bfb76 74 chars, answer 5 chars: Classify this support message: late scan driver locker sunda
u_d59edd3b 69 chars, answer 4 chars: Rate the tone of this text: rain bell scan express pallet de
u_2df2ce2b 80 chars, answer 9 chars: Classify the parcel note: route courier parcel parcel lockerAll three ask for a label for a text: the answer is a few characters long. Short answers are what a copy needs for training a classifier, and the next task uses this sign.
Your turn
Files you need: logrec.py, extract.py and the data of lesson 0 (kr-lab.sh for this lesson, then python3 makelogs.py). Add a fourth feature to your copy of the work: the share of a user's requests whose response is 20 characters or less (resp_len of 20 or less). Use the records of week 2.
Count the users who have 100 requests or more and a short-answer share of 0.9 or more. Then take away the users on the allow-list (extract.allowed_users()). Compute the precision of this smaller rule against the extractors in the truth file.
Check yourself
The rule "100 in the week" has recall 1.00 and precision 0.29. Is it a good rule?
It finds every extractor, but 5 of 7 alerts are wrong. A person who reads the alerts will soon stop. A rule is useful when the people who must act on it trust it, so the false alerts have a cost that recall does not show.
Why is the allow-list a risk, and what protects it?
An attacker who gets the credentials of an allowed integration is not seen. Protect the list as a control: an owner, a review date for each entry, and a separate alert when an allowed user changes its pattern, for example a new template or a new volume.
What can an extractor do to avoid the "same start" feature?
Vary the template, or mix in normal-looking requests. Then the sweep share falls, and so does your recall. The features describe today's simplest extractor. Add features, and test again with a run that tries to hide.
What would a defender do in addition to detecting? Name two actions.
Limit the number of queries per account over the week, and not only per hour, and return less in each answer (shorter, with no probabilities). Both make a copy more expensive. The contract and the terms of use say what is allowed, and the legal contact decides on the response.
Field notes
- Precision and recall depend on the base rate. In this lab 2 of the 7 heavy users are extractors. In production the real rate is much lower, and the same rule will have a lower precision. Measure on your own traffic.
- Keep the features of each user for several weeks. The excerpt lives only 7 days (lesson 1), so a daily job must compute the "same start" feature while the excerpt exists, and store the feature, not the excerpt. A slow extractor needs a longer window, and so does the question "when did this start?".
- Do not accuse a user on one signal. The playbook for model theft (lesson 6) starts with a check against the allow-list and a question to the owner.
- Extraction through the inference interface is only one way to steal a model. The theft of the model file from storage is another, and it needs access control and alerts on the storage, not on the log.
- Tell the reader of the alert what the rule says, with the features and the thresholds. A flagged user who cannot be explained to a manager will not be acted on.