Repository navigation
Strip the inference layer to IDProblem and forecast, and pair a model with its data - #373
Conversation
… a model with its data The method layer predates the `as_turing_model` directive. Every part of it wrapped one Turing call, none was used outside its own tests, and two of them raised `MethodError` on the FlexiChains chain `sample` now returns. `types.jl`, `NUTSampler.jl`, `DirectSample.jl`, `apply_method.jl`, `IDObservables.jl`, `get_param_array.jl`, `post-inference.jl` and `condition_model` all go, and with them `ADTypes`, `AbstractMCMC`, `AdvancedHMC`, `MCMCChains` and `DataFramesMeta`. `as_turing_model(::IDModel, y)` now covers a vector and a `NamedTuple` of streams as well as a matrix, so the shape comes from the data rather than from a restated `length(y)`. `_obs_data_shape` moves to `compose.jl` and the `_shape` that duplicated its matrix case goes, leaving one shape path shared with `forecast`. `IDProblem` is rebuilt on top of that as a model paired with its data. `tspan` goes: every call site restated the data's own length, and the `data_requirements` path that read it now reads the full shape off the data instead, so a stratified problem reports on the stratum axis. The pairing earns its place by printing: the component tree from the package's own printer, plus a line summarising the data, where a conditioned `DynamicPPL.Model` renders as its full nested parametric type with every observation dumped inline. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This comment has been minimized.
This comment has been minimized.
…play claiming streams The two-argument `as_turing_model` is public, so data it cannot read a length from now raises an `ArgumentError` naming the type rather than a `MethodError` from a private helper. An `IDProblem`'s data line called a `NamedTuple`'s entries streams. They are for a `Split`, but a `BinomialError` reads `(y, N)` as one stream's named fields, so the line now names the entries without claiming which and leaves the answer to `data_requirements`. The same confusion in `_obs_data_shape` itself is older than this branch and is filed separately. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This comment has been minimized.
This comment has been minimized.
Try this Pull Request!Option 1: Julia Package ManagerOpen Julia and type: import Pkg
Pkg.activate(temp=true)
Pkg.add(url="https://github.com/EpiAware/ComposableTuringIDModels.jl", rev="feat/359-thin-inference")
using ComposableTuringIDModelsOption 2: Local CheckoutIf you have the repo locally: git checkout feat/359-thin-inference
julia --project=. -e "using Pkg; Pkg.instantiate()" |
…cessors A problem is a model and its data, so fitting the same model to another series is a new problem rather than a second argument. Drops `as_turing_model(problem, data)` in favour of `@set problem.data = y_new`, which is how the rest of a composition is respecified and which leaves `forecast(problem, chain, horizon)` reading the data the problem holds. The pairing is now checked when it is made, by an inner constructor so `@set` is checked too. What it catches is narrow and the comment says so: streams that disagree with each other, never a single series, whose count comes from the data it would be checked against. It cannot reject data `as_turing_model` accepts, `data_fits` being the weaker of the two. Also refuses `data_requirements(problem, n)`, which fell through to the generic method and reported as if no data had been supplied, and reports a wholly blank matrix or set of streams as a simulation the way a blank vector already was. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This comment has been minimized.
This comment has been minimized.
…uard sees There is no data-free problem, because the pairing is what the type is; an `IDModel` is the object for a model on its own. A problem whose observations have not arrived is one over a blank series, which fixes the shape and says how many are expected, and the data is attached with `@set`. Both were already true; neither was written down. The construction check's scope moves out of a code comment and into the docstring. It cannot see a length disagreement on a single series, nor across streams that imply their own strata, and a user who knows the type checks something would otherwise reasonably assume it checks those. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Benchmark comparison vs baseMinimum time per call. Buckets are PR time as a % of base, so lower is faster (🟢 faster, ⚪ within 5%, 🔴 slower). Counts of benchmarks per bucket:
Evaluation — 9 benchmarks (by time change)
AD gradients — 7 benchmarks (by time change)
|
Codecov Report❌ Patch coverage is
Flags with carried forward coverage won't be shown. Click here to find out more.
... and 6 files with indirect coverage changes 🚀 New features to boost your workflow:
|
…s facts `as_turing_model(problem, data)` was removed with the rest of the data-alongside-problem route, but `delays-dayofweek.md` still called it to build the posterior-predictive model. That raises an `ArgumentError` from the `as_turing_model` fallback, so the page could not build. The refit idiom the page already shows does the same job, and the resulting model adds exactly the `y_t` varnames `predict` needs. Trim the comments and docstrings this branch added to the facts a reader cannot get from the code: the inner-constructor scope of the guard, why there is no `data_fits(::IDProblem)`, and why a value with no time axis is refused by name. Split the sentences that joined clauses with a colon or a semicolon. Record the blank-series requirements report in a test, since `n_supplied` counts positions in the series there exactly as it does for a series with gaps in it. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This comment has been minimized.
This comment has been minimized.
Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…tions The field was documented twice and the two disagreed. "or `nothing` if none was" reads as `nothing` when the series holds no observations, which is not what it means and not what it does: a wholly blank series reports its length, exactly as a series with gaps in it does. `nothing` means the requirements were asked for with no data argument at all, which is the distinction `_stream_fits` already turns on. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
seabbs
left a comment
There was a problem hiding this comment.
IDProblem should take IDModle and data not i.e the components of an IDmdoel. you new docwstrings are too long adn LLM cut down
The rebuild-coverage test item added in #372 does `using InteractiveUtils: subtypes`, but the stdlib was never added to `test/Project.toml`. Julia 1.12 refuses to load a stdlib that is not in the active environment, so every test matrix job on a branch carrying that item errors in `reconstruction.jl`. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lw3PbYZfA1dZhfaaE9tbdp (cherry picked from commit 4d7322a)
…ings An IDProblem pairs a composed model with its data, so it takes the IDModel rather than the components an IDModel is built from. The three-argument constructor is gone, and the tutorial and tests build the model first. The IDProblem, as_turing_model(problem) and two-argument as_turing_model docstrings are cut to what the code does not already say. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lw3PbYZfA1dZhfaaE9tbdp
…ck after loading The child called apply_method with a NUTSampler, which #373 removes. It now builds Turing's NUTS from a budget carried on the scenario and calls sample directly, so the smoke test does not depend on the inference layer it is not testing. The adaptation count reaches the sampler this way, where NUTSampler dropped it. Mooncake reverse timed out at 900s on its first scenario, with package loading and the backend's first rule compilation both charged to it. The child now reports once its packages are loaded, which restarts the parent's per-scenario clock, and the cap is 1800s. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lw3PbYZfA1dZhfaaE9tbdp
This comment has been minimized.
This comment has been minimized.
…e items Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lw3PbYZfA1dZhfaaE9tbdp
|
CI status on 1fb3ea8. The test matrix and downgrade-compat passed, and the AD jobs are still running.
Generated by Claude Code |
|
📖 Documentation preview is ready! View the docs for this PR at: https://EpiAware.github.io/ComposableTuringIDModels.jl/previews/PR373/ This preview will be updated automatically when you push new commits. |
Closes #359.
Takes Option B from the issue plus the
generated_observablessub-decision, then follows the maintainer's redirect in the comments.IDProblemstays, but for holding a model and its data together rather than fortspan.src/inference/goes from 581 lines across nine files to 393 across two, and five direct dependencies go with it.What was removed
Everything in the method layer was a wrapper over one Turing call and was used by nothing but its own tests.
types.jl,NUTSampler.jl,DirectSample.jl,apply_method.jl,IDObservables.jl,get_param_array.jl,post-inference.jl, andcondition_modelfromsrc/utils/turing-methods.jl.Two of them did not work on what
samplereturns.samplereturns aFlexiChains.VNChain, whileget_param_arrayandspread_drawsare both typed::MCMCChains.Chainsand raiseMethodErroron it.Their own tests passed only because they wrapped the chain in
MCMCChains.Chains(...)first.Dropped dependencies, verified by resolving rather than by grep.
ADTypes,AbstractMCMC,AdvancedHMC,MCMCChains,DataFramesMeta, plus their[compat]entries.MCMCChainsandDataFramesalso leavetest/Project.toml.TablesandStatisticsstay, needed byReportTriangle,HilbertSpaceGPandforecast.What was added
as_turing_model(::IDModel, y)now covers a vector and aNamedTupleof streams as well as a matrix, so the shape comes from the data instead of being restated aslength(y).There is one shape path rather than two.
_obs_data_shapemoved out ofIDProblem.jlintocompose.jl, the old_shapethat duplicated its matrix case is gone, andforecastcalls the same helper it always did.A blank series reaches the same fallback a scalar
missingreaches, soas_turing_model(model, Vector{Missing}(missing, n))builds aSplit's streams from itsmapornamesthe waymissingdoes.A scalar
missingstill needs an explicitn, and so does anything else with no time axis.Both now raise an
ArgumentErrornaming the type rather than aMethodErrorfrom whichever private helper reaches it first.IDProblemas_turing_model(problem)delegates toas_turing_model(problem.model, problem.data).It is no longer a
@modelwrapper, so the built model is the one theIDModelroute builds rather than a name-preserving copy of it.data_requirements(problem)takes no arguments andforecast(problem, chain, horizon)drops theyargument, because the object holds both halves.There is no method taking data alongside the problem.
An
IDProblemis a model and its data, so fitting the same model to a different series is a different problem rather than a different call on this one.That is
Accessors, the way everything else in a composition is respecified.@setround-trips cleanly on the new struct, including nested intoproblem.model, and is shown indelays-dayofweek.md.The check that could not fail
There is deliberately no
data_fits(::IDProblem).I wrote one, and the test written to prove it catches a misfit passed when it should have failed.
The observation count and the data being checked against it come from the same value, so for a single series the answer is
trueby construction.A check that cannot fail is worse than no check, because a reader takes
trueas evidence that something was verified.Asking whether a dataset fits a model stays
data_fits(model, y_t, n), where the two arguments are independent.What construction guards
A constructor that throws on the cases it can detect says nothing when it passes, so it cannot mislead the way a
data_fitsreturningtruewould.Construction is checked, in an inner constructor so
@setis checked too.Two streams over one infection stratum, so the count is read off
casesanddeathscan contradict it.The guard fires only when streams disagree with each other, never on a single series.
That scope is stated in the docstring as well as the code, because the obvious ragged case passes and a user who knows the type checks something would assume it checks the case they have.
It cannot reject data
as_turing_modelaccepts, becausedata_fitsis the weaker of the two conditions.Checked over twelve shapes (plain, delayed, short, legacy-length,
Aggregate,ReportTriangle,BinomialError,SplitofBinomialError, ragged both ways, blank vector, blank matrix) with no case where the guard rejects something that builds.There is no data-free
IDProblemThe pairing is what the type is, so
IDModelis the object for a model on its own.A problem whose observations have not arrived is one over a blank series, which fixes the shape and says how many observations are expected.
A scalar
missingstill errors, because it carries no length.Attaching data this way gives what the constructor gives, field for field, with identical
VarInfokeys.IDProblemhas no==method, so struct-levelisequalfalls back to===and compares field identity.isequal(@set p.data = y1, IDProblem(model, y2))isfalsefor equal-but-distincty1andy2.Compare field by field.
tspanis goneEvery call site in the repo wrote
tspan = (1, length(y)), restating what the data already says, and if the two disagreed there was no good answer for which won.data_requirements(::IDProblem)now passes the fullModelShapefrom_data_shape, so a stratified problem reports per-stratum supply where reading the length offtspangave a bareIntand a stratum count of 1.The simulation case
tspancovered is served by a blank series, which carries its length the same way observations do.One reason, three times
Three decisions in this PR look separate and are the same one.
tspanwent because it restated a length the data already carries.data_fits(::IDProblem)went because its answer was read off the same value it was checking, so it could not fail.A per-stream
nis deliberately not stored, for the first reason again.The rule underneath is that the data is the single record, and every question about a length is answered by asking it.
Checking that rule turned up two bugs, filed as #374 and #383, and neither is an argument against it: both are the report failing to read a number the data states plainly.
A stored copy would have hidden them and then disagreed with the data, which is the
tspanfailure mode restated.The display
This is the point of keeping
IDProblem.show(stdout, MIME"text/plain"(), as_turing_model(model, y, 30))for aDirectInfections+LatentDelay(NegativeBinomialError())model over 30 observations prints on one line as its full nested parametric type, with all 30 observations dumped inline.The one number a reader might try to use,
n = 34, is the lead-in-inflated internal series length rather than the 30 observations supplied.The same model and data as an
IDProblem:Built on the package's own printer.
_component_childrensupplies the model's children, which hang directly off the problem so the pairing reads as one tree, and_print_component_treegained one optionaltrailingargument for sibling lines that are not components.That is the only change to shared printing code.
The data line reports what is there.
The
NamedTupleline names the entries without saying whether they are streams or fields, which is deliberate.They are streams for a
Split, but aBinomialErrortakes(y = successes, N = trials), one stream with two named fields.data_requirementsis what distinguishes them, and the line points there.The display does not flag a data/model mismatch, for the
data_fitsreason above.It would mean something for ragged
NamedTuplestreams, but a check that is live in one shape and vacuous in another is not one to put in ashow.One bug found, not fixed here
_obs_data_shapemakes the streams-versus-fields mistake the display avoids.It reads a
NamedTuple's entry count as the observation stream count, so aBinomialError's(y, N)resolves to two infection strata wheredata_requirementscorrectly reports one stream.A
ReportTriangleis the same fault and worse, because its matrix rows are reference days.The general fault is that
_obs_data_shapereads any leading array dimension orNamedTupleentry count as a stream count.This is not a regression.
The helper is byte-for-byte what it was and only moved file, but it was reachable through
IDProblemalone before and now also backsas_turing_model(model, y), so the exposure is wider.Fixing it needs a discriminator between a stream axis and a field axis, and the nested case (a
SplitofBinomialErrorstreams) has to be worked through, which is more than belongs in an already-large breaking change.Filed as #374, which #363 already fixes by introducing
observation_streamsas the seam saying which of a data value's axes are streams.#374 should be closed as superseded once #363 lands.
The three-argument form is unaffected, since the caller states the shape.
Migration
apply_method(problem, NUTSampler(; ndraws = 1000, nchains = 4, adtype = ad), (; y_t = y))sample(as_turing_model(IDProblem(model, y)), NUTS(0.8; adtype = ad), MCMCThreads(), 250, 4)apply_method(m, DirectSample(; n_samples = n))sample(m, Prior(), n)apply_method(m, DirectSample())rand(m)res.samplessamplereturnsgenerated_observables(m, d, chain).generatedreturned(m, chain)spread_draws(chain)DataFrame(MCMCChains.Chains(chain)), then add adrawcolumnget_param_array(chain)reshape(rowtable(MCMCChains.Chains(chain)), size(chain, 1), size(chain, 3))condition_model(m, f, c)condition(fix(m, f), c)IDProblem(; infection, observation_model, tspan = (1, n))IDProblem(infection, observation_model, y)as_turing_model(problem, (; y_t = y))as_turing_model(problem)@set problem.data = y_newdata_requirements(problem, (; y_t = y))data_requirements(IDProblem(model, y))data_requirements(problem)readingnofftspandata_requirements(problem)reading it off the datadata_requirements(problem, n)data_requirements(problem.model, y_t, n)forecast(problem, y, chain, h)forecast(problem, chain, h)as_turing_model(model, y, length(y))as_turing_model(model, y)Two need a caveat rather than a substitution.
NUTSampler.ndrawswas the total across chains and_apply_nutsdivided it bynchainsbefore sampling, sondraws = 1000, nchains = 4drew 250 each.The third positional argument of
sampleis per chain, so a ported script has to divide.apply_methodreturned anIDObservablesstruct.res.samplesis the chain andres.generatedis areturnedcall.The struct's other two fields were never read anywhere in the repo.
Docs
Kept deliberately small.
design.mdis being edited by three other open branches, so it gets the one sentence abouttspanand nothing else.delays-dayofweek.mdis the page nothing else touches, so that is whereIDProblemis shown properly.The new constructor, the printed problem,
data_requirements(problem)read straight off it, and the@setrefit.Accessorsjoinsdocs/Project.tomlfor that block.The posterior-predictive model on the same page is built the same way,
@set problem.data = Vector{Missing}(missing, n), since there is no longer a method taking data alongside the problem.That model adds exactly the
ny_tvarnamespredictneeds and drops none of the parameters, checked against the fitted problem'sVarInfokeys.Six tutorials swap
vec(generated_observables(m, d, chain).generated)forvec(returned(m, chain)), one line each.renewal-negbin.mdis also edited bydocs/overview-cleanup, so expect a small conflict there.A second tutorial was not converted to
IDProblem.With
docs/overview-cleanupanddocs/aog-plottingboth in flight over the tutorials, more churn there costs more in rebases than it buys.Worth a follow-up once those land.
Testing
Ran the affected files with the discovery scope copied from
test/runtests.jl, filtered by basename:inference.jl,compose_strata.jl,compose.jl,requirements.jl,interfaces.jl,utils_extra.jl,prettyprinting.jl,traversal.jl.Runic exits 0.
Four test items go (
apply_method,spread_draws, bothgenerated_observablesitems) plus the two inutils_extra.jl.Three are added:
IDProblemprinting,IDProblemrequirements, and two-argumentas_turing_modelacross every data form.The
IDProblemitems also assert that the problem route and the model route build models with identicalVarInfokeys, so swapping one for the other still gives the same chain contents.forecastis otherwise untouched, so the conflict with #348 stays confined to_extend_latent_drawsand_assert_factorised, which this branch does not go near.CI
Every red
testandadjob isUndefVarError: SS_Int not defined in AMD, an AMD.jl 0.5.4 breakage that failsLinearSolveprecompilation and takesModelingToolkitandOrdinaryDiffEqdown with it.It hits every platform and every Julia version, and the same jobs are red on
docs/overview-cleanupfrom the same hour.codecov/projectis red for the same reason, since theadjobs never uploaded their coverage.The Documenter job was cancelled by the shared deploy concurrency group (#353) rather than failing.
Review
@seabbs-review-botraised five findings across two passes.Four were real and are fixed; each is verified against the source in its thread.
The fifth, on
data_requirementscounting a blank series as supplied, is answered in the thread and left as it is, becausen_suppliedcounts positions in the series exactly as it does for a series with gaps in it.This was opened by a bot. Please ping @seabbs for any questions.