Skip to content

Conversation

@penelopeysm
Copy link
Member

@penelopeysm penelopeysm commented Jul 10, 2025

Part 1: Adding hasvalue and getvalue to AbstractPPL
Part 2: Removing hasvalue and getvalue from DynamicPPL
Part 3: Introducing InitContext and init!!

This is part 4/N of #967.


In Part 3 we introduced InitContext. This PR makes use of the functionality in there to replace a bunch of code that no longer needs to exist:

  1. setval_and_resample! followed by model evaluation: This process was used for predict and returned, to manually store certain values in the VarInfo, which would be used in the subsequent model evaluation. We can now do this in a single step using InitFromParams.
  2. initialize_values!!: very similar to the above. It would manually set values inside the varinfo, and then it would trigger an extra model evaluation to update the logp field. Again, this is directly replaced with InitFromParams.
  3. evaluate_and_sample!!: direct one-to-one replacement with init!!.

There is one fairly major API change associated with point (2): the initial_params kwarg to Turing's sample must now be an AbstractInitStrategy.

It's still optional (it will default to init_strategy(spl), which is usually InitFromPrior, except for the HMC family which uses InitFromUniform). However, there are two implications:

  • initial_params cannot be a vector of parameters anymore. It must be InitFromParams(::NamedTuple) OR InitFromParams(::AbstractDict{VarName}).
  • Because InitFromParams expects values in unlinked space, initial_params must always be specified in unlinked space. Previously, initial_params would have to be specified in a way that matched the linking status of the underlying varinfo.

I consider both of these to be a major win for clarity. (One might argue that vectors are more convenient. But IMO anything that lets you extract a vector will also let you extract a NT or Dict, maybe with a bit more typing at worst).

Closes

Closes #774
Closes #797
Closes #983
Closes TuringLang/Turing.jl#2476
Closes TuringLang/Turing.jl#1775

@github-actions
Copy link
Contributor

github-actions bot commented Jul 10, 2025

Benchmark Report for Commit 956ed54

Computer Information

Julia Version 1.11.7
Commit f2b3dbda30a (2025-09-08 12:10 UTC)
Build Info:
  Official https://julialang.org/ release
Platform Info:
  OS: Linux (x86_64-linux-gnu)
  CPU: 4 × AMD EPYC 7763 64-Core Processor
  WORD_SIZE: 64
  LLVM: libLLVM-16.0.6 (ORCJIT, znver3)
Threads: 1 default, 0 interactive, 1 GC (on 4 virtual cores)

Benchmark Results

|                 Model | Dimension |  AD Backend |      VarInfo Type | Linked | Eval Time / Ref Time | AD Time / Eval Time |
|-----------------------|-----------|-------------|-------------------|--------|----------------------|---------------------|
| Simple assume observe |         1 | forwarddiff |             typed |  false |                  8.3 |                 1.6 |
|           Smorgasbord |       201 | forwarddiff |             typed |  false |                654.6 |                45.1 |
|           Smorgasbord |       201 | forwarddiff | simple_namedtuple |   true |                426.3 |                55.7 |
|           Smorgasbord |       201 | forwarddiff |           untyped |   true |               1186.8 |                30.0 |
|           Smorgasbord |       201 | forwarddiff |       simple_dict |   true |               6616.9 |                30.1 |
|           Smorgasbord |       201 | reversediff |             typed |   true |               1303.9 |                32.2 |
|           Smorgasbord |       201 |    mooncake |             typed |   true |               1006.7 |                 4.8 |
|    Loop univariate 1k |      1000 |    mooncake |             typed |   true |               5775.9 |                 4.4 |
|       Multivariate 1k |      1000 |    mooncake |             typed |   true |               1033.5 |                 8.7 |
|   Loop univariate 10k |     10000 |    mooncake |             typed |   true |              65221.0 |                 4.0 |
|      Multivariate 10k |     10000 |    mooncake |             typed |   true |               8885.5 |                 9.7 |
|               Dynamic |        10 |    mooncake |             typed |   true |                144.7 |                10.7 |
|              Submodel |         1 |    mooncake |             typed |   true |                 13.6 |                 4.9 |
|                   LDA |        12 | reversediff |             typed |   true |               1172.4 |                 3.1 |

@penelopeysm penelopeysm changed the title Use init!! to replace evaluate_and_sample!!, predict, returned, and initialize_values InitContext, part 4 - Use init!! to replace evaluate_and_sample!!, predict, returned, and initialize_values Jul 10, 2025
@penelopeysm penelopeysm force-pushed the py/init-prior-uniform branch 2 times, most recently from 025aa8b to b55c1e1 Compare July 10, 2025 14:24
@penelopeysm penelopeysm force-pushed the py/actually-use-init branch 5 times, most recently from b72c3bf to 92d3542 Compare July 10, 2025 15:57
@penelopeysm penelopeysm mentioned this pull request Jul 10, 2025
22 tasks
@penelopeysm penelopeysm force-pushed the py/actually-use-init branch 4 times, most recently from 7438b23 to d55d378 Compare July 10, 2025 16:56
@penelopeysm penelopeysm force-pushed the py/actually-use-init branch 3 times, most recently from 12d93e5 to 7a8e7e3 Compare July 10, 2025 17:47
@penelopeysm penelopeysm force-pushed the py/actually-use-init branch 2 times, most recently from 1d8bceb to 2edcd10 Compare July 20, 2025 00:59
@github-actions
Copy link
Contributor

DynamicPPL.jl documentation for PR #984 is available at:
https://TuringLang.github.io/DynamicPPL.jl/previews/PR984/

@codecov
Copy link

codecov bot commented Jul 20, 2025

Codecov Report

❌ Patch coverage is 86.95652% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.20%. Comparing base (1e1cd94) to head (956ed54).

Files with missing lines Patch % Lines
src/simple_varinfo.jl 40.00% 6 Missing ⚠️
src/test_utils/contexts.jl 83.33% 5 Missing ⚠️
src/test_utils/model_interface.jl 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##           breaking     #984      +/-   ##
============================================
- Coverage     82.87%   81.20%   -1.68%     
============================================
  Files            39       39              
  Lines          3971     3910      -61     
============================================
- Hits           3291     3175     -116     
- Misses          680      735      +55     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@penelopeysm penelopeysm force-pushed the py/actually-use-init branch from 726d486 to bc04355 Compare August 13, 2025 17:16
Comment on lines 20 to 22
function DynamicPPL.Experimental._determine_varinfo_jet(
model::DynamicPPL.Model; only_ddpl::Bool=true
)
Copy link
Member Author

@penelopeysm penelopeysm Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit confused by the comments in this function because as far as I can tell it only ever tested sampling, not both sampling and evaluation. (That was also true going further back e.g. in v0.36)

This PR thus also changes the implementation of this function to test both evaluation and sampling (i.e. initialisation) and if either fails, it will return the untyped varinfo.

Sorry I had to make this change in this PR. There were a few unholy tests where one would end up evaluating a model with a SamplingContext{<:InitContext}, which would error unless I introduced special code to handle it, and I didn't really want to do that. JETExt was one of those unholy scenarios.

Comment on lines -61 to +63
DynamicPPL.evaluate_and_sample!!(rng, model, vi, sampler)
return vi, nothing
strategy = sampler isa SampleFromPrior ? InitFromPrior() : InitFromUniform()
_, new_vi = DynamicPPL.init!!(rng, model, vi, strategy)
return new_vi, nothing
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bit weird, but it's really just to tide us over until we delete SampleFromUniform/SampleFromPrior properly.

src/sampler.jl Outdated
Define the initialisation strategy used for generating initial values when
sampling with `sampler`. Defaults to `InitFromPrior()`, but can be overridden.
"""
init_strategy(::Sampler) = InitFromPrior()
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eventually the aim would be to use ::AbstractSampler. But that will have to wait for cleanup in Turing. DynamicPPL itself doesn't use Sampler at all and if you only look at DPPL it looks like a meaningless empty wrapper, but Turing relies on these methods a fair bit

Comment on lines -158 to -174
@testset "rng" begin
model = GDEMO_DEFAULT

for sampler in (SampleFromPrior(), SampleFromUniform())
for i in 1:10
Random.seed!(100 + i)
vi = VarInfo()
DynamicPPL.evaluate_and_sample!!(Random.default_rng(), model, vi, sampler)
vals = vi[:]

Random.seed!(100 + i)
vi = VarInfo()
DynamicPPL.evaluate_and_sample!!(Random.default_rng(), model, vi, sampler)
@test vi[:] == vals
end
end
end
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is adequately tested in the InitContext tests (test_rng_respected)

Comment on lines -65 to -66
varinfo_untyped = DynamicPPL.VarInfo()
model_with_spl = contextualize(model, SamplingContext(context))
Copy link
Member Author

@penelopeysm penelopeysm Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also had to rework these tests because of the SamplingContext{<:InitContext} case.

@test merge(vi_double, vi_single)[vn] == 1.0
end

@testset "sampling from linked varinfo" begin
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these tests are also covered in InitContext now (test_link_status_respected)!

@penelopeysm penelopeysm requested a review from mhauru August 13, 2025 23:54
Copy link
Member

@mhauru mhauru left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty excited for this! Had some various nits and questions though.

Co-authored-by: Markus Hauru <markus@mhauru.org>
@penelopeysm penelopeysm merged commit 729bfba into breaking Sep 18, 2025
3 of 19 checks passed
@penelopeysm penelopeysm deleted the py/actually-use-init branch September 18, 2025 09:29
penelopeysm added a commit that referenced this pull request Oct 21, 2025
* Bump minor version

* bump benchmarks compat

* add a skeletal changelog

* `InitContext`, part 3 - Introduce `InitContext` (#981)

* Implement InitContext

* Fix loading order of modules; move `prefix(::Model)` to model.jl

* Add tests for InitContext behaviour

* inline `rand(::Distributions.Uniform)`

Note that, apart from being simpler code, Distributions.Uniform also
doesn't allow the lower and upper bounds to be exactly equal (but we
might like to keep that option open in DynamicPPL, e.g. if the user
wants to initialise all values to the same value in linked space).

* Document

* Add a test to check that `init!!` doesn't change linking

* Fix `push!` for VarNamedVector

This should have been changed in #940, but slipped through as the file
wasn't listed as one of the changed files.

* Add some line breaks

Co-authored-by: Markus Hauru <markus@mhauru.org>

* Add the option of no fallback for ParamsInit

* Improve docstrings

* typo

* `p.default` -> `p.fallback`

* Rename `{Prior,Uniform,Params}Init` -> `InitFrom{Prior,Uniform,Params}`

---------

Co-authored-by: Markus Hauru <markus@mhauru.org>

* use `varname_leaves` from AbstractPPL instead (#1030)

* use `varname_leaves` from AbstractPPL instead

* add changelog entry

* fix import

* tidy occurrences of varname_leaves as well (#1031)

* `InitContext`, part 4 - Use `init!!` to replace `evaluate_and_sample!!`, `predict`, `returned`, and `initialize_values` (#984)

* Replace `evaluate_and_sample!!` -> `init!!`

* Use `ParamsInit` for `predict`; remove `setval_and_resample!` and friends

* Use `init!!` for initialisation

* Paper over the `Sampling->Init` context stack (pending removal of SamplingContext)

* Remove SamplingContext from JETExt to avoid triggering `Sampling->Init` pathway

* Remove `predict` on vector of VarInfo

* Fix some tests

* Remove duplicated test

* Simplify context testing

* Rename FooInit -> InitFromFoo

* Fix JETExt

* Fix JETExt properly

* Fix tests

* Improve comments

* Remove duplicated tests

* Docstring improvements

Co-authored-by: Markus Hauru <markus@mhauru.org>

* Concretise `chain_sample_to_varname_dict` using chain value type

* Clarify testset name

* Re-add comment that shouldn't have vanished

* Fix stale Requires dep

* Fix default_varinfo/initialisation for odd models

* Add comment to src/sampler.jl

Co-authored-by: Markus Hauru <markus@mhauru.org>

---------

Co-authored-by: Markus Hauru <markus@mhauru.org>

* `InitContext`, part 5 - Remove `SamplingContext`, `SampleFrom{Prior,Uniform}`, `{tilde_,}assume` (#985)

* Remove `SamplingContext` for good

* Remove `tilde_assume` as well

* Split up tilde_observe!! for Distribution / Submodel

* Tidy up tilde-pipeline methods and docstrings

* Fix tests

* fix ambiguity

* Add changelog

* Update HISTORY.md

Co-authored-by: Markus Hauru <markus@mhauru.org>

---------

Co-authored-by: Markus Hauru <markus@mhauru.org>

* fix missing import

* Shuffle context code around and remove dead code (#1050)

* Delete the `"del"` flag (#1058)

* Delete del

* Fix a typo

* Add HISTORY entry about del

* Fixes for Turing 0.41 (#1057)

* setleafcontext(model, ctx) and various other fixes

* fix a bug

* Add warning for `initial_parameters=...`

* Remove `resume_from` and `default_chain_type` (#1061)

* Remove resume_from

* Format

* Fix test

* remove initial_params warning

* Allow more flexible `initial_params` (#1064)

* Enable NamedTuple/Dict initialisation

* Add more tests

* fix include_all kwarg for predict, improve perf (#1068)

* Fix `include_all` for predict

* Fix include_all for predict, some perf improvements

* Replace `Metadata.flags` with `Metadata.trans` (#1060)

* Replace Medata.flags with Metadata.trans

* Fix a bug

* Fix a typo

* Fix two bugs

* Rename trans to is_transformed

* Rename islinked to is_transformed, remove duplication

* Change pointwise_logdensities default key type to VarName (#1071)

* Change pointwise_logdensities default key type to VarName

* Fix a doctest

* Fix DynamicPPL / MCMCChains methods (#1076)

* Reimplement pointwise_logdensities (almost completely)

* Move logjoint, logprior, ... as well

* Fix imports, etc

* Remove tests that are failing (yes I learnt this from Claude)

* Changelog

* logpdf

* fix docstrings

* allow dict output

* changelog

* fix some comments

* fix tests

* Fix more imports

* Remove stray n

Co-authored-by: Markus Hauru <markus@mhauru.org>

* Expand `logprior`, `loglikelihood`, and `logjoint` docstrings

---------

Co-authored-by: Markus Hauru <markus@mhauru.org>

* Remove `Sampler` and its interface (#1037)

* Remove `Sampler` and `initialstep`

* Actually just remove the entire file

* forgot one function

* Move sampling test utils to Turing as well

* Update changelog to correctly reflect changes

* [skip ci] Make changelog headings more consistent

---------

Co-authored-by: Markus Hauru <markus@mhauru.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants