rml / Examples

Examples

The 32 programs under examples/: what each one trains, runs or simulates, which rml modules it is built from, which /ml-models concept it demonstrates, and the test that holds it to its claim.

On this page
  1. Anatomy of an example
  2. Every example
  3. Networks and architectures
  4. Training and adaptation
  5. Generative models
  6. Retrieval, ranking and multimodal
  7. Classical, causal and production
  8. Runtime and inference-stack tools
  9. What the examples exercise
  10. The four tools
  11. Tests

In short: every example is three Bazel targets, a library with the logic, a main.cc that parses positional arguments and prints, and a GoogleTest that checks the example's headline claim (the CNN beats the MLP with fewer parameters, only the LSTM learns the adding problem, Q-learning takes the cliff edge and SARSA the safe path). Twenty-eight are teaching demos, one per /ml-models concept, from an MLP to DPO, a U-Net diffusion model and a model server; they build on autograd, nn, losses and optim, or on linalg alone for the closed-form ones. Four are tools for the runtime and the inference stack: rml-chat, rml-graph-run and the two exact-output export checks. Together they hold 156 tests.

The rule behind the layout is in rml's own guidance: examples are entry points that parse flags and print, and all the logic they call lives in a library so it can be unit-tested (architecture.md L30–31, AGENTS.md L148–149). The README's quick start lists a bazel run line for each demo (README.md L32–245), which the tables below cite.

Anatomy of an example

The three targets of one example examples/mlp as the pattern. At the top, the binary target mlp built from main.cc, which bazel run starts, and the test target mlp_test built from mlp_test.cc. Both depend on the library target mlp_lib, built from mlp.h and mlp.cc, which holds the model, the synthetic data and the training loop. The library depends on seven rml modules: autograd, nn, losses, optim, data, random and core. bazel run --config=opt //examples/mlp mlp (rml_cc_binary) main.cc: parse argv, print bazel test //examples/mlp:mlp_test mlp_test (rml_cc_test) mlp_test.cc: the claim mlp_lib (rml_cc_library) mlp.h + mlp.cc: data, model, TrainMlp autograd nn losses optim data random core rml modules, by their per-header targets (//rml/nn:linear, //rml/optim:adam, …)
examples/mlp as the pattern (BUILD.bazel L11–47). Libraries are named <name>_lib, except rl's gridworld and rml_chat's chat_lib.

main.cc stays a few lines: it fills an options struct from positional arguments (for the MLP only a seed), calls one function and prints its result struct (main.cc L1–20). Every random draw goes through rml/random's Philox generator, which every example but the four tools depends on, so the same options give the same numbers, which is what lets a test assert a trained model's accuracy. All targets use the rml_cc_* macros, so the warning flags and -Werror apply to examples as to the library (see Build and testing). The binary is named after the directory except for the tools, whose binaries are rml-chat, rml-graph-run, tiny-net and tiny-models.

Every example

Grouped roughly as /ml-models orders its areas. "Built from" lists the rml modules the example's library depends on; "Tests" links its test file.

Networks and architectures

ExampleWhat it doesBuilt fromConceptTests
mlp
//examples/mlp
MLP on synthetic 8×8 digits; the README quotes about 99% test accuracy in a few seconds. (mlp.h L4–10, README L34)autograd, core, data, losses, nn, optim, randomtraining loop2
cnn
//examples/cnn
A CNN next to an MLP on glyphs at random positions: shared filters and pooling generalize where the MLP cannot. (cnn.h L4–12, README L40–41)autograd, core, data, losses, nn, optim, randomcnns2
rnn
//examples/rnn
A vanilla RNN next to an LSTM on the 50-step adding problem; only the LSTM learns the long memory. (rnn.h L4–13, README L47–48)autograd, core, data, losses, nn, optim, randomrnns and lstms2
vit
//examples/vit
A Vision Transformer on the CNN's glyphs, cut into 3×3 patches, with and without position embeddings. (vit.h L4–15, README L54–55)autograd, core, data, losses, nn, optim, randomvision transformer4
ssm
//examples/ssm
A diagonal linear state-space model on the adding problem at 200 steps, its scan checked against the convolution view. (ssm.h L4–20, README L61–62)autograd, core, data, losses, nn, optim, randomstate space models4
gnn
//examples/gnn
A graph convolutional network labelling nodes from ten labels per class, next to an MLP on the node features alone. (gnn.h L4–13, README L177–178)autograd, core, losses, nn, optim, randomgraph neural networks5
encoder
//examples/encoder
An encoder-only transformer pretrained by masked-token prediction on palindromes, next to the same network under a causal mask. (encoder.h L4–14, README L68–70)autograd, core, data, losses, nn, optim, randomencoder only3
char_gpt
//examples/char_gpt
A ~10M-parameter character-level GPT trained on a short original text (TinyCorpus), then sampled. (char_gpt.h L4–8, README L232)autograd, core, losses, nn, optim, randomdecoder only llm5

Training and adaptation

ExampleWhat it doesBuilt fromConceptTests
finetune
//examples/finetune
The pretrained encoder fine-tuned with about a thousand labels, next to a linear probe and training from scratch. (finetune.h L4–21, README L76–78)autograd, core, data, losses, nn, optim, randomfine tuning2
distillation
//examples/distillation
A student with 1/160 of a teacher's parameters, distilled on soft targets next to the same student on hard labels. (distillation.h L4–34, README L147–149)autograd, core, losses, nn, optim, randomdistillation3
dpo
//examples/dpo
Direct preference optimization of a small language model toward a larger digit sum, at two values of beta. (dpo.h L4–17, README L84–86)autograd, core, data, losses, nn, optim, randompreference optimization5
distributed
//examples/distributed
Data-parallel SGD over simulated workers averaging gradients by ring all-reduce; batch scaling and local SGD. (distributed.h L4–36, README L162–164)core, randomdistributed training5

Generative models

ExampleWhat it doesBuilt fromConceptTests
vae
//examples/vae
A VAE with a 2-D latent on 8×8 bars images, printing what the decoder draws across the latent plane. (vae.h L4–12, README L184–185)autograd, core, data, losses, nn, optim, randomvariational autoencoders3
diffusion
//examples/diffusion
DDPM on eight Gaussians on a ring. (diffusion.h L4–15, README L191)autograd, core, data, losses, nn, optim, randomdiffusion models6
diffusion_unet
//examples/diffusion_unet
Diffusion on 12×12 glyph images with a time-conditioned U-Net, next to the same network without skips (about 13 minutes). (diffusion_unet.h L4–26, README L197–199)autograd, core, data, losses, nn, optim, randomdiffusion unet6
flow_matching
//examples/flow_matching
Flow matching on the same ring, comparing how many Euler steps the sampler needs. (flow_matching.h L4–14, README L205)autograd, core, data, losses, nn, optim, randomflow matching6
gan
//examples/gan
A GAN on the same ring, whose samples sharpen and begin to collapse onto a few modes. (gan.h L4–13, README L211–212)autograd, core, losses, nn, optim, randomgans4

Retrieval, ranking and multimodal

ExampleWhat it doesBuilt fromConceptTests
rag
//examples/rag
A dense retriever plus a transformer reader, next to the same reader closed-book, on held-out and edited facts. (rag.h L4–38, README L218–220)autograd, core, data, losses, nn, optim, random, retrievalretrieval augmented generation4
two_tower
//examples/two_tower
Two-tower retrieval on synthetic clicks with and without the logQ correction, cold items, and an IVF index over item embeddings. (two_tower.h L4–40, README L114–116)autograd, core, losses, nn, optim, random, retrievaltwo tower models3
collaborative_filtering
//examples/collaborative_filtering
Held-out ratings from the global mean, ridge biases, item-item kNN and ALS matrix factorization. (collaborative_filtering.h L4–36, README L100–101)core, linalg, randomcollaborative filtering5
learning_to_rank
//examples/learning_to_rank
One linear scorer trained pointwise, pairwise (RankNet) and listwise (LambdaRank), scored by NDCG. (learning_to_rank.h L4–36, README L107–108)core, linalg, randomlearning to rank6
multimodal
//examples/multimodal
CLIP-style contrastive image and caption encoders labelling unseen shape, size and position combinations zero-shot. (multimodal.h L4–34, README L138–141)autograd, core, losses, nn, optim, randommultimodal models5

Classical, causal and production

ExampleWhat it doesBuilt fromConceptTests
time_series
//examples/time_series
Naive, seasonal naive, Holt-Winters and seasonal autoregression forecasts under a rolling-origin backtest. (time_series.h L4–34, README L92–94)classical, core, randomtime series8
online_learning
//examples/online_learning
Logistic regression learned online through a concept change: frozen batch, decaying and constant SGD, FTRL-proximal. (online_learning.h L4–41, README L122–124)core, linalg, randomonline learning5
causal_inference
//examples/causal_inference
A treatment effect from confounded data by difference in means, regression adjustment, IPW and AIPW, next to a randomized trial. (causal_inference.h L4–42, README L130–132)core, linalg, randomcausal inference6
drift
//examples/drift
Covariate and concept drift on a deployed classifier: feature PSI, KS tests, score PSI and week-late accuracy. (drift.h L4–35, README L155–156)core, randommonitoring and drift9
serving
//examples/serving
A simulated model server: dynamic batching under Poisson load, then static against continuous batching for generation. (serving.h L4–46, README L170–171)core, randommodel serving10
rl
//examples/rl
Value iteration, Q-learning and SARSA on cliff walking. (gridworld.h L4–18, README L226)randomreinforcement learning4

Runtime and inference-stack tools

ExampleWhat it doesBuilt fromDeep diveTests
rml_chat
//examples/rml_chat:rml-chat
rml-chat: chat with a GGUF file or Hugging Face directory, optionally with a draft model for speculative decoding. (chat.h L4–6, README L238–240)core, io, llmGeneration11
graph_run
//examples/graph_run:rml-graph-run
rml-graph-run: load an exported rml-graph model, feed it inputs, time it and check it against stored outputs. (graph_run.h L4–5)core, graph, ioExecuting a graph7
tiny_net
//examples/tiny_net:tiny-net
One Dense–ReLU–Dense net exported from PyTorch, JAX and TensorFlow and run with outputs checked bit for bit. (tiny_net.h L1–8)core, graphExporters and the model zoo3
tiny_models
//examples/tiny_models:tiny-models
A CNN, an LSTM and a transformer block from all three frameworks, each with an exact expected output. (tiny_models.h L1–10)core, graphExporters and the model zoo3

What the examples exercise

Library partExamples that use itNote
autograd + nn + losses + optim19Every neural demo; see Autograd, Neural network layers and Losses and optimizers.
data13Only TensorDataset and DataLoader; nothing calls the preprocessing or split helpers (see Data and metrics).
linalg without autograd4causal_inference, collaborative_filtering, learning_to_rank and online_learning fit their models with Cholesky solves (least squares, ridge, Newton steps) instead of gradient descent.
retrieval2rag (cosine similarity) and two_tower (similarity plus the IVF index); see Retrieval.
classical1time_series fits its seasonal autoregression with LinearRegression.
llm, io1rml_chat.
graph3graph_run, tiny_net and tiny_models.
Plain C++ and random only4distributed (with core's thread pool), drift, serving and rl implement their small models by hand.
metrics, quant0No example depends on them directly; examples compute their own accuracy, NDCG and errors.

The counts are of each example library's direct dependencies in its BUILD.bazel at the pin. Most /ml-models concept pages that are not examples are implemented as library modules instead, from the layers on Neural network layers to the estimators on Classical models.

The four tools

The tool examples follow the same library, binary and test split but serve the runtime rather than a lesson, and each has its own deep dive:

  • rml-chat loads a GGUF file or Hugging Face directory with its tokenizer and chat template and holds a conversation, optionally with a draft model for speculative decoding (chat.h L4–6). Its 11 tests run against the toy GGUF models in rml/llm/testdata/models. See Generation.
  • rml-graph-run loads an exported rml-graph model, feeds it inputs, times it and compares its outputs with stored references (graph_run.h L4–5), reading the golden fixtures in //rml/graph:testdata. See Executing a graph.
  • tiny-net and tiny-models run models that tools/make_tiny_net.py and tools/make_tiny_models.py define in PyTorch, JAX and TensorFlow and export, with weights chosen so every op is exact in f32 and the output can be compared bit for bit whatever the summation order, fusion or threading (tiny_net.h L1–8, tiny_models.h L1–10). Their exports are committed under each directory's testdata/. See Exporters and the model zoo.

Tests

Each teaching example's test does two things: checks its building blocks against something exact (a hand-computed value, finite differences, a closed form), then trains the example with a fixed seed and asserts the result its header promises. A few of those headline tests:

TestAsserts
BeatsTheMlpWithFewerParametersThe CNN outscores the MLP on glyphs at random positions with fewer weights.
OnlyTheLstmLearnsALongMemoryThe LSTM beats predicting the mean on the adding problem; the vanilla RNN does not.
EqualsTheConvolutionViewThe step-by-step scan equals the convolution with (1, a, a², …).
OnlyTheEncoderRecoversTheFirstHalfThe bidirectional encoder fills masked positions whose mirror lies ahead; the causal one cannot.
SkipsDenoiseBetterAtLowNoiseThe U-Net with skips beats the same network without them when the noise is small.
QLearningTakesTheCliffEdgeAndSarsaTheSafePathThe two learners' greedy paths differ as Sutton and Barto's Example 6.6 says.
EachObjectiveWinsTheMetricItOptimizesListwise (LambdaRank) wins NDCG@5 by more than 0.05; pairwise (RankNet) wins pairwise accuracy.
ConceptDriftIsSeenOnlyByAccuracyUnder a concept change the three input and score monitors raise at most two alarms each, while the accuracy monitor fires within two days of the late labels arriving.
GreedyRepliesMatchTheModelAloneSpeculative decoding with a draft gives the same greedy reply as the target alone.
MatchesTheExactOutputEvery export of every tiny model reproduces its exact expected output bit for bit.

The 156 tests are spread over the 32 test files linked in the tables above, from 2 (mlp, cnn, rnn, finetune) to 11 (rml_chat). Ten examples mark their test size = "large", all of them training demos; every one runs in CI with the rest of bazel test //... (ci.yml L37).