Skip to content
Mementropy
SolutionsMementropyNotebookExecuted example

Notebook pipeline demo

A tiny bigram language model that exercises every part of the notebook-to-site renderer.

By Ryan HammangUpdated

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.

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.

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 np
import 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'

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 c
pairs = (
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 W∈R∣V∣×∣V∣W \in \mathbb{R}^{|V| \times |V|}. Given the previous character xt−1x_{t-1} it predicts

P(xt∣xt−1)=softmax⁡(Wxt−1)xtP(x_t \mid x_{t-1}) = \operatorname{softmax}\left(W_{x_{t-1}}\right)_{x_t}

and training minimises the mean negative log-likelihood L=−1N∑tlog⁡P(xt∣xt−1)\mathcal{L} = -\frac{1}{N}\sum_{t} \log P(x_t \mid x_{t-1}).

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()
0 20 40 60 80 100 120 140 step 1.75 2.00 2.25 2.50 2.75 3.00 3.25 negative log-likelihood Loss falls, then the gap opens train validation
Mean negative log-likelihood per step. Validation loss flattens early; a bigram model runs out of signal fast.
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()
space n a c s d h b i r 0% 2% 4% 6% 8% 10% 12% 14% 16% probability Next character after "e"
What the trained model expects after the letter "e".
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 sys
missing = 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
  • 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.