Skip to content

varnamedtuple: store tuple nodes as tuples - #1549

Merged
yebai merged 2 commits into
mainfrom
vnt-tuple-nodes
Nov 26, 2026
Merged

yebai merged 2 commits into
mainfrom
vnt-tuple-nodes

Conversation

@yebai

@yebai yebai commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

#1539 lets VarNamedTuple record 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's setindex!!, which widens the container through an immutable write rather than converting the value.

@model function f()
    x = (0, 0)
    x[2] ~ Normal()  # immutable write widens `x` to `(0, draw)`
    x[1] ~ Normal()
end

On main, evaluating f() directly works, but VarInfo and LogDensityFunction throw, as they do for a tuple argument with missing entries such as (missing, 1.0). ForwardDiff has the same effect: with x = (0.0, 0.0); x[1] ~ Normal(); x[2] ~ Normal(x[1]), x becomes (Dual, 0.0), and a gradient through evaluate!! with a VarInfo throws. This PR fixes all three.

This PR stores a tuple node as a PartialTuple, a tuple of slots that each hold an element or nothing. 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: 1 and 2.5 stored in x[1] and x[2] of x = (0, 0) read back as (1, 2.5), where main gives [1.0, 2.5].

Changes to unreleased behaviour from #1539:

  • Elements of a tuple node take a single integer index; ranges and colons throw an ArgumentError. Whole tuple values still accept them.
  • Merging a tuple node with an array node, made by an indexed value without a template, throws an ArgumentError; ==, isequal and hash tell the two apart.
  • densify!! keeps tuple nodes, so ParamsWithStats reports x[1] and x[2] rather than x.
  • AbstractPPL.of throws for a tuple node.

Once this merges, #1548 no longer needs its tuple promotion.

@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.34483% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.91%. Comparing base (d3aeca3) to head (8a7b083).

Files with missing lines Patch % Lines
src/varnamedtuple/show.jl 68.18% 7 Missing ⚠️
src/varnamedtuple/partial_tuple.jl 86.66% 6 Missing ⚠️
src/varnamedtuple/getset.jl 97.61% 1 Missing ⚠️
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.
📢 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.

@github-actions

Copy link
Copy Markdown
Contributor

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

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Benchmarks

Performance 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: main d3aeca3, PR 8a7b083

================================================================================================================================
                                                                     primal                            gradient                 
                                                             ----------------------  -------------------------------------------
Model                                         dim    linked        main          PR     FwdDiff    RvsDiff    Mooncake    Enzyme
--------------------------------------------------------------------------------------------------------------------------------
Simple assume observe*                          1     false     5.25 ns     5.25 ns        9.83    1376.76       10.18      6.49
Simple assume observe*                          1      true     5.27 ns     5.26 ns        9.60    1310.39       11.18      6.48
Smorgasbord                                   201     false     5.33 μs     5.37 μs       79.29     140.42        5.42      1.29
Smorgasbord                                   201      true     6.47 μs     6.44 μs       76.23     162.64        5.49      1.46
Smorgasbord fixed                             100     false      2.6 μs     2.58 μs       52.36     168.94        6.45      1.24
Smorgasbord fixed                             100      true     3.03 μs     3.05 μs       62.29     185.84        6.52      1.46
NamedTuple-field LHS variable*                  1     false     5.26 ns     5.25 ns        9.72    1441.43       10.24      6.54
NamedTuple-field LHS variable*                  1      true     5.26 ns     5.26 ns        9.77    1455.88       10.24      6.19
MvNormal argument-supplied observation*         1     false     74.8 ns     70.1 ns        2.32     692.21        3.49      2.29
MvNormal argument-supplied observation*         1      true     72.1 ns     68.9 ns        2.32     735.19        3.48      2.37
Loop univariate 1k                           1000     false     16.9 μs     16.9 μs      864.16     323.31        3.00      0.82
Loop univariate 1k                           1000      true     18.2 μs     18.2 μs     1307.01     301.20        2.82      0.69
Multivariate 1k                              1000     false    940.0 ns     1.02 μs     1442.83     628.63        1.73      2.96
Multivariate 1k                              1000      true    950.0 ns    962.0 ns     1537.27     739.63        1.90      3.27
Loop univariate 10k                         10000     false    163.0 μs    164.0 μs    12676.44     382.78        2.97      0.71
Loop univariate 10k                         10000      true    176.0 μs    177.0 μs    13350.04     357.80        2.83      0.65
Multivariate 10k                            10000     false     9.93 μs     9.63 μs    26081.92     705.89        1.65      2.88
Multivariate 10k                            10000      true     9.36 μs      9.5 μs    26110.57     742.82        1.66      2.81
Dynamic                                       err     false     1.41 μs     1.39 μs         err      42.15       15.06      4.47
Dynamic                                        10      true     1.95 μs     1.84 μs        1.51      55.93       12.44      6.25
Submodel*                                       1     false     5.26 ns     5.26 ns        9.80    1509.35       10.09      6.07
Submodel*                                       1      true     5.27 ns     5.26 ns        9.85    1587.48       10.07      6.07
LDA                                             6      true     3.96 μs      3.7 μs        1.44      11.36       28.28     28.46
================================================================================================================================
Environment
Julia 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)

@sunxd3

sunxd3 commented Nov 25, 2026

Copy link
Copy Markdown
Member

The direction looks very right.

A tricky thing is that x[1] can index into an array as well as a tuple, but a tuple's elements can have different types. Right now (inherited from main), something like fix(model, @varname(x[1]) => 4.0) falls back to an array for the x[1] mapping. On main that was fine, because tuple draws were promoted to arrays too (hence the same-type limitation). With this PR the model's own draw is a tuple node, so the two no longer meet:

@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.

condition behaves the same.

A possible fix: an untemplated node is always backed by a GrowableArray, so the cross-kind _merge could move a 1-D GrowableArray node's entries into the tuple's slots, since the tuple knows the real length and element types.

Another incoherency worth patching is that PartialTuple doesn't get some of the special treatment PartialArray does. I think PartialTuple should be handled in these places too; some MWEs:

Details

hasvalue/getvalue for LKJCholesky only rebuild the matrix from per-element entries when the node stored under x is a VarNamedTuple or PartialArray; any other node is taken to be the matrix itself, so a PartialTuple is passed straight to logpdf:

@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)

merge shares mutable children with its inputs (PartialArray's merge starts from copy(pa2)):

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

densify!! maps over every entry of pa.data, including unset ones, and this PR adds PartialTuple to that branch (map.jl#L504), so ParamsWithStats fails on a sparse array of tuples:

@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: UndefRefError

There 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 Union{Nothing,Some{T}} slot field. Still, this is a same-type tuple, which used to work (although, again, under a design that basically treated tuples as arrays). So I am fine if we decide the more faithful tuple is the right approach.

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>
@yebai

yebai commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

Thanks, all five reproduce. Where they stand at 9a7d426:

  1. fix(fix(f(), p), @varname(x[1]) => 4.0): I'd keep the throw. The next PR in the split stores bindings on the model, and there this returns (4.0, …) as on main. Nothing is released in between, so a tuple × array merge here would only be replaced. (There, fix(f(), @varname(x[1]) => 4.0) needs an of template when the model holds no value for x.)

  2. LKJCholesky: now an ArgumentError naming x. A tuple can't supply a Cholesky factor, and falling back to the prior would hide that.

  3. merge sharing children: I'll leave this one. merge doesn't promise a result independent of its inputs; on main, merge(VarNamedTuple(), r) already shares r's nested arrays, so copy before mutating in place.

  4. densify!!: now skips unset entries. main throws the same UndefRefError for an array of VarNamedTuples with unset entries, so that's fixed too.

  5. Enzyme: Enzyme expects a union's value to occupy one field of the compiled struct, but Julia splits some values, ours included, across several, so Enzyme's type reconstruction fails and throws. A Const struct with a Union{Nothing,Tuple{Int32,Int32}} field reproduces it without DynamicPPL. Slots now hold a flag and the value instead, and your example matches main.

    More generally, Enzyme must infer types that LLVM IR does not record. Exact inference is undecidable in general: the type a load returns depends on which stores reach it, a may-alias question Landi (1992) showed undecidable. So Enzyme approximates, and throws when the approximation fails. Whether it fails depends on the function body and the Julia version: differentiating f(x, n) = x[1] * Float64(n) with respect to x, with n::Int128 passed as Const and no union involved, fails on 1.10 but not on 1.12 with the same Enzyme release (Enzyme 0.13.221, Enzyme_jll 0.0.310). Differentiating LLVM code therefore does not mean every Julia program can be differentiated. Our change fixes this case, but no representation can guarantee that Enzyme accepts future code.

Comment thread src/varnamedtuple/getset.jl Resolved
@yebai
yebai added this pull request to the merge queue Nov 26, 2026
@yebai
yebai removed this pull request from the merge queue due to a manual request Nov 26, 2026
`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>
@yebai
yebai enabled auto-merge November 26, 2026 16:49
@yebai
yebai added this pull request to the merge queue Nov 26, 2026
Merged via the queue into main with commit b51b918 Nov 26, 2026
24 checks passed
@yebai
yebai deleted the vnt-tuple-nodes branch November 26, 2026 17:10
yebai added a commit that referenced this pull request Nov 27, 2026
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.
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