Experiments#
High-level experiment API built on top of tinto.runners.
This module consolidates the notebook boilerplate of parameter sweeps +
Monte-Carlo aggregation + plotting into a single Experiment
object. The design is deliberately thin: the heavy lifting stays in
tinto.runners and the Config/Graph/scheduler/solver stack, while
Experiment adds three amenities:
Sweep composition: a 1-D
Iteratorfor one varying parameter, and a cartesianProductIteratorobtained via*for joint sweeps.Campaign aggregation:
Experiment + Experiment(and thereforesum()) merges campaigns into a single object.Result handling:
Experiment.run()fillsExperiment.results, a structured nested dict. From there,Experiment.plot(),Experiment.to_dict()andExperiment.to_csv()expose the common consumption paths.
Matplotlib and tqdm are imported lazily; neither is a hard
dependency.
- class tinto.experiments.Experiment(name: str | None = None, iterator: Iterator | ProductIterator | None = None, **params: Any)[source]#
Bases:
objectHigh-level entry point binding sweeps to a Monte-Carlo runner.
An
Experimentbundles one or more campaigns. Each campaign pairs a name, an optionalIterator(orProductIterator) sweeping one or several parameters, and a dict of fixed keyword arguments forwarded to the runner. Combining experiments with+(orsum()) concatenates their campaigns;run()executes every campaign sequentially and stores the per-replica moments underresults.- Parameters:
name (
str, optional) – Campaign label, used as key inresultsand as plot legend.iterator (
IteratororProductIterator, optional) – Sweep definition. IfNone, the campaign is a single point (useful only when combined with others).**params (keyword arguments) – Runner arguments that stay fixed across the sweep (typically
starter,scheduler,solver,n_trials).
Examples
A minimal 1-D sweep evaluated with an injected dummy runner:
>>> def dummy(n): ... return {"steps": (float(n), 0.0, 0.0), "activations": (0.0, 0.0, 0.0)} >>> exp = Experiment("demo", iterator=Iterator("n", [1, 2, 3])) >>> _ = exp.run(runner=dummy, progress=False) >>> exp.results["demo"]["axes"] ('n',) >>> exp.results["demo"]["data"][(2,)]["steps"] (2.0, 0.0, 0.0)
Two campaigns combined with
+keep distinct entries inresults:>>> a = Experiment("A", iterator=Iterator("n", [1])) >>> b = Experiment("B", iterator=Iterator("n", [2])) >>> sorted((a + b).to_dict_keys()) ['A', 'B']
- _infer_x(x, hue, selected)[source]#
Resolve an omitted x when the selected campaigns leave no ambiguity.
Collects every axis appearing in the selected campaigns, drops hue if present, and returns the unique remaining axis if any. Otherwise leaves x untouched.
- _select(campaign)[source]#
Return an ordered
{name: camp}dict filtered by campaign.campaign is
None(all), a string (one), or an iterable of strings (a subset). Unknown names are dropped silently.
- _xy_sigma(metric, x, hue, campaign)[source]#
Yield
(label, xs, ys, sigma)for each selected series.Pulls the per-point mean and variance via
series()and derives the standard error of the meansigma_i = sqrt(var_i / (n_trials - 1)). Shared byfit()andfit_fractions().
- fit(metric: str = 'steps', basis=None, x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None) dict[source]#
Fit a law to a metric’s mean across campaigns, with error bars.
Convenience bridge to
tinto.estimate. For each series (same{label: ...}selection asseries()/plot()), it pulls the per-point mean and variance, derives the standard error of the meansigma_i = sqrt(var_i / (n_trials - 1))(then_trials / (n_trials - 1)term turns the population variance returned bytinto.runners.mc()into the unbiased estimate), and runstinto.estimate.fit().The default basis is affine (
a*x + b); pass a custom basis such astinto.estimate.power_basis()for inverse-power lawsf(k) = a/k + b/k**2. The fitted coefficients can then be turned into exact fractions withtinto.estimate.recover().- Parameters:
- Returns:
{label: fit_dict}with the same labels asseries(), each value being the dict returned bytinto.estimate.fit().- Return type:
- Raises:
ValueError – If a selected campaign has no recorded
n_trials(e.g. it was run with a custom runner that does not take it).
Examples
A dummy runner with exactly affine means and unit variance: the fit recovers the slope and intercept.
>>> import numpy as np >>> def dummy(n, n_trials): ... return {"steps": (2.0 * n + 1, 1.0, 0.0), ... "activations": (0.0, 1.0, 0.0)} >>> exp = Experiment("demo", iterator=Iterator("n", [1, 2, 3]), n_trials=100) >>> _ = exp.run(runner=dummy, progress=False) >>> r = exp.fit(metric="steps") >>> np.round(r["demo"]["beta"], 6).tolist() [2.0, 1.0] >>> r["demo"]["dof"] 1
- fit_fractions(metric: str = 'steps', basis=None, x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None, **kwargs) dict[source]#
Recover exact fractions for a metric’s law, coefficient by coefficient.
Same
(x, y, sigma)assembly asfit(), but forwarded totinto.estimate.fit_fractions(), which jointly fits, anchors the surest coefficient as a fraction, and refits the rest (see that function for the anchor-and-refit rationale). Extra keyword arguments (k,max_denominator,resolution, …) pass straight through.- Parameters:
- Returns:
{label: result}with the same labels asseries(), each value the dict returned bytinto.estimate.fit_fractions().- Return type:
Examples
>>> def dummy(n, n_trials): ... return {"steps": ((2 / 3) * n - 1 / 3, 1.0, 0.0), ... "activations": (0.0, 1.0, 0.0)} >>> exp = Experiment("demo", iterator=Iterator("n", range(10, 60)), n_trials=10**6) >>> _ = exp.run(runner=dummy, progress=False) >>> exp.fit_fractions(metric="steps")["demo"]["fractions"] [Fraction(2, 3), Fraction(-1, 3)]
- plot(metric: str = 'steps', stat: str = 'mean', x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None, scale: str = 'linear', ax=None, **plot_kwargs)[source]#
Light matplotlib rendering of a metric across campaigns.
Thin wrapper around
series(): pulls the{label: (xs, ys)}dict and renders one line per entry on ax.- Parameters:
metric (
str, default=’steps’) – Key into the runner’s output dict ("steps"or"activations"when usingtinto.runners.mc()).stat (
str, default=’mean’) – One of"mean","var","m3"; indexes the 3-tuple returned by the runner.x (
str, optional) – Name of the parameter to place on the x-axis. When omitted, inferred from the selected campaigns: if exactly one axis (excluding hue) appears, it is used. Campaigns missing the resolved axis are skipped.hue (
str, optional) – Name of a second parameter to use as series. IfNone, each campaign contributes a single line.campaign (
str, iterable of strings, orNone,) – default=``None`` Restrict to a subset of campaigns. Seeseries().scale (
str, default=’linear’) – One of"linear","logx","logy","loglog". Applied viaset_xscale()/set_yscale()after the lines are drawn.ax (
matplotlib.axes.Axes, optional) – Existing axes. Created viamatplotlib.pyplot.gca()whenNone.**plot_kwargs (keyword arguments) – Forwarded to
matplotlib.axes.Axes.plot(). User kwargs take precedence over the ones set internally (notablylabel), so passinglabel="foo"overrides the auto-generated labels — shared across every series, which produces a duplicated legend when more than one line is drawn. For per-series customization, preferseries()+ a manual matplotlib loop.
- Returns:
The axes drawn on.
- Return type:
Examples
>>> import matplotlib.pyplot as plt >>> def dummy(n): ... return {"steps": (float(n), 0.0, 0.0), "activations": (0.0, 0.0, 0.0)} >>> exp = Experiment("demo", iterator=Iterator("n", [1, 2, 3])) >>> _ = exp.run(runner=dummy, progress=False) >>> fig, ax = plt.subplots() >>> _ = exp.plot(x="n", ax=ax) >>> ax.get_xlabel(), ax.get_ylabel() ('n', 'steps (mean)') >>> len(ax.lines) 1 >>> plt.close(fig)
Cartesian-product campaigns light up multiple series via hue:
>>> def dummy2(n, kind): ... return {"steps": (float(n) + {"a": 0.0, "b": 1.0}[kind], 0.0, 0.0), ... "activations": (0.0, 0.0, 0.0)} >>> exp2 = Experiment( ... "multi", ... iterator=Iterator("n", [1, 2]) * Iterator("kind", ["a", "b"]), ... ) >>> _ = exp2.run(runner=dummy2, progress=False) >>> fig, ax = plt.subplots() >>> _ = exp2.plot(x="n", hue="kind", ax=ax) >>> len(ax.lines) 2 >>> plt.close(fig)
When x is omitted it is inferred from the campaign axes. Passing hue alone is enough to disambiguate a 2-D campaign:
>>> fig, ax = plt.subplots() >>> _ = exp.plot(ax=ax) >>> _ = exp2.plot(hue="kind", ax=ax) >>> [line.get_label() for line in ax.lines] ['demo', 'multi / kind=a', 'multi / kind=b'] >>> plt.close(fig)
Ambiguous axes (two candidates, no hue), explicit x not in axes, hue not in axes, or a 2-D campaign with x but no hue, all skip silently:
>>> fig, ax = plt.subplots() >>> _ = exp2.plot(ax=ax) >>> _ = exp.plot(x="unknown", ax=ax) >>> _ = exp.plot(x="n", hue="unknown", ax=ax) >>> _ = exp2.plot(x="n", ax=ax) >>> len(ax.lines) 0 >>> plt.close(fig)
Filter to one campaign and pick a log-log scale. When ax is omitted,
matplotlib.pyplot.gca()is used:>>> bis = Experiment("bis", iterator=Iterator("n", [1, 2, 3, 4])) >>> both = (exp + bis).run(runner=dummy, progress=False) >>> ax = both.plot(x="n", campaign="bis", scale="loglog") >>> ax.get_xscale(), ax.get_yscale() ('log', 'log') >>> len(ax.lines) 1 >>> plt.close("all")
Plot kwargs take precedence over the auto-generated
label:>>> fig, ax = plt.subplots() >>> _ = exp.plot(x="n", label="override", color="red", ax=ax) >>> ax.lines[0].get_label() 'override' >>> plt.close(fig)
- report(metric: str = 'steps', basis=None, names=None, x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None, **kwargs)[source]#
Tabulate recovered fractions across campaigns, ready to display.
Runs
fit_fractions()and hands the result totinto.estimate.fractions_table(), which returns a table that prints as aligned ASCII in a terminal and renders as HTML in a notebook (Jupyter calls its_repr_html_automatically — the same.autospirit astqdm, with no environment sniffing). Each row shows, per coefficient, eithervalue -> fraction(anchored) orvalue +/- error(left free), pluschi2_red,pvalueand a one-word fit verdict; ahighverdict means the fractions are not to be trusted.Coefficient names default to
tinto.estimate.basis_names()applied to basis —["1", "x"]for the affine default,["x^-1", "x^-2"]forpower_basis([-1, -2]), positionalc0, c1, ...for an anonymous custom basis. Override with names.- Parameters:
metric (see
fit_fractions().)basis (see
fit_fractions().)x (see
fit_fractions().)hue (see
fit_fractions().)campaign (see
fit_fractions().)names (list of
str, optional) – Column names for the coefficients. Defaults totinto.estimate.basis_names()of basis.**kwargs – Forwarded to
fit_fractions()(k,max_denominator,resolution, …).
- Returns:
Printable / notebook-displayable table.
- Return type:
tinto.estimate._FractionTable
Examples
>>> def dummy(n, n_trials): ... return {"steps": ((2 / 3) * n - 1 / 3, 1.0, 0.0), ... "activations": (0.0, 1.0, 0.0)} >>> exp = Experiment("demo", iterator=Iterator("n", range(10, 60)), n_trials=10**6) >>> _ = exp.run(runner=dummy, progress=False) >>> print(exp.report()) campaign | n | 1 | chi2_red | pvalue | fit ---------+---------------+-----------------+----------+--------+---- demo | 0.6667 -> 2/3 | -0.3333 -> -1/3 | 0.00 | 1 | low
- residuals(metric: str = 'steps', basis=None, normalize: bool = True, x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None) dict[source]#
Per-series fit residuals, for eyeballing noise vs. leftover structure.
Same
(x, y, sigma)assembly asfit(), then returns the residuals of the linear basis fit (affine by default). The whole point is to look: under a correct model the normalized residuals are iidN(0, 1)scatter, whereas a trend, curvature, or a run of same-sign points across x betrays a missing term that the scalarchi2_redonly hints at.Residuals follow the usual convention
y - model(observed minus predicted), so a point above the fit reads positive and the plotted curvature matches the data’s: a concave law shows a concave (∩) residual, not an inverted one.Normalized residuals
(y - model) / sigmaare the right thing to plot: they are dimensionless and weighted by each point’s error bar, so heteroscedasticsigma_ido not distort the picture. Passnormalize=Falsefor raw residualsy - modelin the metric’s own units. Note both the sign convention and the weighted fit (small-sigmapoints dominate the line) shape what you see — with a stronglyn-dependentsigmathe fitted line tilts toward the low-nend.Caution
Residuals are an exploratory tool. Choosing a new basis term because you saw it in the residuals and then testing that same term on the same data is double-dipping: the resulting
pvalue/tare optimistic. Confirm a term either on fresh data or by checking that its coefficient lands on a clean, stable fraction — not by the in-sample fit improving (it always does).- Parameters:
- Returns:
{label: (xs, resid)}with the same labels asseries(); xs and resid are plain Python lists, sorted by x. Plot one withplt.plot(*exp.residuals()[label], "o").- Return type:
Examples
On exactly affine data the residuals vanish (pure-noise limit):
>>> import numpy as np >>> def dummy(n, n_trials): ... return {"steps": (2.0 * n + 1, 1.0, 0.0), ... "activations": (0.0, 1.0, 0.0)} >>> exp = Experiment("demo", iterator=Iterator("n", [1, 2, 3]), n_trials=100) >>> _ = exp.run(runner=dummy, progress=False) >>> xs, res = exp.residuals()["demo"] >>> xs [1, 2, 3] >>> bool(np.allclose(res, 0.0)) True
- run(runner: Callable | None = None, progress: bool = True) Experiment[source]#
Execute every campaign sequentially and fill
results.- Parameters:
runner (callable, optional) – Function called with the per-point parameters and returning a dict
{metric: (mean, var, m3)}. Defaults totinto.runners.mc().progress (
bool, default=True) – Show atqdmprogress bar whentqdmis installed. Silently ignored otherwise.
- Returns:
Self, for chaining.
- Return type:
Examples
With the default runner (
tinto.runners.mc()) on a small line-graph campaign with no sweep:>>> from tinto.graphs import line >>> from tinto.configs import make as make_config >>> from tinto.starters import from_graph >>> from tinto.schedulers import shuffled >>> from tinto.solvers import make as make_solver >>> from tinto.io import set_seed >>> set_seed(0) >>> Config = make_config() >>> starter = from_graph(Config, color=0)(line(5)) >>> exp = Experiment( ... "bare", ... starter=starter, ... scheduler=shuffled(), ... solver=make_solver(), ... n_trials=5, ... ) >>> _ = exp.run() >>> sorted(exp.results["bare"]["data"][()].keys()) ['activations', 'steps']
resultsraises if accessed beforerun():>>> Experiment("untouched").results Traceback (most recent call last): ... RuntimeError: Experiment.run() must be called before accessing results.
- series(metric: str = 'steps', stat: str = 'mean', x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None) dict[str, tuple[list, list]][source]#
Extract
{label: (xs, ys)}without any plotting.Same selection logic as
plot(): campaigns missing x, a hue not in the axes, or a 2-D campaign without a hue are skipped. Labels arecampaign_namefor 1-D campaigns,"{campaign_name} / {hue}={hue_value}"for 2-D campaigns split by hue.When x is omitted, it is inferred from the selected campaigns: if exactly one axis (excluding hue) appears across them, it is used. If zero or more than one, the call behaves as if x was unknown (empty result).
- Parameters:
- Returns:
Insertion-ordered mapping
{label: (xs, ys)}. Both xs and ys are plain Python lists, sorted by x.- Return type:
Examples
>>> def dummy(n): ... return {"steps": (float(n), 0.0, 0.0), "activations": (float(n * 2), 0.0, 0.0)} >>> a = Experiment("A", iterator=Iterator("n", [1, 2, 3])) >>> b = Experiment("B", iterator=Iterator("n", [1, 2, 3])) >>> exp = (a + b).run(runner=dummy, progress=False) >>> exp.series(x="n", metric="steps") {'A': ([1, 2, 3], [1.0, 2.0, 3.0]), 'B': ([1, 2, 3], [1.0, 2.0, 3.0])}
Selecting a single campaign:
>>> exp.series(x="n", metric="activations", campaign="A") {'A': ([1, 2, 3], [2.0, 4.0, 6.0])}
Or a subset. Unknown names silently drop:
>>> exp.series(x="n", campaign=["B", "ghost"]) {'B': ([1, 2, 3], [1.0, 2.0, 3.0])}
With hue on a cartesian-product campaign, labels combine campaign name and hue value:
>>> def dummy2(n, kind): ... return {"steps": (float(n) + {"a": 0.0, "b": 1.0}[kind], 0.0, 0.0), ... "activations": (0.0, 0.0, 0.0)} >>> prod = Experiment( ... "P", iterator=Iterator("n", [1, 2]) * Iterator("kind", ["a", "b"]) ... ) >>> _ = prod.run(runner=dummy2, progress=False) >>> prod.series(x="n", hue="kind") {'P / kind=a': ([1, 2], [1.0, 2.0]), 'P / kind=b': ([1, 2], [2.0, 3.0])}
x is inferred when unambiguous, so passing it is optional on simple 1-D campaigns:
>>> exp.series() == exp.series(x="n") True
- to_csv(target) None[source]#
Write flat CSV rows (one per data point) to target.
Columns:
campaign, then every axis seen in any campaign (empty cells when absent), then{metric}_{stat}forstepsandactivations×mean,var,m3.- Parameters:
target (path-like or text stream) – Opened file path (string /
Path) or any object exposing a.write()method (io.StringIO, an opened file, …).
Examples
>>> import io >>> def dummy(n): ... return {"steps": (float(n), 0.0, 0.0), "activations": (float(n+1), 0.0, 0.0)} >>> exp = Experiment("demo", iterator=Iterator("n", [1, 2])) >>> _ = exp.run(runner=dummy, progress=False) >>> buf = io.StringIO() >>> exp.to_csv(buf) >>> header, *rows = buf.getvalue().splitlines() >>> header 'campaign,n,steps_mean,steps_var,steps_m3,activations_mean,activations_var,activations_m3' >>> len(rows) 2 >>> rows[0] 'demo,1,1.0,0.0,0.0,2.0,0.0,0.0'
Two campaigns sharing the same axis keep a single column for it:
>>> combined = exp + Experiment("bis", iterator=Iterator("n", [3])) >>> _ = combined.run(runner=dummy, progress=False) >>> buf = io.StringIO() >>> combined.to_csv(buf) >>> buf.getvalue().splitlines()[0].split(",").count("n") 1
A filesystem path is also accepted:
>>> import tempfile >>> from pathlib import Path >>> with tempfile.TemporaryDirectory() as td: ... path = Path(td) / "out.csv" ... exp.to_csv(path) ... "steps_mean" in path.read_text() True
- to_dict() dict[source]#
Return a deep copy of the internal result dict.
Examples
>>> def dummy(n): ... return {"steps": (float(n), 0.0, 0.0), "activations": (0.0, 0.0, 0.0)} >>> exp = Experiment("demo", iterator=Iterator("n", [1, 2])) >>> d = exp.run(runner=dummy, progress=False).to_dict() >>> d["demo"]["data"][(1,)]["steps"] (1.0, 0.0, 0.0)
- class tinto.experiments.Iterator(parameter: str, values: Iterable[Any], name: str | None = None, process: Callable[[Any], Any] | None = None)[source]#
Bases:
objectOne-dimensional parameter sweep.
Yields, at each step, a triplet
(kwargs, display_names, display_values)where kwargs is a single-entry dict ready to be passed as keyword arguments to the runner, and the two tuples carry the display metadata used byExperiment.plot()andExperiment.to_csv(). For a 1-D iterator both tuples have length one; for aProductIteratorobtained via*they have one entry per dimension.- Parameters:
parameter (
str) – Keyword argument name the runner expects.values (iterable) – Raw values to sweep. Stored as a list.
name (
str, optional) – Human-readable axis label for plots. Defaults to parameter.process (callable, optional) – Maps each raw value to the object actually passed to the runner (e.g. build a
Starterfrom an integer n). Defaults to identity.
Examples
>>> it = Iterator("n", [1, 2, 3]) >>> len(it) 3 >>> list(it) == [ ... ({"n": 1}, ("n",), (1,)), ... ({"n": 2}, ("n",), (2,)), ... ({"n": 3}, ("n",), (3,)), ... ] True
A custom
nameandprocesslet the display label decouple from the runner keyword:>>> it2 = Iterator("n", [2, 4], name="$n$", process=lambda v: v * 10) >>> [kwargs for (kwargs, _, _) in it2] [{'n': 20}, {'n': 40}] >>> [names for (_, names, _) in it2] [('$n$',), ('$n$',)]
- class tinto.experiments.ProductIterator(iterators: Iterable)[source]#
Bases:
objectCartesian product of
Iterator(and/orProductIterator) instances.Yields the same triplet as
Iteratorbut with one entry per dimension, in left-to-right order. The rightmost dimension varies fastest (standarditertools.product()behavior).- Parameters:
iterators (list of
IteratororProductIterator) – Dimensions of the product. Stored flat: passing aProductIteratorin the list merges its inner iterators.
Examples
>>> it_n = Iterator("n", [1, 2]) >>> it_p = Iterator("p", [0.1, 0.5]) >>> prod = it_n * it_p >>> len(prod) 4 >>> [values for (_, _, values) in prod] [(1, 0.1), (1, 0.5), (2, 0.1), (2, 0.5)]
Multiplication chains without nesting:
>>> prod3 = it_n * it_p * Iterator("k", [10]) >>> [it.parameter for it in prod3.iterators] ['n', 'p', 'k'] >>> len(prod3) 4
Direct construction with a nested
ProductIteratorin the list flattens it transparently:>>> nested = ProductIterator([prod, Iterator("w", [0])]) >>> [it.parameter for it in nested.iterators] ['n', 'p', 'w']