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 03 · 60 minutes

Watch confidence and drift, and share the evidence without naming anyone

After this lesson you can
  • Turn token probabilities into one confidence score for an answer
  • Compare a new week with a baseline week using a drift measure and a stated threshold
  • Build the queue of answers that people must read, and release evidence in which no record stands alone
Lab files of this lesson (11)

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

Since Wednesday the support team says that Orbi "feels worse". Nobody can say when it started or how bad it is, and the log holds no answers to read. You have the confidence of each answer, and a quiet baseline week. You find the day when the answers changed, measure how much, and build a queue so that a person reads a fair sample. Then the supplier of the new model asks for the records, and none may name a customer.

Recall

Lesson 1: which field of the record tells you which model answered?

model. Without it you cannot tell whether a change came from a new model version, from new documents or from new users.

Lesson 2: why did the quiet week matter for the rules?

Every alert in a quiet week is a false alert. Here the quiet week is also the baseline.

The idea

A language model writes an answer one token at a time. For each token the server can report the log-probability: the logarithm of the probability that the model gave to the token it chose. A value near 0 means that the model was sure, a very negative value that it was not. The mean of these values, turned back into a probability, is a common confidence score, from 0 to 1. It is a signal, not the truth: a model can be sure and wrong. A change in the scores still means that something changed.

Drift is a change in the data that the system sees or produces. You see it when you compare the distribution of a number in a new period with the distribution in a baseline period. The measure of this lesson is the population stability index (PSI). Split the range 0 to 1 into ten equal bins. For each bin take the share of answers in the baseline and the share in the new data. Then add up, over the bins, (new share − baseline share) × ln(new share ÷ baseline share). The result is 0 when the two pictures are the same and grows as they move apart.

The threshold is a choice: this course says that a day with a PSI above 0.2 has drifted. Practitioners use 0.1 to 0.25 and no standard sets one, so you state yours and test it on the quiet week. A day with fewer than 100 answers is too small to judge.

Drift says that something changed. A person must read answers to learn whether they got worse. So you also build a review queue: every answer with a low confidence, plus a fixed share of the others, chosen by a rule that nobody can influence.

From two weeks to a verdict
Baseline weekTen binsPSIVerdictReview queueshare of answers in each bincompare with the new dayabove 0.2 means driftpeople read a sampleBaseline weekTen binsPSIVerdictReview queue1234
  1. Baseline week → Ten bins: share of answers in each bin
  2. Ten bins → PSI: compare with the new day
  3. PSI → Verdict: above 0.2 means drift
  4. Verdict → Review queue: people read a sample

Worked example

1. Turn log-probabilities into a score

math.exp is the number e raised to a power: it undoes a logarithm. Three tokens with log-probabilities −0.1, −0.2 and −0.3 give the geometric mean of their probabilities.

python3 -c "import math; print(math.exp(sum([-0.1, -0.2, -0.3]) / 3))"
0.8187307530779818

The score is about 0.82. The lab log holds it in confidence.

2. Write the drift module

drift.py has the score, the PSI, a day-by-day comparison and the queue. min(int(v * BINS), BINS - 1) finds the bin of a value and keeps 1.0 in the last bin. An empty bin counts as 0.0001, because the logarithm of 0 does not exist. The queue takes a record when its confidence is below 0.5, or when the hash of its id, read as a number, divides by 20: about one record in twenty, the same ones on every run.

drift.py

"""drift.py: a confidence score, a drift measure (PSI) and a queue of answers for people to review."""
import hashlib
import math
from collections import defaultdict

BINS = 10
THRESHOLD = 0.2          # a PSI above this means drift
MIN_N = 100              # a day with fewer answers is too small to judge
LOW = 0.5                # an answer below this confidence goes to a person
SAMPLE_ONE_IN = 20       # so does about one answer in twenty


def confidence_from_logprobs(logprobs):
    """The geometric mean of the token probabilities: a number from 0 to 1."""
    return math.exp(sum(logprobs) / len(logprobs))


def proportions(values):
    """The share of values in each of BINS equal bins from 0 to 1. An empty bin counts as 0.0001."""
    counts = [0] * BINS
    for v in values:
        counts[min(int(v * BINS), BINS - 1)] += 1
    return [max(c / len(values), 0.0001) for c in counts]


def psi(baseline, new):
    """Population stability index of two lists of numbers between 0 and 1."""
    p, q = proportions(baseline), proportions(new)
    return sum((b - a) * math.log(b / a) for a, b in zip(p, q))


def by_day(records):
    days = defaultdict(list)
    for r in records:
        days[r["ts"][:10]].append(r["confidence"])
    return dict(sorted(days.items()))


def drift_days(baseline, new):
    """(day, answers, psi, verdict) for each day of `new`, compared with all of `baseline`."""
    base = [r["confidence"] for r in baseline]
    out = []
    for day, vals in by_day(new).items():
        if len(vals) < MIN_N:
            out.append((day, len(vals), None, "too few"))
        else:
            value = round(psi(base, vals), 2)
            out.append((day, len(vals), value, "DRIFT" if value > THRESHOLD else "ok"))
    return out


def review_queue(records):
    """(id, reason) for each answer that a person should read. The code decides, not a person."""
    queue = []
    for r in records:
        if r["confidence"] < LOW:
            queue.append((r["id"], "low confidence"))
        elif int(hashlib.sha256(r["id"].encode()).hexdigest()[:8], 16) % SAMPLE_ONE_IN == 0:
            queue.append((r["id"], "sample"))
    return queue

3. Compare the weeks day by day

run_drift.py compares each day of a week with the whole baseline week and prints the review queue.

run_drift.py

"""run_drift.py: compare week 2 with the baseline week 1, day by day, and build the review queue."""
from collections import Counter

import drift
from logrec import load

week1, week2 = load("logs/week1.jsonl"), load("logs/week2.jsonl")
for name, week in (("week 1", week1), ("week 2", week2)):
    print(f"{name}, each day against the baseline (threshold {drift.THRESHOLD}, at least {drift.MIN_N} answers)")
    for day, n, value, verdict in drift.drift_days(week1, week):
        print(f"  {day}  n={n:4}  psi={'-' if value is None else format(value, '.2f'):>5}  {verdict}")
    queue = drift.review_queue(week)
    print(f"  review queue: {len(queue)} {dict(Counter(reason for _, reason in queue))}")
python3 run_drift.py
week 1, each day against the baseline (threshold 0.2, at least 100 answers)
  2026-10-05  n= 167  psi= 0.01  ok
  2026-10-06  n= 178  psi= 0.03  ok
  2026-10-07  n= 165  psi= 0.01  ok
  2026-10-08  n= 181  psi= 0.01  ok
  2026-10-09  n= 168  psi= 0.01  ok
  2026-10-10  n=  27  psi=    -  too few
  2026-10-11  n=  22  psi=    -  too few
  review queue: 51 {'sample': 51}
week 2, each day against the baseline (threshold 0.2, at least 100 answers)
  2026-10-12  n= 193  psi= 0.01  ok
  2026-10-13  n= 387  psi= 0.01  ok
  2026-10-14  n= 194  psi= 1.36  DRIFT
  2026-10-15  n= 349  psi= 1.49  DRIFT
  2026-10-16  n= 197  psi= 1.97  DRIFT
  2026-10-17  n=  41  psi=    -  too few
  2026-10-18  n=  38  psi=    -  too few
  review queue: 118 {'sample': 67, 'low confidence': 51}

In week 1 every weekday has a PSI of 0.03 or less. In week 2 it jumps from 0.01 to 1.36 on Wednesday, 2026-10-14: the first day of drift. The review queue holds 51 answers in week 1, all samples, and 118 in week 2, 51 with a low confidence.

PSI of each weekday of week 2
Mon 12 Oct0.01Tue 13 Oct0.01Wed 14 Oct1.36Thu 15 Oct1.49Fri 16 Oct1.97Mon 12 Oct0.01Tue 13 Oct0.01Wed 14 Oct1.36Thu 15 Oct1.49Fri 16 Oct1.97

4. See why small days are skipped

Compute the PSI of Saturday of week 1 against the same week, without the minimum.

python3 -c "
import drift
from logrec import load
w = load('logs/week1.jsonl')
sat = [r['confidence'] for r in w if r['ts'][:10] == '2026-10-10']
print(len(sat), 'answers, psi', round(drift.psi([r['confidence'] for r in w], sat), 2))
"
27 answers, psi 0.45

A quiet Saturday gives a PSI of 0.45, far above the threshold, only because 27 answers do not fill ten bins. The minimum of 100 prevents that false alert.

5. Find the cause

Group week 2 by model. The field model was in the record for this.

python3 -c "
from logrec import load
rs = load('logs/week1.jsonl') + load('logs/week2.jsonl')
for m in ('orbi-1.2', 'orbi-1.3'):
    c = [r['confidence'] for r in rs if r['model'] == m]
    print(m, len(c), 'answers, mean confidence', round(sum(c) / len(c), 2), ', below 0.5:', sum(x < 0.5 for x in c))
"
orbi-1.2 1488 answers, mean confidence 0.78 , below 0.5: 0
orbi-1.3 819 answers, mean confidence 0.66 , below 0.5: 51
Mean confidence by model version
orbi-1.2 (1,488 answers)0.78orbi-1.3 (819 answers)0.66orbi-1.2 (1,488 answers)0.78orbi-1.3 (819 answers)0.66

The change starts on the day when the model changes from orbi-1.2 to orbi-1.3. The drift is real, and you can act on its cause: lesson 7 rolls the model back.

6. Share the evidence without naming anyone

The supplier of orbi-1.3 now asks for the records of its answers. A pseudonym (a code in place of a name) is not enough: whoever has the salt can hash guessed names and compare. The customers of the lab are named cust-0001 to cust-0999, so guess 999 names and count the users of the orbi-1.3 records that you can name again. The GDPR treats pseudonymised data as personal data, and only anonymous information as outside its principles (recital 26). The law asks whether anybody could reasonably identify a person with the means at hand, so it depends on who receives the data. Take the current text.

python3 -c "
from logrec import load, pseudonym
guess = {pseudonym(f'cust-{i:04d}'): f'cust-{i:04d}' for i in range(1, 1000)}
rs = [r for r in load('logs/week2.jsonl') if r['model'] == 'orbi-1.3']
users = {r['user'] for r in rs}
print(len(rs), 'records,', len(users), 'users,', sum(u in guess for u in users), 'recovered by guessing')
"
819 records, 62 users, 58 recovered by guessing

The four that stay hidden are service accounts, not named cust-NNNN. To anonymise, take out what names a person (user, prompt_sha, excerpt) and make the rest coarse. Then test that no released record is alone: a record that is unique in its columns can be found by someone who knows one fact about its person. Counter counts equal items. Each group of equal records must hold at least 5, and a smaller group is suppressed (left out). This rule is k-anonymity, and here k is 5.

Test the columns as they stand (the day and six number columns), then the release: the day, the tools, the decision and the confidence cut to one decimal (int(c * 10) / 10, the ten bins of the PSI). Everything else is dropped: cost, tokens, lengths, id, docs and model.

release.py

"""release.py: test that no released record of orbi-1.3 stands alone (k-anonymity, k = 5)."""
from collections import Counter

from logrec import load

rs = [r for r in load("logs/week2.jsonl") if r["model"] == "orbi-1.3"]
NUMBERS = ("confidence", "cost", "tokens_in", "tokens_out", "prompt_len", "resp_len")
# test 1: the columns as they stand
raw = Counter((r["ts"][:10],) + tuple(r[c] for c in NUMBERS) for r in rs)
print(len(raw), "groups on the day and the numbers, smallest", min(raw.values()))
# test 2: the columns of the release
rows = [(r["ts"][:10], tuple(r["tools"]), r["decision"], int(r["confidence"] * 10) / 10) for r in rs]
size = Counter(rows)
print(len(size), "groups on the released columns, smallest", min(size.values()))
# suppress the groups below 5, then count what the suppression removed
kept = [x for x in rows if size[x] >= 5]
print(len(rows) - len(kept), "records suppressed, smallest group now", min(Counter(kept).values()))
gone = [r for r, row in zip(rs, rows) if size[row] < 5]
for call in ("issue_refund", "send_email_external"):
    print(call, sum(call in r["tools"] for r in rs), "in the orbi-1.3 records,", sum(call in r["tools"] for r in gone), "suppressed")
print(sum(r["ts"][:10] > "2026-10-16" for r in gone), "suppressed records fall on the two weekend days")
python3 release.py
819 groups on the day and the numbers, smallest 1
100 groups on the released columns, smallest 1
101 records suppressed, smallest group now 5
issue_refund 15 in the orbi-1.3 records, 15 suppressed
send_email_external 2 in the orbi-1.3 records, 2 suppressed
40 suppressed records fall on the two weekend days

With the numbers kept, every one of the 819 records is alone: anyone who knows the cost of one answer finds it. After coarsening and suppression, each record is one of at least 5 in the columns that the supplier gets. The list of released columns is part of the test: add a column, and test again. Coarsening has a cost: the supplier gets the day and not the time. Of the 101 suppressed records, 40 fall on the two small weekend days, and 17 are refund or external-email calls. Those 17 are every such call among these 819 records, and an investigator wants them most. The test is a screen, and the data owner chooses the threshold. It cannot count what the supplier already knows.

Your turn

Files you need: logrec.py, drift.py, run_drift.py and the data of lesson 0 (kr-lab.sh for this lesson, then python3 makelogs.py). Measure the model change itself, not the days: compare the confidence of every orbi-1.3 record of week 2 with all records of week 1, using the PSI of your drift.py. Count the orbi-1.3 answers with a confidence below 0.5. Find the first day of week 2 that your day-by-day comparison marks as drift.

Last, compute the confidence of an answer whose two tokens have the log-probability −0.5 each, rounded to 2 decimals.

Check yourself

A model is very sure of every answer and every answer is wrong. What does the confidence score show?

High confidence, so nothing looks wrong. Confidence measures how sure the model is, not whether it is right. That is why the course adds a review queue and, in lesson 8, a labelled sample.

Why compare a day with a baseline week and not with the day before?

A slow change moves each day only a little, so day-to-day comparisons stay small while the total grows. A fixed baseline shows the sum. It must be a period that you checked, and you replace it on purpose.

Why does the review queue take a hash of the id and not a random number?

The hash gives the same answers on every run and machine, so two people get the same queue and an audit can repeat it. Nobody can steer the choice.

The supplier gets your log with the pseudonyms in place of the names. Is the data anonymous?

No. Anyone who has the salt and a list of names can rebuild the pseudonym, and the rest of the record can single a person out: cost, tokens and exact confidence are unique for every record. It is still personal data. Take out the identifiers, drop or round the numbers, and test that the smallest group over all released columns meets your threshold.

Field notes

  • Watch drift in the input (what users ask) and in the output (what the model writes). A change in the input can be real life, such as a holiday.
  • Not every model service gives log-probabilities, and the scores of two models are not comparable. A new version changes the score and does not rank itself: use the test set (lesson 7).
  • Record the baseline: its dates, model version and size.
  • Size the queue for people: 118 answers a week can be read, 10,000 cannot.