Notebook pipeline demo
A tiny bigram language model that exercises every part of the notebook-to-site renderer.
A character-level bigram language model, small enough to run in seconds. It exists to prove the publishing path: prose, code, printed output, a pandas table, theme-aware charts, math, an aside and tagged cells should all render as a native Mementropy page.
Prerequisites and support
Section titled “Prerequisites and support”The saved environment reports Python 3.12.12. For the public download, use an isolated Python environment with JupyterLab and NumPy, pandas, Matplotlib, IPython. These are package prerequisites, not a locked or newly tested environment. The Python examples generate their own teaching data and do not require cloud credentials or a pretrained model.
The public download omits the site-only mementropy.mplstyle setup cell; use Matplotlib’s default style. Before running chart cells, import matplotlib.pyplot as plt in your Jupyter kernel: that import was part of the omitted site-style cell. No style file or environment lock is bundled. If a rerun differs, record package versions and compare to the saved outputs rather than treating them as a guaranteed result.
Evidence: these are saved outputs from an earlier execution, not rerun for the 2026-10-29 editorial update. Rendering displays saved cells; it does not execute them. The public download is not a locked environment or a production validation.
Corpus
Section titled “Corpus”The training text is three sentences. A real lab would load a dataset; the point here is the shape of the output.
import numpy as npimport pandas as pd
corpus = ( "information survives transmission when the receiver can rebuild it. " "knowledge decays when nobody rehearses it. " "a model learns the statistics of the text it is shown.")chars = sorted(set(corpus))stoi = {c: i for i, c in enumerate(chars)}itos = {i: c for c, i in stoi.items()}data = np.array([stoi[c] for c in corpus])V = len(chars)
print(f"characters: {len(corpus)}")print(f"vocabulary: {V} symbols -> {''.join(chars)!r}")characters: 165 vocabulary: 24 symbols -> ' .abcdefghiklmnorstuvwxy'
Bigram counts
Section titled “Bigram counts”Count how often each character follows another. This is a pandas DataFrame; the page applies the site’s table design instead of pandas’ own styling.
counts = np.zeros((V, V), dtype=int)for a, b in zip(data[:-1], data[1:]): counts[a, b] += 1
show = lambda c: "space" if c == " " else cpairs = ( pd.DataFrame( [(show(itos[a]), show(itos[b]), counts[a, b]) for a in range(V) for b in range(V) if counts[a, b]], columns=["current", "next", "count"], ) .assign(share=lambda d: (d["count"] / d["count"].sum()).round(3)) .sort_values("count", ascending=False, kind="stable") .head(8) .reset_index(drop=True))pairs| current | next | count | share | |
|---|---|---|---|---|
| 0 | h | e | 6 | 0.037 |
| 1 | s | space | 6 | 0.037 |
| 2 | space | t | 5 | 0.030 |
| 3 | n | space | 5 | 0.030 |
| 4 | space | i | 4 | 0.024 |
| 5 | e | space | 4 | 0.024 |
| 6 | space | r | 3 | 0.018 |
| 7 | space | s | 3 | 0.018 |
A neural bigram model is one weight matrix . Given the previous character it predicts
and training minimises the mean negative log-likelihood .
rng = np.random.default_rng(7)split = int(0.85 * len(data))train, val = data[:split], data[split:]
def nll(W, seq): logits = W[seq[:-1]] logits = logits - logits.max(axis=1, keepdims=True) probs = np.exp(logits) / np.exp(logits).sum(axis=1, keepdims=True) return -np.log(probs[np.arange(len(seq) - 1), seq[1:]]).mean(), probs
W = rng.normal(0, 0.1, size=(V, V))history = []for step in range(150): loss, probs = nll(W, train) grad = probs.copy() grad[np.arange(len(train) - 1), train[1:]] -= 1 dW = np.zeros_like(W) np.add.at(dW, train[:-1], grad / (len(train) - 1)) W -= 5.0 * dW history.append((step, loss, nll(W, val)[0]))
hist = pd.DataFrame(history, columns=["step", "train", "validation"])print(f"final train loss {hist.train.iloc[-1]:.3f} | validation loss {hist.validation.iloc[-1]:.3f}")final train loss 1.687 | validation loss 3.404
fig, ax = plt.subplots()ax.plot(hist.step, hist.train, label="train")ax.plot(hist.step, hist.validation, label="validation")ax.set_title("Loss falls, then the gap opens")ax.set_xlabel("step")ax.set_ylabel("negative log-likelihood")ax.legend(loc="center right")plt.show()Show code
p = np.exp(W[stoi["e"]] - W[stoi["e"]].max())p /= p.sum()top = np.argsort(p)[::-1][:10]fig, ax = plt.subplots(figsize=(7.2, 2.8))ax.bar(["space" if itos[i] == " " else itos[i] for i in top], p[top], color=["#0969da"] + ["#6f706a"] * 9, width=0.62)ax.set_title('Next character after "e"')ax.set_ylabel("probability")ax.yaxis.set_major_formatter(lambda v, _: f"{v:.0%}")plt.show()def sample(W, start="t", n=72, seed=3): g = np.random.default_rng(seed) out, i = [start], stoi[start] for _ in range(n): p = np.exp(W[i] - W[i].max()) p /= p.sum() i = g.choice(V, p=p) out.append(itos[i]) return "".join(out)
print(sample(W))t. ticarat. reitreleb whesmit. matrceburermorens the s tareil tisuivesmiv
import sysmissing = sorted(set(corpus) - set(corpus[split:]))print(f"note: {len(missing)} of {V} symbols never appear in the validation split", file=sys.stderr)note: 12 of 24 symbols never appear in the validation split
What to notice
Section titled “What to notice”- Code blocks use the site’s Expressive Code theme, copy button included.
- Printed output, tables and charts sit in quiet panels built from the same tokens as the rest of the site.
- Charts are inline SVG. Switch the theme and they switch with it.