Repository navigation
varnamedtuple: store tuple nodes as tuples - #1549
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #1549 +/- ##
==========================================
+ Coverage 85.34% 86.91% +1.57%
==========================================
Files 52 53 +1
Lines 4714 4792 +78
==========================================
+ Hits 4023 4165 +142
+ Misses 691 627 -64 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
DynamicPPL.jl documentation for PR #1549 is available at: |
BenchmarksPerformance Ratio: gradient time divided by log-density time. For very small models these ratios are noisy across runs and machines; raw primal and gradient timings are more reliable. The benchmarks are aimed at DynamicPPL developers and mainly catch obvious allocation or type-stability regressions. See benchmark notes for details. Primal times: EnvironmentJulia Version 1.13.4 Commit c1ac32ab733 (2026-11-13 17:30 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-20.1.8 (ORCJIT, znver3) GC: Built with stock GC Threads: 1 default, 1 interactive, 1 GC (on 4 virtual cores) |
d3fcd6b to
f6abbd5
Compare
|
The direction looks very right. A tricky thing is that @model function f(); x = (0.0, 0.0); x[1] ~ Normal(); x[2] ~ Normal(x[1]); return x; end
p = rand(Xoshiro(1), f())
fix(fix(f(), p), @varname(x[1]) => 4.0)()
# main: (4.0, 0.46089361482929836)
# PR: ArgumentError: Cannot merge tuple and array nodes; give the tuple's template.
A possible fix: an untemplated node is always backed by a Another incoherency worth patching is that Details
@model function tup(); x = (0.0, 0.0); x[1] ~ Normal(); x[2] ~ Normal(); end
@model function lkj(); x ~ LKJCholesky(2, 1.0); return x; end
init!!(Xoshiro(1), lkj(), VarInfo(), InitFromParams(rand(Xoshiro(1), tup())), UnlinkAll())
# main: falls back to the prior
# PR: MethodError: no method matching logpdf(::LKJCholesky{Float64}, ::PartialTuple)
tt = ([1, 2], [1, 2])
w(i) = templated_setindex!!(VarNamedTuple(), 11, @varname(x[i][1]), tt)
l = w(1); r = w(2)
m = merge(l, r)
BangBang.setindex!!(m, 22, @varname(x[2][1]))
r[@varname(x[2][1])]
# main: 11 PR: 22
@model function sparse(); x = [([0.0],), ([0.0],)]; x[1][1] ~ MvNormal([0.0], I); return x; end
DynamicPPL.ParamsWithStats(InitFromPrior(), sparse())
# main: keys x[1][1] PR: UndefRefErrorThere is also an Enzyme regression on an all-Float64 tuple: @model function dep(t); x = t; x[1] ~ Normal(); x[2] ~ Normal(x[1]); return x; end
ad = AutoEnzyme(; mode=Enzyme.set_runtime_activity(Enzyme.Reverse))
ldf = LogDensityFunction(dep((0.0, 0.0)), getlogjoint_internal, UnlinkAll(); adtype=ad)
LogDensityProblems.logdensity_and_gradient(ldf, [1.0, 3.0])
# main: (-4.337877066409345, [1.0, -2.0])
# PR: IllegalTypeAnalysisException (1.13 and 1.10)This might be an Enzyme limitation: it doesn't seem to support the |
A tuple node was stored as an array, which would promote or widen elements of different types, so `VarNamedTuple` refused mixed tuples. A tilde that leaves one, as `x = (0, 0); x[2] ~ Normal(); x[1] ~ Normal()` does, threw under `VarInfo` and `LogDensityFunction`, though `model()` ran. Tuple nodes are now `PartialTuple`s: a tuple of slots, each holding a set flag and a value undefined while unset, which keeps Enzyme working, and whose type parameter fixes the element type whether or not the slot is set. Mixed tuples, and element values that are themselves `nothing` or `Some`, round-trip without promotion, and same-type writes with an index known only at run time still infer, as they did with array storage. Marking unset positions with a sentinel type instead makes the tuple's type depend on which positions are set, so a first write with a run-time index does not infer. Elements of a tuple node take one integer index; ranges and colons, which the array storage accepted, throw, though whole tuple values still accept them. Merging a tuple node with an array node for the same variable throws, where the array storage merged them. Reading a whole tuple node returns a tuple rather than a `Vector`, `densify!!` keeps tuple nodes so their elements stay separate keys and skips the unset entries of an array of nodes, which threw an `UndefRefError`, `empty!!` drops them, and `AbstractPPL.of` throws for them, as it has no tuple template. Assisted-by: Claude Code <noreply@anthropic.com>
f6abbd5 to
9a7d426
Compare
|
Thanks, all five reproduce. Where they stand at 9a7d426:
|
`haskey` on a tuple node checked only its own slots, so with
`@template x = ((0.0, 0.0),)` and only `x[1][2]` set, `haskey` returned
`true` for `x` while `getindex` threw and `haskey` for `x[1]` returned
`false`. It now requires every slot's value to be complete.
The slots are checked by recursion over the tuple: a loop over slots of
mixed types allocates (14-33 ns, 2-4 allocations against 1.3 ns), and
`all` over a tuple may infer `Union{Missing,Bool}`.
Assisted-by: Claude Code <noreply@anthropic.com>
Split of #1529 (part 4.3 of 12; part 4 comes as nine PRs). Builds on #1549, which stores `VarNamedTuple` tuple nodes as tuples. Two tilde writes into existing storage go wrong: - `x = fill(0.0); x[] ~ Normal()` throws "reducing over an empty collection is not allowed" under `rand(model)` and `LogDensityFunction(model)`. Recording the value calls BangBang's `setindex!!` with an empty index tuple, and BangBang sums the dimensions of that tuple, which throws. - `x[X=2] ~ Normal()` on a `DimArray` replaces `x` with its parent array, and thread-safe evaluation throws. `Accessors.set` returns whatever the keyword `setindex!` returns, and DimensionalData's returns the parent `Array`. Tilde writes, including thread-safe ones, now go through DynamicPPL's own setter instead of `Accessors.set`. It writes keyword indices in place and returns the array, and gives zero-dimensional writes an explicit `CartesianIndex()`. `VarNamedTuple` array writes now do the same, so `setindex!!(vnt, 1.0, @varname(x[]))` also works, with or without a template. `rand(model)` still throws for keyword indices, which `VarNamedTuple` storage does not accept. The setter writes an array-valued draw into an element of a mutable array in place, so after `x = OffsetArray(Any[0.0, 0.0], 0:1); y = x; x[0] ~ MvNormal(zeros(2), I)`, `y[0]` is the draw. `Accessors.set` did this only for `Array` and its views: an `OffsetArray{Any}` or `DimArray{Any}` lost such aliases, and thread-safe evaluation threw for them. Earlier revisions of this PR promoted same-type tuples so that `x = (0, 0); x[2] ~ Normal(); x[1] ~ Normal()` could record values. Tuple storage in #1549 accepts the mixed tuple `(0, draw)`, so that promotion is gone and tilde writes into tuples behave as on #1549 alone. Inference of `LogDensityFunction` evaluation and of ForwardDiff and Mooncake gradients on `DynamicPPL.TestUtils.DEMO_MODELS` is unchanged; allocations and minimum times are unchanged within run-to-run noise.
#1539 lets
VarNamedTuplerecord variables set by index into a tuple, but stores the tuple as an array, so it refuses tuples with mixed element types ("same-type tuples only"). Tildes produce them routinely: they write through BangBang'ssetindex!!, which widens the container through an immutable write rather than converting the value.On
main, evaluatingf()directly works, butVarInfoandLogDensityFunctionthrow, as they do for a tuple argument withmissingentries such as(missing, 1.0). ForwardDiff has the same effect: withx = (0.0, 0.0); x[1] ~ Normal(); x[2] ~ Normal(x[1]),xbecomes(Dual, 0.0), and a gradient throughevaluate!!with aVarInfothrows. This PR fixes all three.This PR stores a tuple node as a
PartialTuple, a tuple of slots that each hold an element ornothing. A slot's type parameter fixes its element type whether or not it is set, so writes at indices known only at run time still infer. Elements keep their types:1and2.5stored inx[1]andx[2]ofx = (0, 0)read back as(1, 2.5), wheremaingives[1.0, 2.5].Changes to unreleased behaviour from #1539:
ArgumentError. Whole tuple values still accept them.ArgumentError;==,isequalandhashtell the two apart.densify!!keeps tuple nodes, soParamsWithStatsreportsx[1]andx[2]rather thanx.AbstractPPL.ofthrows for a tuple node.Once this merges, #1548 no longer needs its tuple promotion.