Machine learning with football · Chapter 10 · Large language models

Programming exercise

Build a language model from the site's news in plain Python, then distil a big football model into a tiny one.

Estimated time: 15 minutes · page 4 of 4

A language model from the news

The first script downloads the site's recent news stories, splits them into tokens, measures how sparse the n-grams get, builds a bigram model, prints the likeliest next words after a few contexts, and generates a sentence by sampling.

  1. Save it as ngram.py and run python ngram.py.
  2. Change the seed in random.seed(4). How many sentences make sense to the end?
  3. Turn it into a trigram model that uses two words of context. Does it write better, or does it run out of examples?
import collections
import json
import random
import re
import sys
import urllib.request

sys.stdout.reconfigure(encoding="utf-8")  # names with accents print on any terminal

API = "https://tactical-insights.com/api"

# The corpus: every recent news story on the site, headline and summary.
news = json.load(urllib.request.urlopen(f"{API}/news?limit=200"))
text = " ".join(f"{n['title']}. {n.get('summary') or ''}" for n in news)

# Tokens: here simply words and full stops, in lower case. Real LLMs use subword tokens.
tokens = re.findall(r"[\w']+|\.", text.lower())  # \w includes accented letters such as the ñ in Coruña
print(f"{len(news)} stories, {len(tokens)} tokens, {len(set(tokens))} different ones")
print(f"about {len(text) / 4:.0f} tokens by the 4-characters-per-token rule of thumb\n")

# 1. Sparsity: how many n-grams appear only once?
for n in (1, 2, 3, 4):
    grams = collections.Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
    once = sum(1 for c in grams.values() if c == 1)
    print(f"{n}-grams: {len(grams):>5} different, {once / len(grams):.0%} seen only once")

# 2. A bigram model: the probability of each next word, given one word of context.
following = collections.defaultdict(collections.Counter)
for a, b in zip(tokens, tokens[1:]):
    following[a][b] += 1

def next_words(word, top=5):
    counts = following[word]
    total = sum(counts.values())
    return [(w, c / total) for w, c in counts.most_common(top)]

for context in ("win", "the", "scored"):
    print(f"\nafter '{context}':  " + ",  ".join(f"{w} {p:.0%}" for w, p in next_words(context)))

# 3. Generate text: start somewhere and keep sampling the next word.
random.seed(4)
word, sentence = "the", ["the"]
for _ in range(15):
    counts = following[word]
    if not counts:
        break
    word = random.choices(list(counts), weights=list(counts.values()))[0]
    if word == ".":
        break
    sentence.append(word)
print("\ngenerated: " + " ".join(sentence))

Distil a model

The second script trains chapter 9's goals model as the teacher on the older matches, then trains two tiny students on the goal difference gap. One learns from the real results, the other from the teacher's home-win probabilities for every possible pairing. It tests both on the latest matches.

  1. Pick a league on the board of the tuning page. The code follows it here too.
  2. Run it. Does the distilled student beat the one trained on real results?
  3. Give the student the teacher's 0 or 1 instead of its probability, rounding at 0.5. What happens to the advantage?
import json
import math
import urllib.request

API = "https://tactical-insights.com/api"
LEAGUE = 1  # change it to try another league

played = sorted(json.load(urllib.request.urlopen(f"{API}/fixtures?league_id={LEAGUE}&status=FT&limit=200")),
                key=lambda m: m["fixture_date"])
cut = int(len(played) * 0.8)
train, test = played[:cut], played[cut:]
clubs = sorted({m["home_team_id"] for m in played} | {m["away_team_id"] for m in played})
index = {c: i for i, c in enumerate(clubs)}

# The teacher: chapter 9's goals model, an attack and a defence number per club. Big and slow, by our standards.
attack, defence, base, home = [0.0] * len(clubs), [0.0] * len(clubs), 0.0, 0.0
for _ in range(1500):
    ga, gd, gb, gh = [0.0] * len(clubs), [0.0] * len(clubs), 0.0, 0.0
    for m in train:
        h, a = index[m["home_team_id"]], index[m["away_team_id"]]
        eh = math.exp(base + home + attack[h] - defence[a]) - m["home_goals"]
        ea = math.exp(base + attack[a] - defence[h]) - m["away_goals"]
        gb, gh = gb + eh + ea, gh + eh
        ga[h] += eh
        gd[a] -= eh
        ga[a] += ea
        gd[h] -= ea
    base -= 0.05 * gb / len(train)
    home -= 0.05 * gh / len(train)
    attack = [x - 0.05 * (g / len(train) + 0.02 * x) for x, g in zip(attack, ga)]
    defence = [x - 0.05 * (g / len(train) + 0.02 * x) for x, g in zip(defence, gd)]

def poisson(k, lam):
    return math.exp(-lam) * lam ** k / math.factorial(k)

def teacher(h, a):
    """The teacher's chance of a home win: add up every scoreline where the home side scores more."""
    lh = math.exp(base + home + attack[h] - defence[a])
    la = math.exp(base + attack[a] - defence[h])
    return sum(poisson(i, lh) * poisson(j, la) for i in range(10) for j in range(i))

# The student's one feature: the gap in goal difference per game, from the training matches.
gd_sum, games = [0] * len(clubs), [0] * len(clubs)
for m in train:
    for team, d in ((m["home_team_id"], m["home_goals"] - m["away_goals"]), (m["away_team_id"], m["away_goals"] - m["home_goals"])):
        gd_sum[index[team]] += d
        games[index[team]] += 1
gap = lambda h, a: gd_sum[h] / max(games[h], 1) - gd_sum[a] / max(games[a], 1)

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

def fit(rows, steps=2000, rate=0.3):
    """A tiny student: logistic regression on one number. rows are (x, target), and the target may be a probability."""
    w = b = 0.0
    for _ in range(steps):
        e = [sigmoid(w * x + b) - y for x, y in rows]
        w -= rate * sum(ei * x for ei, (x, _) in zip(e, rows)) / len(rows)
        b -= rate * sum(e) / len(rows)
    return w, b

# Student 1 learns from the real results only: one 0 or 1 per match played.
real = [(gap(index[m["home_team_id"]], index[m["away_team_id"]]), 1 if m["home_goals"] > m["away_goals"] else 0) for m in train]
# Student 2 learns from the teacher: a probability for every possible pairing, played or not.
soft = [(gap(h, a), teacher(h, a)) for h in range(len(clubs)) for a in range(len(clubs)) if h != a]

def log_loss(model, matches):
    w, b = model
    total = 0.0
    for m in matches:
        p = sigmoid(w * gap(index[m["home_team_id"]], index[m["away_team_id"]]) + b)
        y = 1 if m["home_goals"] > m["away_goals"] else 0
        total -= y * math.log(p) + (1 - y) * math.log(1 - p)
    return total / len(matches)

print(f"student on real results: {len(real)} labels of 0 or 1")
print(f"student on the teacher:  {len(soft)} labels, each a probability\n")
print(f"test log loss, real-results student: {log_loss(fit(real), test):.4f}")
print(f"test log loss, distilled student:    {log_loss(fit(soft), test):.4f}")

Check yourself

The first script's generated sentence starts sensibly and soon wanders off. Why?
In the second script, why can the student learn from more labels than there are matches?

What the chapter adds up to

A language model predicts the next token. Counting n-grams runs out of context and examples fast. Transformers let every token attend to every other and, at enormous scale, become the LLMs behind today's chatbots. Fine-tuning shapes them, distillation shrinks them and prompts steer them, and all of them inherit the data's flaws, so the last chapters on production systems and fairness apply to them most of all.

Leagues