Every Bayesian workflow eventually hits the same wall: pm.sample() runs for a while, prints a progress bar, and hands back an object full of numbers. The moment divergences appear, or a chain stalls at max tree depth, or a model compiles for two minutes before drawing a single sample, the abstractions stop helping. You need to know what the library actually did: which graph it built, what it compiled, which process holds which chain.

Most people then reach for docs, and the docs explain the API, not the machinery. The interesting part of PyMC is not pm.Normal — it is the journey a model takes from a Python with block to a compiled C kernel inside a multiprocessing worker. That journey is spread across a deceptively small package: the model core, the distribution zoo, the sampling dispatcher, and the step methods.

This tour reads the real PyMC tree on the main branch as of December 2026. Every path and line number below was checked against the repository before being cited — nothing is reconstructed from memory. The two diagrams were drawn from that same reading pass, so you can keep them open as a map while we walk the code.

PyMC overview architecture: Model context, distribution library, sampling API, step methods and the pytensor bridge

The five provinces of PyMC: the model core turns a with-block into a symbolic graph, the distribution library supplies random variables, the sampling API dispatches step methods, the HMC engine does the math, and the pytensor bridge compiles everything.

Reading the overview from left to right:

  • Model, L1680 — the user-facing model class; it registers every random variable you declare inside the with pm.Model() block and tracks coords, dims and named vars.
  • modelcontext, L131 — the resolver that lets every helper function find the “current” model without you passing it explicitly; it reads a thread-local stack maintained by the metaclass at ContextMeta, L336.
  • Distribution, L471 — the base class built on a custom DistributionMeta (L87); its .dist() classmethod at L583 constructs symbolic RVs without registering them in a model.
  • Normal, L444 — one of 56 classes in continuous.py, the single largest distribution module at 4,259 lines.
  • sample, L631 — the pm.sample() entry point in a 2,044-line module that also owns step-method auto-assignment and initialization.
  • CompoundStep, L280 — the wrapper that lets one chain advance heterogeneous variable blocks with different steppers in a single iteration.
  • NUTS, L43 — the No-U-Turn sampler: recursive binary tree doubling over a leapfrog trajectory, with a hard cap of max_treedepth=10.
  • ValueGradFunction, L143 — the compiler that turns the model’s log-probability graph into one callable returning both the value and the gradient over a raveled point vector.
  • DualAverageAdaptation, L41 — Nesterov dual averaging for the step size, with the smoothing anchor mu = log(10 * initial_step).
PyMC detail graph: model core internals, IR transforms, distribution families, sampling API, HMC engine, step methods and pytensor bridge

The detail view follows one draw end to end: initial points, step-method dispatch, the HMC engine, per-chain worker processes, and the graph transforms that sit between the model and pytensor.

The model context: a with-block that builds a symbolic graph

PyMC’s famous with pm.Model(): syntax is enforced by machinery, not magic. ContextMeta at L336 of pymc/model/core.py is a metaclass whose __enter__/__exit__ maintain a stack of active models; modelcontext() at L131 returns the top of that stack so that free functions like pm.Deterministic or pm.set_data can locate the model without an explicit argument. Model itself (L1680) extends BaseModel (L362), and the file also defines FrozenModel (L2236) for models whose dims and data have been pinned, plus BlockModelAccess (L2352) used when composing submodels.

Variables enter the graph through add_named_variable (L2196), which records dims and attaches the variable to the model’s namespace. Dims are resolved through shape_from_dims (L907) and user coords via the coords property (L895). The data-container story is handled by set_data (L982): it swaps the values behind shared variables so you can refit the same graph on new data without rebuilding it. Everything the samplers consume, though, flows through ValueGradFunction (L143) — it wraps the log-probability tensor plus its gradient into a single callable over a flat vector, which is exactly the interface the HMC and Metropolis kernels want.

Distributions: one metaclass, roughly 101 RV classes

The distribution layer is where PyMC’s design pays off. pymc/distributions/distribution.py defines DistributionMeta (L87), an ABC metaclass that lets classes like Normal work both as constructors and as parameter-inspectable types, and SymbolicRandomVariable (L216), the pytensor Op base that makes random variables first-class graph nodes with RNG state. Distribution (L471) hangs dist() (L583) off the class so you can build unregistered RVs, and the Discrete (L710) and Continuous (L720) markers partition support types.

The counts are worth internalizing: continuous.py carries 56 classes (4,259 lines) from Normal, L444 to HalfNormal (L821); discrete.py adds 14 integer-support classes; multivariate.py adds 31 including MvNormal (L188). Around that core sit wrapper distributions that manipulate log-probabilities rather than define new math: Mixture (L356) switches between components, Censored (L79) folds the log-CDF mass into interval tails, and Truncated (L279) renormalizes a base RV to a bounded support. Shape handling is centralized in shape_utils.py: shape_from_dims (L163) turns dim names into broadcast shapes, and change_dist_size (L235) rewrites an existing RV node to a new size instead of rebuilding it. Every distribution also declares a moment in distributions/moments/means.py, which is what initial points and prior-default plots use.

Inside pm.sample(): dispatch, workers, and a DataTree out

sample() (L631 in pymc/sampling/mcmc.py) is the busiest function in the package. Its defaults encode real policy: draws=1000, tune falling back to 1000, chains defaulting to max(cores, 2), and cores documented as the CPU count capped at 4. It accepts a nuts_sampler literal restricted to "pymc", "nutpie", "numpyro", "blackjax", and its init="auto" path delegates to init_nuts (L1761), which tries initialization strategies and jitters starts with jitter_max_retries=10 and an optimization budget of n_init=200_000. Initial points themselves come from make_initial_point_fn (L130 in pymc/initial_point.py), which evaluates each RV’s moment and applies per-chain jitter.

Step-method selection is centralized in assign_step_methods (L257): all-continuous models go straight to NUTS, binary variables get BinaryGibbsMetropolis, categorical ones CategoricalGibbsMetropolis, and anything left over falls back to gradient-free steppers. Once steppers are picked, _mp_sample (L1588) fans chains out to worker processes; pymc/sampling/parallel.py provides ProcessAdapter (L283) and ParallelSampler (L465) for the per-chain protocol, and population samplers get their own stepper in sampling/population.py. Results are reassembled into a DataTree (or a legacy MultiTrace if you opt out), and convergence diagnostics such as divergence and max-treedepth warnings are produced by run_convergence_checks (L64 in pymc/stats/convergence.py) before the object is returned. Forward simulation lives in pymc/sampling/forward.py: draw (L397), sample_prior_predictive (L485) and sample_posterior_predictive (L607) reuse the same compile path but keep RNG updates flowing so repeated draws advance rather than repeat.

NUTS internals: trees, divergences and dual averaging

The NUTS implementation is compact — 489 lines in pymc/step_methods/hmc/nuts.py. The class (L43) inherits from BaseHMC (L73 in base_hmc.py), which owns the shared Hamiltonian machinery and the DivergenceInfo namedtuple (L46) that encodes why a trajectory blew up. Each iteration builds a binary tree of leapfrog states; doubling stops when the no-U-turn criterion fails or the depth hits max_treedepth=10 (with an earlier stop at early_max_treedepth=8 during warmup). The integrator is CpuLeapfrogIntegrator (L41 in integration.py), and the kinetic energy comes from a mass-matrix family in quadpotential.py: diagonal adaptation in QuadPotentialDiagAdapt (L211) and full-covariance adaptation in QuadPotentialFullAdapt (L748).

Step size adaptation is textbook dual averaging, spelled out in DualAverageAdaptation (L41 in step_sizes.py): the update uses mu = log(10 * initial_step), weights each observation by w = 1 / (count + t0), and blends the log step into a smoothed bar with count**-k. The constructor defaults arrive from NUTS itself: target_accept=0.8, gamma=0.05, k=0.75, t0=10. What users see as the stats table is declared explicitly in stats_dtypes_shapes (L109-L129) — nineteen per-draw statistics including mean_tree_accept, diverging, energy, tree_size, model_logp and wall-clock timings, which is why every draw carries that diagnostic payload.

From a 2,721-line model core to 19 sampler stats

A few numbers make the engineering trade-offs concrete. The model core (pymc/model/core.py) is 2,721 lines — about twice the NUTS engine — because it owns contexts, dims, coords, data containers, and the value/grad compiler in one file. The distribution library is bigger still: continuous.py alone is 4,259 lines with 56 classes, while the entire Metropolis family fits in 1,259 lines across six proposal types (NormalProposal, UniformProposal, CauchyProposal, LaplaceProposal, PoissonProposal, MultivariateNormalProposal, L79-L106 of metropolis.py), plus DEMetropolisZ (L1032) and the classic tune() heuristic (L361) that scales proposal widths by acceptance rate.

The pytensor bridge in pymc/pytensorf.py (1,153 lines) is the quiet hero: compile (L936) normalizes backend and mode kwargs into one entry point, make_shared_replacements (L445) clones graphs so steppers can hot-swap points through shared variables, and collect_default_updates (L755) harvests RNG update expressions so forward draws remain reproducible. Model-to-IR conversion is symmetrical — fgraph_from_model (L139) and model_from_fgraph (L301) in pymc/model/fgraph.py, with clone_model (L387) for safe copies — and that IR layer is what makes causal edits possible: observe (L46) and do (L125) in pymc/model/transform/conditioning.py, plus freeze_dims_and_data (L53) before compilation. Introspection closes the loop: ModelGraph (L238 in model_graph.py) drives both model_to_graphviz (L658) and a networkx export at L564, find_MAP (L177 in pymc/tuning/starting.py) ships its objective into scipy optimizers via scipy_interface.py, and printing.py registers pretty-printers with IPython (L365) so models render nicely in notebooks.

Honest Limits

This tour reflects the main branch at one point in time; line numbers drift as the project moves, so treat them as coordinates for this snapshot rather than permanent anchors. The read covered the model, distributions, sampling and step-methods directories in depth; variational inference (ADVI at L357 of variational/inference.py, the fit() facade at L699), sequential Monte Carlo (sample_smc at L42 of smc/sampling.py), and the log-probability subpackage (logp at L105 of logprob/basic.py) were skimmed for architecture only — their internals deserve their own write-up. The two diagrams are hand-authored from this reading and validated against the file tree, not auto-generated; they compress structure, and some cross-module edges (for example, everything touching pytensor rewriting passes) are simplified. Finally, performance numbers were not benchmarked here — the line and class counts come from the working tree at commit 92dbdb6cde6c, and any rebuild of this analysis on a future commit should re-run the same greps before quoting them.

Watch PyShine on YouTube

Contents