Machine Learning — Contents Appendix D

Appendix DComputational Specifications of the Simulators and Records of Checks

The chapters of this book embed ten simulators, in which you move parameters and watch the results. This appendix records, so that readers can judge for themselves, what each simulator computes (the formulas and algorithms) and how far it has been checked (against what, how many cases, and with what tolerance). Before you quote a number shown on a simulator’s screen in a report or in research, please read the relevant section.

Section D.1 describes the design common to all simulators (operating environment, random numbers, display of equations, embedding, computation limits), and Sections D.2–D.11 list the same items for each simulator in turn. Section D.12 summarizes what has not been checked and the known limitations. “Checked” as written here refers only to the tests actually run on November 12–13, 2026. It does not guarantee correct behavior under conditions not described here (other browsers, other devices, parameter combinations not included in the tests).

The checking methods are divided into the following four kinds. Analytical solution: comparison with quantities that are determined by a closed-form expression or a hand calculation. Full enumeration: comparison with the value obtained by counting all possible cases. Independent implementation: comparison with the value computed for the same quantity by a Python program (NumPy, SciPy, PyTorch, and so on) written independently of the simulator. Statistical check: a test, with a stated tolerance, of whether a quantity that uses random numbers follows the theoretical distribution. Writing $a$ for the value being compared (the simulator) and $b$ for the reference, the tolerance takes the form $\abs{a-b}\le \mathrm{atol}+\mathrm{rtol}\,\abs{b}$ (absolute tolerance atol, relative tolerance rtol).

In December 2026, each simulator was divided into two pages. The simulator page (sim/NAME-simulator.html) has two levels: the simple view, in which you grasp what is happening through pictures and motion, and the detailed view, which keeps the screen of the simulator as originally made. The explanation page (sim/NAME-derivation.html) now holds the explanation that used to be below the simulator’s screen (procedure, the formulas being computed, conditions of the data and random numbers, simplifications, conditions for instability, questions), with an added explanation of what the pictures of the simple view compute. What is embedded in the main text is the detailed view, and the “Operate and Observe” part of the boxes in the main text is written for the detailed view. Opening a former URL (sim/NAME.html) moves to the new simulator page, passing on the attached parameters (the parts after ? and after #) as they are. Unless otherwise stated, the records of computations and checks in Sections D.2–D.11 refer to the detailed view (the simulator as originally made). The scenes of the simple view and the checks of the computations added for them are described under “Corresponding chapters, sections, and tabs” and “How and to what extent the numbers were checked” in each section, and what was checked when the pages were divided is described in D.1.8.

D.1 Common Design

D.1.1 List of simulators

Table D.1: List of simulators (the key is the name used in the URL after ?only= and #; all files are under sim/)
SimulatorFiles (simulator, explanation)Tabs of the detailed view (key)Scenes of the simple view (key)Corresponding chaptersDefault seed
S01 Probability Distributionsdistributions-simulator.html
distributions-derivation.html
shape, meanboard, dice, lightChapter 320261112
S02 Bayesian Updatingbayes-update-simulator.html
bayes-update-derivation.html
beta, gausscoin, scaleChapter 420261112
S03 Regression and Overfittingregression-simulator.html
regression-derivation.html
fit, biasvar, bayesoverfit, shake, bandChapters 6, 820261112
S04 Classification and Kernelsclassifier-simulator.html
classifier-derivation.html
logistic, svmline, roadChapters 9–1120261112
S05 Neural Networksneural-net-simulator.html
neural-net-derivation.html
trace, train, gradchecklearn, flowChapters 14, 1520261112 (two: initial values and data)
S06 Gaussian Processes and Bayesian Optimizationgp-bo-simulator.html
gp-bo-derivation.html
gp, bo, comparepredict, searchChapters 12, 1320261112
S07 Latent Variableslatent-simulator.html
latent-derivation.html
em, pcagroup, axisChapters 17, 18data 20261113, initial value 1
S08 Approximate Inference and MCMCinference-mcmc-simulator.html
inference-mcmc-derivation.html
approx, mhwalk, traceChapters 20, 2120261112
S09 Sequence Modelshmm-simulator.html
hmm-derivation.html
hmm, kalmanguess, trackChapter 2220261112
S10 Attention and Next-Token Generationattention-simulator.html
attention-derivation.html
attn, modellook, writeChapters 24–2620261112

D.1.2 Operating environment and communication with the outside

D.1.3 Random numbers

D.1.4 Display of equations

The equations on the simulators’ screens are written in the browser’s standard MathML (MathJax is not used). Therefore they look slightly different from the equations in the main text (for example, the transpose is $\tp$ in the main text but T on screen), but the choice of symbols matches the main text. Many simulators have a panel “Putting the current numbers into the formula,” which displays the formula with the numbers of the current settings substituted. This panel is in the detailed view and not in the simple view. The equations on the explanation pages are also written in MathML. Boldface within equations is specified with MathML mathvariant="bold-italic" to match the main text’s $\bm{x}$ ("bold" for capital Greek letters and digits), and so that it also appears bold in Chrome, which does not reflect this specification, a bold typeface is specified in the stylesheet common to the simulators. Calligraphic and blackboard bold are written with mathematical characters (𝒩, 𝒟, ℬ, 𝔼) without using mathvariant. Boldface in explanatory text outside the equations (<b>) is upright bold, and its shape differs slightly from the bold italic of the main text. How MathML looks in browsers other than Chrome has not been checked.

D.1.5 Embedding parameters

Table D.2: Parameters that can be attached to a simulator’s URL
ParameterEffect
?level=easy
?level=detail
Specifies the level (simple view or detailed view) shown when the page is opened. Without a parameter, the page opens in the first scene of the simple view.
?embed=1Hides the title (h1) and the introductory text. This is the form used when embedding in a chapter. If no level is specified, the page opens in the detailed view. The explanation that used to be below the simulator (procedure, formulas, conditions, questions) has been moved to the explanation page, so the screen has a one-line link to the explanation page.
?only=<key>Displays only that tab (scene) and removes the others. It also serves as embed=1. The level is the one to which the key belongs. The boxes in the main text (Simulator N.k) embed one tab of the detailed view in this form.
#<key>The tab selected when the page is opened (example: sim/gp-bo-simulator.html#compare). If the key belongs to a scene of the simple view, the page opens in the simple view; if it belongs to a tab of the detailed view, it opens in the detailed view.
?mode=handS09 only. Opens the hidden Markov model tab in hand-calculation mode ($T=3$).

The level is determined by the first of the following that is present, in this order: the key of ?only=, the key of #, ?level=, and ?embed=1. Parameters attached to a former URL (sim/NAME.html) are passed on as they are to the new simulator page. An embedded simulator reports its own height to the parent page on loading, when the screen width changes, when tabs are switched, and whenever the height of the page changes, and the height of the frame on the main-text side changes accordingly.

D.1.6 Computation limits, behavior on errors, and when JavaScript is disabled

D.1.7 How the checks were carried out

Table D.3: Number of checks (record of November 12–13, 2026; all succeeded)
SimulatorNumerical tests (count)Screen checks (steps / comparisons)Check of opening with file://
Shared library685——
S01 Probability Distributions593218 / 41Right after opening (390 px)
S02 Bayesian Updating170126 / 22Right after opening (390 px)
S03 Regression and Overfitting217283 / 61Right after opening (3 widths)
S04 Classification and Kernels275339 / 71Right after opening (3 widths)
S05 Neural Networks253174 / 19Right after opening
S06 Gaussian Processes and Bayesian Optimization221158 / 24Right after opening
S07 Latent Variables208154 / 38Right after opening (390 px)
S08 Approximate Inference and MCMC656128 / 29Right after opening (390 px)
S09 Sequence Models285169 / 44All steps of the script
S10 Attention and Next-Token Generation587179 / 42All steps of the script

The counts in the table “How and to what extent the numbers were checked” in each of the following sections are the number of test items (one item is one comparison or one condition). The “comparisons” in the screen checks are the number of places in the script where a value or a state on the screen was checked, and all succeeded. The numerical tests of Table D.3 were all run again on November 13, 2026, and we confirmed that all succeeded with the same counts.

D.1.8 Checks made when the simulators were divided into two pages in December 2026

D.2 S01 Probability Distributions (distributions)

D.2.1 Corresponding chapters, sections, and tabs

D.2.2 What is computed

D.2.3 Input ranges, upper limits, and random numbers

D.2.4 Simplifications

D.2.5 Conditions for instability and the behavior of the simulator

D.2.6 How and to what extent the numbers were checked

Table D.4: Numerical tests of S01 (593 in total; all passed)
Quantity checkedCompared againstTypeNumberTolerance, etc.
Probability density (mass) function, cumulative distribution function, and quantiles (29 parameter sets)SciPy statsindependent implementation94density rtol $10^{-11}$, cumulative distribution rtol $10^{-10}$, quantile rtol $10^{-9}$
Mean, variance, and median (“none” with the reason for those that do not exist)SciPy statsindependent implementation89—
Normalization (integral of the density = 1, sum of the mass = 1)Theoretical value (integrating from the 0.0001 % point to the 99.9999 % point by adaptive Simpson’s rule gives $1-2\times10^{-6}$)analytical solution53—
Interval probability $P(x_1\le x\le x_2)$SciPy stats, direct sum of the mass, double-exponential numerical integration of the densityindependent implementation212rtol $10^{-9}$ (atol $10^{-8}$ only when the density diverges at an endpoint)
Full width at half maximumAnalytical formula, and the value found with SciPy brentqanalytical solution, independent implementation39rtol $10^{-10}$
Partial integral of the Cauchy density $(\gamma/\pi)\ln(1+R^{2}/\gamma^{2})$SciPy quadindependent implementation25rtol $10^{-8}$
Sequential computation of the sample mean and median, computation in time chunks, reproducibility of the seed, formulas of the theoretical valuesDirect computation, batch computationanalytical solution23the median agrees exactly
Distribution of the samples (continuous distributions)KS test ($n=20000$)statistical22$D\lt1.95/\sqrt{n}$
Distribution of the samples (discrete)$\chi^{2}$ goodness-of-fit test ($n=20000$)statistical7upper 0.1 % point
Spread of the sample mean: for the Gaussian, $\sigma^{2}/n$; for the Cauchy, $\bar{x}$ ($n=1000$, 400 sequences) remains a Cauchy distribution (KS test and interquartile range ≈ $2\gamma$); standard deviation of the median ≈ $\pi\gamma/(2\sqrt{n})$Theoretical valuestatistical6about 4 standard errors, KS test
Mean and variance of the histogram samplesTheoretical valuestatistical9about 4 standard errors
Mode (including ties for discrete distributions)Value obtained by full enumeration of the maximum of the probability mass functionfull enumeration9exact agreement
Input restrictions (rounding to the range, upper limit; that a finite value is returned even for 20000 samples beyond the upper limit)——5—

In the checks on the screen, 218 steps (41 comparisons) were carried out, including boundary values (the minimum and maximum of $\nu$, binomial $N=200$ with success probability 0 and 1, gamma $a=0.2$, beta $a=b=0.2$, Weibull $m=30$, 0 samples and 10000 samples, a single sequence, and $n=10^{5}\times20$ sequences) and the operating procedure of the box in Chapter 3.

The computations added for the simple view (sim/distributions.easy.js) were checked with 329 Node.js tests, and all succeeded. They were compared with the functions of the computation file (including that the sequence of bins for the balls is the same, for the same seed, as the samples of the binomial distribution in ① of the detailed view) and with closed-form expressions such as binomial coefficients, convolutions, and the cumulative distribution function of the Cauchy distribution.

D.3 S02 Bayesian Updating (bayes-update)

D.3.1 Corresponding chapters, sections, and tabs

D.3.2 What is computed

D.3.3 Input ranges, upper limits, and random numbers

D.3.4 Simplifications

D.3.5 Conditions for instability and the behavior of the simulator

D.3.6 How and to what extent the numbers were checked

Table D.5: Numerical tests for S02 (170 tests; all passed)
Quantity checkedCompared againstTypeNumber of testsTolerance, etc.
Parameters of the Beta–Bernoulli posterior distribution, posterior mean and posterior prediction, standard deviation, MAP, maximum likelihood, 95 % credible interval, weight $w$ (11 combinations of $a,b,m,l$)SciPy’s stats.beta and the analytical solutionAnalytical solution and independent implementation98Posterior mean rtol $10^{-15}$, standard deviation rtol $10^{-12}$, credible interval maximum absolute error $10^{-11}$
Sequential updating = batch updating (500 observations, reversed order, numerical computation one observation at a time on the grid with $N=10$–2000)Batch analytical solutionAnalytical solution9Maximum relative difference from the grid $7.46\times10^{-13}$ ($N=2000$)
Reproducibility of the seed; fraction of successes, mean, and variance of the synthetic dataTrue valuesStatistical4About 4 standard errors
Posterior distribution of the Gaussian mean $\mu_N,\sigma_N^{2}$, predictive variance, credible and prediction intervals, sequential = batch (6 combinations)Analytical solution and SciPy’s stats.normAnalytical solution and independent implementation50$\mu_N$ rtol $10^{-13}$, $\sigma_N^{2}$ rtol $10^{-14}$, intervals $10^{-12}$
Case analysis of the MAP estimate (interior maximum, endpoint when one parameter is 1, not uniquely determined when uniform, divergence below 1)Maximum of the density on a grid, analytical case analysisAnalytical solution9—

The on-screen checks comprise 126 steps (22 cross-checks), including the operating procedures in the boxes of Chapter 4.

The computations added for the simple view (sim/bayes-update.easy.js) were checked with 943 Node.js tests, and all succeeded. They were compared with the functions of the computation file, closed-form expressions, and the values of SciPy’s Beta distribution.

D.4 S03 Regression and Overfitting (regression)

D.4.1 Corresponding chapters, sections, and tabs

D.4.2 What is computed

D.4.3 Input ranges, upper limits, and random numbers

D.4.4 Simplifications

D.4.5 Conditions for instability and the behavior of the simulator

D.4.6 How and to what extent the numbers were checked

Table D.6: Numerical tests for S03 (217 tests; all passed)
Quantity checkedCompared againstTypeNumber of testsTolerance, etc.
True function of Data A, design matrix of the Gaussian basis functionsNumPyIndependent implementation3$10^{-12}$, $10^{-15}$
Coefficients of ① (including the minimum-norm solution) and of Ridge, RMSE on training and validation data and against the true function, condition number (13 settings)NumPy’s lstsq, normal equations solved with SciPyIndependent implementation89Coefficients: relative norm $\max(10^{-10},\ \text{condition number}\times10^{-13})$; RMSE rtol $10^{-7}$–$10^{-8}$; condition number rtol $10^{-8}$
Properties of the solution: QR solution = SVD solution, residual of the normal equations, interpolation at $N=d+1$, $\bm{w}\approx\bm{\Phi}^{\tp}\bm{y}/\lambda$ as $\lambda\to\infty$, $\norm{\bm{w}}$ decreasing monotonically in $\lambda$, training RMSE not increasing with the degreeIdentities and limitsAnalytical solution14—
Bias$^{2}$, variance, and $\langle(f^{(l)}-g)^{2}\rangle$ of ②Mean and variance computed directly with NumPyIndependent implementation52rtol $10^{-6}$–$10^{-7}$. Relative difference of the identity below $10^{-12}$; difference between time-split and batch computation below $10^{-10}$
$\bm{m}_N$, $\bm{\phi}^{\tp}\bm{S}_N\bm{\phi}$, and the predictive mean of ③; MAP = Ridge with $\lambda=\sigma^{2}/\sigma_w^{2}$; the prior distribution with zero data points; $\bm{\phi}^{\tp}\bm{S}_N\bm{\phi}$ not increasing when observations are added (5 settings)NumPy ($\bm{S}_N$ built with an inverse matrix)Independent implementation and analytical solution36Relative norm difference $10^{-8}$
Reproducibility of the seed——7—
Uniformity of $s$ in the synthetic data; distribution, mean, and variance of the noise ($n=20000$)KS test, theoretical valuesStatistical4$D\lt1.95/\sqrt{n}$, 4 standard errors
Mean squared error when predicting with the true function ≈ $\sigma^{2}$Theoretical valueStatistical14 standard errors
Bias$^{2}$ + variance + $\sigma^{2}$ = squared error at a new noisy point (independent Monte Carlo method)Measured 1.8489 and predicted 1.8824Statistical1±0.2623 (4 standard errors)
Mean and variance of the function samples from the posterior distribution (5 points)$\bm{m}_N^{\tp}\bm{\phi}$, $\bm{\phi}^{\tp}\bm{S}_N\bm{\phi}$Statistical104 standard errors

The on-screen checks comprise 283 steps (61 cross-checks), including the operating procedures in the boxes of Chapters 6 and 8. We also confirmed that there are no console errors in the display (at three widths) immediately after opening the page via file://.

The computations added for the simple view (sim/regression.easy.js) were checked with 621 Node.js tests, and all succeeded. They were compared with the functions of the computation file, simple computations written separately within the tests (the normal equations, Gaussian elimination, averages on a grid), and the numbers in the main text (Table 6.1 and the operating procedures of Simulators 6.1, 6.2, and 8.2).

D.5 S04 Classification and Kernels (classifier)

D.5.1 Corresponding chapters, sections, and tabs

D.5.2 What is computed

D.5.3 Input ranges, upper limits, and random numbers

D.5.4 Simplifications

D.5.5 Conditions for instability and the behavior of the simulator

D.5.6 How and to what extent the numbers were checked

Table D.7: Tests of the S04 numbers (275 tests; all passed)
Quantity checkedCompared withTypeNumber of testsTolerance, etc.
Loss, gradient, and one step of gradient descent for ①; $\lambda_{\max}$ and $L_c$ (four kinds of data)NumPyindependent implementation68rtol about $10^{-12}$ ($10^{-10}$ for $\lambda_{\max}$)
Gradientcentral differenceanalytical solution12relative $10^{-7}$
Minimum point (Newton’s method)SciPy BFGS + Newton’s methodindependent implementation24$L^{*}$ rtol $10^{-10}$, $\bm{w}^{*}$ $10^{-6}$
Detection of the case with no minimum (linearly separable, one class), monotone increase of $\norm{\bm{w}}$, zero data pointsanalytical propertiesanalytical solution9—
No overflow of the cross-entropy (such as $a=\pm800$)direct formula and asymptotic formanalytical solution23—
Kernels and the Gram matrixNumPyindependent implementation7$10^{-12}$
SMO solution ($\varepsilon=10^{-9}$, seven cases): dual objective function $D$, $\norm{\bm{w}}^{2}$, box and equality constraints, KKT residual, weak duality, $b$, and $f(\bm{x})$ at eight test points. $D$ at the default on-screen $\varepsilon=10^{-3}$dual problem solved with SciPy SLSQP and trust-constr (KKT residual of the reference solution at most $10^{-6}$)independent implementation77$D$ rtol $10^{-8}$, KKT residual at most $10^{-8}$, $b$ $10^{-5}$, $f(\bm{x})$ $10^{-4}$, relative difference of $D$ at the default $\varepsilon$ at most $10^{-3}$
Examples that can be calculated by hand (two points, three points, and a soft margin with $P=D=0.32$; the type in Chapter 11, Section 11.4)hand-calculated valuesanalytical solution14rtol $10^{-12}$
Special cases and the iteration upper limit, $D$ not decreasing at each step, the formula for $f(\bm{x})$—analytical solution11—
Reproducibility of the seed——16—
Mean, variance, and radius of the synthetic data, and the number of points in each quadranttheoretical valuesstatistical114 standard errors, $\chi^{2}$ (0.1 %)
Record of the numbers at the on-screen default values (initial loss $=N\ln 2$, etc.)—analytical solution3—

The on-screen checks comprised 339 procedures, including the operating procedures in the boxes of Chapters 9–11 (71 of them comparisons against reference values). We also confirmed that there are no console errors in the display immediately after opening the page via file:// (at three widths).

The computations added for the simple view (sim/classifier.easy.js) were checked with 243 Node.js tests, and all succeeded. They were compared with the functions of the computation file and with closed-form expressions (the spacing between the lines of probability 0.1 and 0.9, and the agreement of the margin width of the SVM with the direction in which the road is widest).

D.6 S05 Neural Networks (neural-net)

D.6.1 Corresponding chapters, sections, and tabs

D.6.2 What is computed

D.6.3 Input ranges, upper limits, and random numbers

D.6.4 Simplifications

D.6.5 Conditions for instability and the behavior of the simulator

D.6.6 How and to what extent the numbers were checked

Table D.8: Tests of the S05 numbers (253 items; all passed)
Quantity checkedCompared againstTypeItemsTolerance, etc.
One step of ① (four cases: the default values and other inputs): $a$, $z$, $\hat{y}$, $L$, $\delta$, each gradient, and the weights and loss after the updateHand-written NumPy calculation and PyTorch automatic differentiation (double precision)independent implementation79$10^{-15}$ to $10^{-13}$
Loss and gradients of 32 randomly generated networks (4 activations × 2 outputs × 4 shapes, with weight decay)PyTorch automatic differentiationindependent implementation96$10^{-13}$ times the magnitude of the gradient
Minibatch stochastic gradient descent for 6 epochs (same data, initial values, and ordering)NumPy implementationindependent implementation8$10^{-12}$
Output-layer error $\delta^{(2)}=\hat{y}-y$ (sigmoid + cross-entropy; identity + sum of squares/2)Central difference of $\partial\ell/\partial a^{(2)}$analytical solution29rtol $10^{-8}$
Gradient checking (12 networks). The error of the central difference is proportional to $\epsilon^{2}$, and that of the forward difference to $\epsilon$Central differenceanalytical solution16Relative error of the vector at most $10^{-6}$. With the default weights and $\epsilon=10^{-5}$, the maximum absolute error is $3.10\times10^{-12}$ (the value in Node.js; about $7.9\times10^{-12}$ in Chrome)
The weight decay term, a linear map when the activation is the identity, the symmetry of the all-0 initial values, the ordering of the parameters, and detection of divergenceAnalytical propertiesanalytical solution6—
Synthetic data (the true function of data A analytically; the noise, the uniformity of the inputs, the radii of the concentric circles, the XOR labels, and the variance of the initial values statistically)Theoretical values, KS testanalytical solution / statistical154 standard errors
Record of training with the default settings——4—

The on-screen checks comprise 174 procedures (19 comparisons), including the operating procedures in the boxes of Chapters 14 and 15. At 390 px, the long formula in “Putting the current numbers into the formula” scrolls horizontally inside its frame (the page does not overflow horizontally).

The computations added for the simple view (sim/neural-net.easy.js) were checked with 395 Node.js tests, and all succeeded. They were compared with the results of calling the functions of the computation file in the same order as ② of the detailed view (bit-for-bit agreement), with the numbers in Sections 15.3 and 15.5 of the main text, and with the fact that the border of the coloring is a straight line when there is one hidden unit.

D.7 S06 Gaussian Processes and Bayesian Optimization (gp-bo)

D.7.1 Corresponding chapters, sections, and tabs

D.7.2 What is computed

D.7.3 Input ranges, upper limits, and random numbers

D.7.4 Simplifications

D.7.5 Conditions for instability and the behavior of the simulator

D.7.6 How and to what extent the numbers were checked

Table D.9: Tests of the S06 numbers (221 tests; all passed)
Quantity checkedCompared withTypeNumber of testsTolerance, etc.
The 11 points of data C, and the positions and values of the true maximum and the local maximumSciPy minimize_scalarindependent implementation7position $2\times10^{-7}$, value $10^{-13}$
Predictive mean and variance, posterior covariance, log marginal likelihood and its three terms (9 cases). Hand-calculation formulas for one and two observations, zero observations, return to the prior far away, interpolation as $\sigma\to0$NumPy solve and slogdet without the Cholesky decomposition, SciPy multivariate_normal, explicit 2 × 2 inverse matrixindependent implementation, analytical solution107$10^{-10}$ (hand-calculation formulas $10^{-12}$ to $10^{-14}$)
Jitter, rounding of the variance, input validation—analytical solution8—
The curve of the log marginal likelihood versus $\ell$ and the maximum of the grid searchNumPyindependent implementation8$10^{-10}$ to $10^{-12}$
EI and PI (12 cases), the limit $\sigma_*\to0$, monotonicity, the formulas for UCB and LCBnumerical integration with mpmath (50 digits)independent implementation, analytical solution37EI rtol $10^{-11}$, PI $10^{-12}$
Values of the acquisition function on the 401-point grid and the chosen points (7 cases)NumPyindependent implementation21$f_{\mathrm{best}}$ rtol $10^{-12}$
Correspondence between maximization and minimization: sequences of observation points for 3 acquisition functions × 2 kinds of $f_{\mathrm{best}}$ × $\ell$ fixed/chosen × 4 seedsthe problem with the sign of the objective function reversedanalytical solution14Exact agreement in all 15 cases. LCB$(-y)=-$UCB$(y)$ agrees bit for bit
Reproducibility of the seed, definition of the simple regret——9—
Median and interquartile rangeNumPy quantileindependent implementation2—
Mean and variance of the noise of the synthetic data, uniformity of the $x$ of random search, covariance of 4000 samples from the prior and posterior distributions (15 components)theoretical values, KS teststatistical84 standard errors, $D\lt1.95/\sqrt{n}$

The results of the comparison in ③ (the simple regret of Bayesian optimization and random search) are recorded as measured values over 200 repetitions with a fixed seed, and no pass/fail criterion is applied (the quartiles agreed with a recomputation using NumPy’s quantile). SciPy’s quad was not used as the reference for EI because it gave a relative error of 2 % in the tail at $z\approx-12$. The on-screen checks comprise 158 steps (24 of them comparisons), including the operating procedures in the boxes of Chapters 12 and 13.

The computations added for the simple view (sim/gp-bo.easy.js) were checked with 121 Node.js tests, and all succeeded. They were compared with the functions of the computation file, the numbers given in the chapters, and closed-form expressions.

D.8 S07 Latent Variables (latent)

D.8.1 Corresponding chapters, sections, and tabs

D.8.2 What is computed

D.8.3 Input ranges, upper limits, and random numbers

D.8.4 Simplifications

D.8.5 Conditions for instability and the behavior of the simulator

D.8.6 How and to what extent the numbers were checked

For the reference calculations, the data generated by the simulator’s calculation file were passed as they were to NumPy and SciPy (so that the comparison uses the same data and the same initial values).

Table D.10: Numerical tests of S07 (208 tests; all passed)
Quantity checkedCompared againstTypeNumber of testsTolerance, etc.
Logarithm of the 2 × 2 Gaussian densitySciPy’s multivariate_normalindependent implementation16rtol $10^{-13}$
Responsibilities in the E step and the initial log-likelihood; $\bm{\mu}_k,\bm{\Sigma}_k,\pi_k,N_k$ in the M step; the sequence of log-likelihoods up to convergence and the number of iterations; the converged values (five cases)An independent NumPy implementationindependent implementation60$10^{-11}$–$10^{-13}$; log-likelihood sequence $10^{-9}$; number of iterations ±1; converged values $\pi$ $10^{-7}$, $\bm{\mu}$ $10^{-6}$
Variance floor (raising the eigenvalues)NumPy’s eighindependent implementation4$10^{-12}$
The log-likelihood of EM does not decrease (5 data sets × 5 values of $K$ × 5 seeds × 3 floors = 375 cases)—analytical solution1within rounding of relative $10^{-12}$
$J$ and the means in k-means; $J$ does not increase in either half step; empty componentsNumPy’s Lloyd algorithmindependent implementation, analytical solution12rtol $10^{-12}$
Degeneracy: without the floor the run stops and keeps a finite value; with the floor it converges; and the converged value increases as $c$ is made smaller—analytical solution6—
Values of the first iteration with the default settings (for the hand calculation in Chapter 17)NumPyindependent implementation3$10^{-12}$–$10^{-13}$
Two-dimensional PCA: the eigenvalues from the SVD equal those of the covariance matrix; the angle of the principal axis; $\bm{u}^{\tp}\bm{S}\bm{u}$ in 24 directions; at the principal axis the reconstruction error equals $\lambda_2$; $1\pm r$ after standardization; $\lambda_2=0$ for $N=2$NumPy’s eigh, the Jacobi algorithmindependent implementation, analytical solution43angle $10^{-9}$; $10^{-8}$–$10^{-12}$
PCA of the spectra: the eigenvalues (including the 200 × 200 Jacobi algorithm); for $k=0$–7 the reconstruction error equals the sum of the discarded eigenvalues; orthonormality of the loadings and agreement up to sign; the reconstruction does not change when the sign is flippedNumPyindependent implementation, analytical solution46rtol $10^{-10}$
Reproducibility with the seed——7—
Synthetic data (covariance of a two-dimensional point cloud of 40,000 points, component means, mean of Dirichlet random numbers, mean and maximum of the eigenvalues for pure noise)Theoretical valuesstatistical104 standard errors (±20 % for the maximum eigenvalue)

The checks on the screen comprise 154 steps, including the procedures in the boxes of Chapters 17 and 18 (38 of them cross-checks).

The computations added for the simple view (sim/latent.easy.js) were checked with 754 Node.js tests, and all succeeded. They were compared with the functions of the computation file and with simple computations rewritten within the tests (the nearest representative point, the objective function $J$, the closed-form expression for the eigenvalues of a 2×2 matrix, and the maximum on a fine grid of angles).

D.9 S08 Approximate Inference and MCMC (inference-mcmc)

D.9.1 Corresponding chapters, sections, and tabs

D.9.2 What is computed

D.9.3 Input ranges, upper limits, and random numbers

D.9.4 Simplifications

D.9.5 Conditions for instability and the behavior of the simulator

D.9.6 How and to what extent the numbers were checked

Table D.11: Numerical tests of S08 (656 tests; all passed)
Quantity checkedCompared againstTypeNumber of testsTolerance, etc.
$\ln Z$, mean, variance, and entropy of the targets (15 targets)SciPy’s quad; analytical solutions ($\ln B(a,b)$; for the double well, a closed form in terms of modified Bessel functions)independent implementation, analytical solution71atol $10^{-10}$–$10^{-9}$ (variance rtol $10^{-9}$)
Mode, curvature $\Lambda$, and the approximation of $\ln Z$ for the Laplace approximation; KL in both directions; ELBO (for the Beta type, also with the truncated $q$)SciPyindependent implementation, analytical solution168mode atol $10^{-7}$, $\Lambda$ rtol $10^{-7}$, KL and ELBO atol $10^{-8}$
The minimum of $\KL(p\,\|\,q)$ = matching of the mean and variance (it increases in the neighborhood)SciPyindependent implementation, analytical solution66atol $10^{-8}$
The minimum of $\KL(q\,\|\,p)$ (for each initial value)SciPy’s Nelder–Mead + BFGSindependent implementation62KL atol $10^{-8}$, $m,s$ $2\times10^{-4}$
KL in both directions and ELBO for hand-chosen $q$ (27 of them); $\ELBO+\KL=\ln Z$, $\KL\ge0$, $\ELBO\le\ln Z$SciPy’s quadindependent implementation, analytical solution186atol $10^{-8}$ (identities $10^{-12}$)
Transition matrix, stationary distribution, and detailed balance of the three-state Metropolis algorithmValues computed exactly with fractionsanalytical solution37$2\times10^{-16}$, $10^{-15}$
Autocorrelation function (FFT), integrated autocorrelation time and window, split-$\hat{R}$ and its $W$ and $B$Direct sums in NumPy, Sokal’s window written in Python, a different implementation in a shared libraryindependent implementation37$10^{-10}$–$10^{-12}$
Acceptance rule, rejection of proposals outside the support, reproducibility with the seed—analytical solution6—
Reproduction of the barrier example ($b=12$): the chains do not leave the wells, $\hat{R}=9.898$, $\tau_{\mathrm{int}}\lt10$, and $\hat{R}=1.003$ from the same pointRecorded values—4—
Invariance: the distribution does not change when 3000 points drawn exactly from the target are advanced 25 steps from the starting points (4 targets)KS test, $\chi^{2}$ teststatistical12$D\lt1.95/\sqrt{n}$, upper 0.1 %; first acceptance rate within 4 standard errors
Mean and variance of one long chainTrue valuesstatistical6Within 4 times the Monte Carlo standard error
Record of the computation time——1—

The estimate of the integrated autocorrelation time was recorded alongside the theoretical value $(1+\phi)/(1-\phi)$ for an AR(1) sequence (for $\phi=0.9$, estimated 14.06 versus theoretical 19.0), but this is a reference for comparing estimators and not a pass/fail test. The checks on the screen comprise 128 steps, including the procedures in the boxes of Chapters 20 and 21 (29 of them cross-checks).

The computations added for the simple view (sim/inference-mcmc.easy.js) were checked with 90 Node.js tests, and all succeeded. They were compared with the functions of the computation file, closed-form expressions (the cumulative distribution function of the Gaussian distribution, the probabilities of the mixture distribution), and the numbers of Example 21.6 in Chapter 21.

D.10 S09 Sequence Models (hmm)

D.10.1 Corresponding chapters, sections, and tabs

D.10.2 What is computed

D.10.3 Input ranges, upper limits, and random numbers

D.10.4 Simplifications

D.10.5 Conditions for instability and the behavior of the simulator

D.10.6 How and to what extent the numbers were checked

Table D.12: Tests of the S09 numbers (285 tests, all passed)
Quantity checkedCompared withTypeCountTolerance, etc.
$\alpha,\beta,\gamma,p(x_{1:3})$, $\omega$, and the Viterbi path for the two hand-calculation examplesNumPy and the full enumeration of the eight sequencesfull enumeration, independent implementation37rtol $10^{-13}$ to $10^{-15}$
Eight short sequences ($T\le8$; discrete and Gaussian, cases with 0 in $A$ or $\pi$, and $s=1$): likelihood and $\gamma$ of the scaled and logarithmic versions, and ViterbiFull enumeration in Python, and SciPy’s logarithmic-domain computationfull enumeration, independent implementation80rtol $10^{-13}$
Long sequences ($T=200$, 2000): likelihood, $\gamma$, and the Viterbi log probabilityLogarithmic-domain computation with SciPy’s logsumexpindependent implementation42likelihood rtol $10^{-12}$, $\gamma$ $2.5\times10^{-13}\cdot T$
Boundaries and anomalies (stopping for an observation sequence of probability 0, $\gamma$ equal to the prior marginal distribution at $s=0$, $\Delta=30$, ties)Analytical valuesanalytical solution10—
Kalman filter: sequential computation, $\mu_t,P_t$, steady-state values, $K_t\to K_\infty$ after 4000 steps, and $P$ growing by $q$ per step during missing observationsNumPy’s sequential computation, conditioning of the joint Gaussian distribution (NumPy’s solve), and closed-form expressionsindependent implementation, analytical solution95sequential $10^{-12}$, conditioning rtol $10^{-9}$, steady-state values rtol $10^{-12}$
Reproducibility of the seed. The sequence generated with the on-screen defaults ($\pi_1=0.95$, $A_{11}=0.97$, $A_{22}=0.95$, $s=0.7$, $T=100$) (degraded interval $t=69$–86, first 20 observations)Recorded values—5—
Synthetic data: frequencies of transitions and outputs, stationary distribution, mean and variance of the Gaussian output, mean, variance, and autocorrelation of the Kalman standardized prediction error, and coverageTheoretical values, $\chi^{2}$ teststatistical15about 4 standard errors (corrected by the integrated autocorrelation time for correlated quantities), upper 0.1 %
Record of computation time——1—

For the on-screen checks, 169 procedures (44 of them comparisons), including the operating procedures in the boxes of Chapter 22, were run under both http and file://, and the on-screen values (for example the default $\ln p(x_{1:T})=-102.6791$) were compared with the Node.js values. At 330 px, which corresponds to the chapter’s frame, the fields for the hand-calculation, Kalman, and generation formulas become wider than the frame, but everything can be read by scrolling horizontally within the field.

The computations added for the simple view (sim/hmm.easy.js) were checked with 287 Node.js tests, and all succeeded. They were compared with the functions of the computation file (including that the first record is the same sequence as under the default conditions of ① of the detailed view).

D.11 S10 Attention and Next-Token Generation (attention)

D.11.1 Corresponding chapters, sections, and tabs

D.11.2 What this simulator has and lacks

This simulator clearly distinguishes the following three things (this is also always displayed at the top of the screen).

Table D.13: What S10 covers and does not cover
① Calculation demo with hand-set weights② A small Transformer trained for this book③ The actual GPT
Where it istab attntab modelNot in this simulator
WeightsValues the reader enters in the numeric fields (the defaults are the same as the hand calculation in Chapter 24). Not trainedValues trained by next-token prediction (PyTorch, CPU, single precision)—
StructureOne head, $d_k=d_v=d_{\mathrm{model}}$ (2–4), $T$ 3–5, no bias and no output projection $\bm{W}_O$Decoder only, pre-LN, learned position embedding, GELU (tanh approximation), weight sharing between the embedding and the output projection. $n_{\mathrm{layer}}=2$, $n_{\mathrm{head}}=2$, $d_{\mathrm{model}}=32$ (16 per head), FFN hidden size 128, context length $T_{\max}=24$The same type (a decoder-only Transformer with next-token prediction), but the scale, the training data, and the training method are entirely different from those of this simulator
Number of parameters$3d_{\mathrm{model}}^{2}$ ($\bm{W}_Q,\bm{W}_K,\bm{W}_V$)28,384—
Vocabulary and data—Vocabulary of 67 (word level; including <bos>, <eos>, and the period). The training data are synthetic sentences for teaching purposes: only short sentences made mechanically from a table of 27 materials and 8 sentence patterns (no real texts are used). 6211 training sentences, 693 validation sentences—
Evaluation values—Validation perplexity 1.651 (expected value from the entropy rate of the generation rules 1.653; predicting the 693 validation sentences with the same rules gives 1.645, and the trained model is larger than this; bigram model 2.52, uniform 67). Top-1 accuracy on 144 contexts asking for a fact: 139/144 (62/67 for infrequent materials). Factual errors in generation with the material specified ($\tau=1$): 47/520 (9.0 %) for infrequent materialsThe numbers of this simulator are not the error rate of the actual GPT

The “bigram model” on the screen is a model that looks only at the immediately preceding token and counts the frequencies of the next token (with additive smoothing $\alpha=0.1$); it is neither a Transformer nor GPT. It is included only for comparison with ②.

Caution: Attention weights are not necessarily the reason for a decision

The attention weights shown on the screen are the proportions in which each position gathers information from the other positions, and they are intermediate quantities of the computation. You must not read a position with a large weight as “the reason the model decided so.” This caution is also written directly below the weight diagram on the screen.

D.11.3 What is computed

D.11.4 Input ranges, upper limits, random numbers, and training conditions

D.11.5 Simplifications

D.11.6 Conditions for instability and the behavior of the simulator

D.11.7 How and to what extent the numbers were checked

Table D.14: Tests of the S10 numbers (587 tests, all passed)
Quantity checkedCompared withTypeCountTolerance, etc.
That the weights and tables the simulator reads are the same as the original dataOriginal data—3—
For ①: $\bm{Q},\bm{K},\bm{V}$, scores, weights, outputs, row sums (30 examples), closed-form expressions for the defaults, properties of the mask, and equivariance under row permutation (50 examples)NumPy, SciPy’s softmax, closed-form expressionsindependent implementation, analytical solution204weights $10^{-14}$, outputs $10^{-13}$, closed-form expressions rtol $10^{-15}$
Forward propagation of ②: logits at the last position for 50 contexts. For one context of length 24, all intermediate values (embedding, attention weights, residuals, and outputs of each layer, the final LayerNorm, and the logits at all positions)The PyTorch model used for training (single precision)independent implementation14maximum absolute error of the logits $4.5\times10^{-6}$ (tolerance $10^{-4}$), embedding and weights $10^{-5}$, others $10^{-4}$
Attention weights and sequence log probabilities of ②. Row sums = 1 (deviation below $10^{-14}$), weights at future positions = 0 (exact), and the logits at earlier positions not depending on later tokens because of the causal maskAn independent NumPy (double precision) forward propagation, and PyTorch log probabilitiesindependent implementation, analytical solution29weights $10^{-12}$, log probabilities $10^{-11}$ (against PyTorch, $10^{-3}$)
Next-token distributions (temperature, top-k, top-p; 78 examples): the set and order of the remaining words, the distribution, and the sampling result for given uniform random numbersA reference written with the same rules as the generation at training timeindependent implementation320distribution $10^{-14}$
Classification of generated sentences (288 sentences). That all sentences of the training data are classified as “correct”A reference with the same rules as the classification used in the evaluationindependent implementation6all agree
The table of the bigram model, reproducibility of the seed——8—
Frequencies of sampling (20000 draws each for three settings)$\chi^{2}$ teststatistical3significance level 0.001

Of the evaluation values of ②, the accuracy and the error rate in generation were measured in Python just once after training, and were not re-measured inside the browser (the error rate in generation was counted on sentences generated with Python’s random numbers, so it cannot be reproduced with the simulator’s random numbers). The validation perplexity of 1.65 was recomputed from the 693 validation sentences by a NumPy (double precision) forward propagation using the simulator’s weights, giving 1.6506 (2.5249 for the bigram model). For the on-screen checks, 179 procedures (42 of them comparisons), including the operating procedures in the boxes of Chapters 24–26, were run under both http and file://, and it was also confirmed that the formula of “Putting the current numbers into the formula” fits within the frame at 310 and 352 px, which correspond to the chapter’s frame.

The computations added for the simple view (sim/attention.easy.js) were checked with 276 Node.js tests, and all succeeded. They were compared with the functions of the computation file (forward, nextDist, generate, judge), with $\mathrm{softmax}(o/\tau)$ rewritten within the tests, and with the generated sequence under the default of the detailed view (seed 20261112).

D.12 Summary of What Was Not Checked and Limitations

D.12.1 Environments not checked

D.12.2 Known limitations

D.12.3 Beyond the range checked