-
Notifications
You must be signed in to change notification settings - Fork 29
/
varinfo.jl
2011 lines (1754 loc) · 66.5 KB
/
varinfo.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
####
#### Types for typed and untyped VarInfo
####
####################
# VarInfo metadata #
####################
"""
The `Metadata` struct stores some metadata about the parameters of the model. This helps
query certain information about a variable, such as its distribution, which samplers
sample this variable, its value and whether this value is transformed to real space or
not.
Let `md` be an instance of `Metadata`:
- `md.vns` is the vector of all `VarName` instances.
- `md.idcs` is the dictionary that maps each `VarName` instance to its index in
`md.vns`, `md.ranges` `md.dists`, `md.orders` and `md.flags`.
- `md.vns[md.idcs[vn]] == vn`.
- `md.dists[md.idcs[vn]]` is the distribution of `vn`.
- `md.gids[md.idcs[vn]]` is the set of algorithms used to sample `vn`. This is used in
the Gibbs sampling process.
- `md.orders[md.idcs[vn]]` is the number of `observe` statements before `vn` is sampled.
- `md.ranges[md.idcs[vn]]` is the index range of `vn` in `md.vals`.
- `md.vals[md.ranges[md.idcs[vn]]]` is the vector of values of corresponding to `vn`.
- `md.flags` is a dictionary of true/false flags. `md.flags[flag][md.idcs[vn]]` is the
value of `flag` corresponding to `vn`.
To make `md::Metadata` type stable, all the `md.vns` must have the same symbol
and distribution type. However, one can have a Julia variable, say `x`, that is a
matrix or a hierarchical array sampled in partitions, e.g.
`x[1][:] ~ MvNormal(zeros(2), I); x[2][:] ~ MvNormal(ones(2), I)`, and is managed by
a single `md::Metadata` so long as all the distributions on the RHS of `~` are of the
same type. Type unstable `Metadata` will still work but will have inferior performance.
When sampling, the first iteration uses a type unstable `Metadata` for all the
variables then a specialized `Metadata` is used for each symbol along with a function
barrier to make the rest of the sampling type stable.
"""
struct Metadata{
TIdcs<:Dict{<:VarName,Int},
TDists<:AbstractVector{<:Distribution},
TVN<:AbstractVector{<:VarName},
TVal<:AbstractVector{<:Real},
TGIds<:AbstractVector{Set{Selector}},
}
# Mapping from the `VarName` to its integer index in `vns`, `ranges` and `dists`
idcs::TIdcs # Dict{<:VarName,Int}
# Vector of identifiers for the random variables, where `vns[idcs[vn]] == vn`
vns::TVN # AbstractVector{<:VarName}
# Vector of index ranges in `vals` corresponding to `vns`
# Each `VarName` `vn` has a single index or a set of contiguous indices in `vals`
ranges::Vector{UnitRange{Int}}
# Vector of values of all the univariate, multivariate and matrix variables
# The value(s) of `vn` is/are `vals[ranges[idcs[vn]]]`
vals::TVal # AbstractVector{<:Real}
# Vector of distributions correpsonding to `vns`
dists::TDists # AbstractVector{<:Distribution}
# Vector of sampler ids corresponding to `vns`
# Each random variable can be sampled using multiple samplers, e.g. in Gibbs, hence the `Set`
gids::TGIds # AbstractVector{Set{Selector}}
# Number of `observe` statements before each random variable is sampled
orders::Vector{Int}
# Each `flag` has a `BitVector` `flags[flag]`, where `flags[flag][i]` is the true/false flag value corresonding to `vns[i]`
flags::Dict{String,BitVector}
end
###########
# VarInfo #
###########
"""
```
struct VarInfo{Tmeta, Tlogp} <: AbstractVarInfo
metadata::Tmeta
logp::Base.RefValue{Tlogp}
num_produce::Base.RefValue{Int}
end
```
A light wrapper over one or more instances of `Metadata`. Let `vi` be an instance of
`VarInfo`. If `vi isa VarInfo{<:Metadata}`, then only one `Metadata` instance is used
for all the sybmols. `VarInfo{<:Metadata}` is aliased `UntypedVarInfo`. If
`vi isa VarInfo{<:NamedTuple}`, then `vi.metadata` is a `NamedTuple` that maps each
symbol used on the LHS of `~` in the model to its `Metadata` instance. The latter allows
for the type specialization of `vi` after the first sampling iteration when all the
symbols have been observed. `VarInfo{<:NamedTuple}` is aliased `TypedVarInfo`.
Note: It is the user's responsibility to ensure that each "symbol" is visited at least
once whenever the model is called, regardless of any stochastic branching. Each symbol
refers to a Julia variable and can be a hierarchical array of many random variables, e.g. `x[1] ~ ...` and `x[2] ~ ...` both have the same symbol `x`.
"""
struct VarInfo{Tmeta,Tlogp} <: AbstractVarInfo
metadata::Tmeta
logp::Base.RefValue{Tlogp}
num_produce::Base.RefValue{Int}
end
const UntypedVarInfo = VarInfo{<:Metadata}
const TypedVarInfo = VarInfo{<:NamedTuple}
const VarInfoOrThreadSafeVarInfo{Tmeta} = Union{
VarInfo{Tmeta},ThreadSafeVarInfo{<:VarInfo{Tmeta}}
}
# NOTE: This is kind of weird, but it effectively preserves the "old"
# behavior where we're allowed to call `link!` on the same `VarInfo`
# multiple times.
transformation(vi::VarInfo) = DynamicTransformation()
function VarInfo(old_vi::VarInfo, spl, x::AbstractVector)
md = newmetadata(old_vi.metadata, Val(getspace(spl)), x)
return VarInfo(
md, Base.RefValue{eltype(x)}(getlogp(old_vi)), Ref(get_num_produce(old_vi))
)
end
function VarInfo(
rng::Random.AbstractRNG,
model::Model,
sampler::AbstractSampler=SampleFromPrior(),
context::AbstractContext=DefaultContext(),
)
varinfo = VarInfo()
model(rng, varinfo, sampler, context)
return TypedVarInfo(varinfo)
end
VarInfo(model::Model, args...) = VarInfo(Random.default_rng(), model, args...)
unflatten(vi::VarInfo, x::AbstractVector) = unflatten(vi, SampleFromPrior(), x)
# TODO: deprecate.
unflatten(vi::VarInfo, spl::AbstractSampler, x::AbstractVector) = VarInfo(vi, spl, x)
# without AbstractSampler
function VarInfo(rng::Random.AbstractRNG, model::Model, context::AbstractContext)
return VarInfo(rng, model, SampleFromPrior(), context)
end
# TODO: Remove `space` argument when no longer needed. Ref: https://github.com/TuringLang/DynamicPPL.jl/issues/573
function newmetadata(metadata::Metadata, space, x)
return Metadata(
metadata.idcs,
metadata.vns,
metadata.ranges,
x,
metadata.dists,
metadata.gids,
metadata.orders,
metadata.flags,
)
end
@generated function newmetadata(
metadata::NamedTuple{names}, ::Val{space}, x
) where {names,space}
exprs = []
offset = :(0)
for f in names
mdf = :(metadata.$f)
if inspace(f, space) || length(space) == 0
len = :(sum(length, $mdf.ranges))
push!(
exprs,
:(
$f = Metadata(
$mdf.idcs,
$mdf.vns,
$mdf.ranges,
x[($offset + 1):($offset + $len)],
$mdf.dists,
$mdf.gids,
$mdf.orders,
$mdf.flags,
)
),
)
offset = :($offset + $len)
else
push!(exprs, :($f = $mdf))
end
end
length(exprs) == 0 && return :(NamedTuple())
return :($(exprs...),)
end
####
#### Internal functions
####
"""
Metadata()
Construct an empty type unstable instance of `Metadata`.
"""
function Metadata()
vals = Vector{Real}()
flags = Dict{String,BitVector}()
flags["del"] = BitVector()
flags["trans"] = BitVector()
return Metadata(
Dict{VarName,Int}(),
Vector{VarName}(),
Vector{UnitRange{Int}}(),
vals,
Vector{Distribution}(),
Vector{Set{Selector}}(),
Vector{Int}(),
flags,
)
end
"""
empty!(meta::Metadata)
Empty the fields of `meta`.
This is useful when using a sampling algorithm that assumes an empty `meta`, e.g. `SMC`.
"""
function empty!(meta::Metadata)
empty!(meta.idcs)
empty!(meta.vns)
empty!(meta.ranges)
empty!(meta.vals)
empty!(meta.dists)
empty!(meta.gids)
empty!(meta.orders)
for k in keys(meta.flags)
empty!(meta.flags[k])
end
return meta
end
# Removes the first element of a NamedTuple. The pairs in a NamedTuple are ordered, so this is well-defined.
if VERSION < v"1.1"
_tail(nt::NamedTuple{names}) where {names} = NamedTuple{Base.tail(names)}(nt)
else
_tail(nt::NamedTuple) = Base.tail(nt)
end
function subset(varinfo::UntypedVarInfo, vns::AbstractVector{<:VarName})
metadata = subset(varinfo.metadata, vns)
return VarInfo(metadata, varinfo.logp, varinfo.num_produce)
end
function subset(varinfo::TypedVarInfo, vns::AbstractVector{<:VarName{sym}}) where {sym}
# If all the variables are using the same symbol, then we can just extract that field from the metadata.
metadata = subset(getfield(varinfo.metadata, sym), vns)
return VarInfo(NamedTuple{(sym,)}(tuple(metadata)), varinfo.logp, varinfo.num_produce)
end
function subset(varinfo::TypedVarInfo, vns::AbstractVector{<:VarName})
syms = Tuple(unique(map(getsym, vns)))
metadatas = map(syms) do sym
subset(getfield(varinfo.metadata, sym), filter(==(sym) ∘ getsym, vns))
end
return VarInfo(NamedTuple{syms}(metadatas), varinfo.logp, varinfo.num_produce)
end
function subset(metadata::Metadata, vns_given::AbstractVector{<:VarName})
# TODO: Should we error if `vns` contains a variable that is not in `metadata`?
# For each `vn` in `vns`, get the variables subsumed by `vn`.
vns = mapreduce(vcat, vns_given) do vn
filter(Base.Fix1(subsumes, vn), metadata.vns)
end
indices_for_vns = map(Base.Fix1(getindex, metadata.idcs), vns)
indices = Dict(vn => i for (i, vn) in enumerate(vns))
# Construct new `vals` and `ranges`.
vals_original = metadata.vals
ranges_original = metadata.ranges
# Allocate the new `vals`. and `ranges`.
vals = similar(metadata.vals, sum(length, ranges_original[indices_for_vns]))
ranges = similar(ranges_original)
# The new range `r` for `vns[i]` is offset by `offset` and
# has the same length as the original range `r_original`.
# The new `indices` (from above) ensures ordering according to `vns`.
# NOTE: This means that the order of the variables in `vns` defines the order
# in the resulting `varinfo`! This can have performance implications, e.g.
# if in the model we have something like
#
# for i = 1:N
# x[i] ~ Normal()
# end
#
# and we then we do
#
# subset(varinfo, [@varname(x[i]) for i in shuffle(keys(varinfo))])
#
# the resulting `varinfo` will have `vals` ordered differently from the
# original `varinfo`, which can have performance implications.
offset = 0
for (idx, idx_original) in enumerate(indices_for_vns)
r_original = ranges_original[idx_original]
r = (offset + 1):(offset + length(r_original))
vals[r] = vals_original[r_original]
ranges[idx] = r
offset = r[end]
end
flags = Dict(k => v[indices_for_vns] for (k, v) in metadata.flags)
return Metadata(
indices,
vns,
ranges,
vals,
metadata.dists[indices_for_vns],
metadata.gids,
metadata.orders[indices_for_vns],
flags,
)
end
function Base.merge(varinfo_left::VarInfo, varinfo_right::VarInfo)
return _merge(varinfo_left, varinfo_right)
end
function _merge(varinfo_left::VarInfo, varinfo_right::VarInfo)
metadata = merge_metadata(varinfo_left.metadata, varinfo_right.metadata)
return VarInfo(
metadata, Ref(getlogp(varinfo_right)), Ref(get_num_produce(varinfo_right))
)
end
@generated function merge_metadata(
metadata_left::NamedTuple{names_left}, metadata_right::NamedTuple{names_right}
) where {names_left,names_right}
names = Expr(:tuple)
vals = Expr(:tuple)
# Loop over `names_left` first because we want to preserve the order of the variables.
for sym in names_left
push!(names.args, QuoteNode(sym))
if sym in names_right
push!(vals.args, :(merge_metadata(metadata_left.$sym, metadata_right.$sym)))
else
push!(vals.args, :(metadata_left.$sym))
end
end
# Loop over remaining variables in `names_right`.
names_right_only = filter(∉(names_left), names_right)
for sym in names_right_only
push!(names.args, QuoteNode(sym))
push!(vals.args, :(metadata_right.$sym))
end
return :(NamedTuple{$names}($vals))
end
function merge_metadata(metadata_left::Metadata, metadata_right::Metadata)
# Extract the varnames.
vns_left = metadata_left.vns
vns_right = metadata_right.vns
vns_both = union(vns_left, vns_right)
# Determine `eltype` of `vals`.
T_left = eltype(metadata_left.vals)
T_right = eltype(metadata_right.vals)
T = promote_type(T_left, T_right)
# TODO: Is this necessary?
if !(T <: Real)
T = Real
end
# Determine `eltype` of `dists`.
D_left = eltype(metadata_left.dists)
D_right = eltype(metadata_right.dists)
D = promote_type(D_left, D_right)
# TODO: Is this necessary?
if !(D <: Distribution)
D = Distribution
end
# Initialize required fields for `metadata`.
vns = VarName[]
idcs = Dict{VarName,Int}()
ranges = Vector{UnitRange{Int}}()
vals = T[]
dists = D[]
gids = metadata_right.gids # NOTE: giving precedence to `metadata_right`
orders = Int[]
flags = Dict{String,BitVector}()
# Initialize the `flags`.
for k in union(keys(metadata_left.flags), keys(metadata_right.flags))
flags[k] = BitVector()
end
# Range offset.
offset = 0
for (idx, vn) in enumerate(vns_both)
# `idcs`
idcs[vn] = idx
# `vns`
push!(vns, vn)
if vn in vns_left && vn in vns_right
# `vals`: only valid if they're the length.
vals_left = getval(metadata_left, vn)
vals_right = getval(metadata_right, vn)
@assert length(vals_left) == length(vals_right)
append!(vals, vals_right)
# `ranges`
r = (offset + 1):(offset + length(vals_left))
push!(ranges, r)
offset = r[end]
# `dists`: only valid if they're the same.
dist_right = getdist(metadata_right, vn)
# Give precedence to `metadata_right`.
push!(dists, dist_right)
# `orders`: giving precedence to `metadata_right`
push!(orders, getorder(metadata_right, vn))
# `flags`
for k in keys(flags)
# Using `metadata_right`; should we?
push!(flags[k], is_flagged(metadata_right, vn, k))
end
elseif vn in vns_left
# Just extract the metadata from `metadata_left`.
# `vals`
vals_left = getval(metadata_left, vn)
append!(vals, vals_left)
# `ranges`
r = (offset + 1):(offset + length(vals_left))
push!(ranges, r)
offset = r[end]
# `dists`
dist_left = getdist(metadata_left, vn)
push!(dists, dist_left)
# `orders`
push!(orders, getorder(metadata_left, vn))
# `flags`
for k in keys(flags)
push!(flags[k], is_flagged(metadata_left, vn, k))
end
else
# Just extract the metadata from `metadata_right`.
# `vals`
vals_right = getval(metadata_right, vn)
append!(vals, vals_right)
# `ranges`
r = (offset + 1):(offset + length(vals_right))
push!(ranges, r)
offset = r[end]
# `dists`
dist_right = getdist(metadata_right, vn)
push!(dists, dist_right)
# `orders`
push!(orders, getorder(metadata_right, vn))
# `flags`
for k in keys(flags)
push!(flags[k], is_flagged(metadata_right, vn, k))
end
end
end
return Metadata(idcs, vns, ranges, vals, dists, gids, orders, flags)
end
const VarView = Union{Int,UnitRange,Vector{Int}}
"""
getval(vi::UntypedVarInfo, vview::Union{Int, UnitRange, Vector{Int}})
Return a view `vi.vals[vview]`.
"""
getval(vi::UntypedVarInfo, vview::VarView) = view(vi.metadata.vals, vview)
"""
setval!(vi::UntypedVarInfo, val, vview::Union{Int, UnitRange, Vector{Int}})
Set the value of `vi.vals[vview]` to `val`.
"""
setval!(vi::UntypedVarInfo, val, vview::VarView) = vi.metadata.vals[vview] = val
function setval!(vi::UntypedVarInfo, val, vview::Vector{UnitRange})
if length(vview) > 0
vi.metadata.vals[[i for arr in vview for i in arr]] = val
end
return val
end
"""
getmetadata(vi::VarInfo, vn::VarName)
Return the metadata in `vi` that belongs to `vn`.
"""
getmetadata(vi::VarInfo, vn::VarName) = vi.metadata
getmetadata(vi::TypedVarInfo, vn::VarName) = getfield(vi.metadata, getsym(vn))
"""
getidx(vi::VarInfo, vn::VarName)
Return the index of `vn` in the metadata of `vi` corresponding to `vn`.
"""
getidx(vi::VarInfo, vn::VarName) = getidx(getmetadata(vi, vn), vn)
getidx(md::Metadata, vn::VarName) = md.idcs[vn]
"""
getrange(vi::VarInfo, vn::VarName)
Return the index range of `vn` in the metadata of `vi`.
"""
getrange(vi::VarInfo, vn::VarName) = getrange(getmetadata(vi, vn), vn)
getrange(md::Metadata, vn::VarName) = md.ranges[getidx(md, vn)]
"""
setrange!(vi::VarInfo, vn::VarName, range)
Set the index range of `vn` in the metadata of `vi` to `range`.
"""
setrange!(vi::VarInfo, vn::VarName, range) = setrange!(getmetadata(vi, vn), vn, range)
setrange!(md::Metadata, vn::VarName, range) = md.ranges[getidx(md, vn)] = range
"""
getranges(vi::VarInfo, vns::Vector{<:VarName})
Return the indices of `vns` in the metadata of `vi` corresponding to `vn`.
"""
function getranges(vi::VarInfo, vns::Vector{<:VarName})
return mapreduce(vn -> getrange(vi, vn), vcat, vns; init=Int[])
end
"""
getdist(vi::VarInfo, vn::VarName)
Return the distribution from which `vn` was sampled in `vi`.
"""
getdist(vi::VarInfo, vn::VarName) = getdist(getmetadata(vi, vn), vn)
getdist(md::Metadata, vn::VarName) = md.dists[getidx(md, vn)]
"""
getval(vi::VarInfo, vn::VarName)
Return the value(s) of `vn`.
The values may or may not be transformed to Euclidean space.
"""
getval(vi::VarInfo, vn::VarName) = getval(getmetadata(vi, vn), vn)
getval(md::Metadata, vn::VarName) = view(md.vals, getrange(md, vn))
"""
setval!(vi::VarInfo, val, vn::VarName)
Set the value(s) of `vn` in the metadata of `vi` to `val`.
The values may or may not be transformed to Euclidean space.
"""
setval!(vi::VarInfo, val, vn::VarName) = setval!(getmetadata(vi, vn), val, vn)
function setval!(md::Metadata, val::AbstractVector, vn::VarName)
return md.vals[getrange(md, vn)] = val
end
function setval!(md::Metadata, val, vn::VarName)
return md.vals[getrange(md, vn)] = vectorize(getdist(md, vn), val)
end
"""
getval(vi::VarInfo, vns::Vector{<:VarName})
Return the value(s) of `vns`.
The values may or may not be transformed to Euclidean space.
"""
getval(vi::VarInfo, vns::Vector{<:VarName}) = mapreduce(Base.Fix1(getval, vi), vcat, vns)
"""
getall(vi::VarInfo)
Return the values of all the variables in `vi`.
The values may or may not be transformed to Euclidean space.
"""
getall(vi::UntypedVarInfo) = getall(vi.metadata)
# NOTE: `mapreduce` over `NamedTuple` results in worse type-inference.
# See for example https://github.com/JuliaLang/julia/pull/46381.
getall(vi::TypedVarInfo) = reduce(vcat, map(getall, vi.metadata))
function getall(md::Metadata)
return mapreduce(Base.Fix1(getval, md), vcat, md.vns; init=similar(md.vals, 0))
end
"""
setall!(vi::VarInfo, val)
Set the values of all the variables in `vi` to `val`.
The values may or may not be transformed to Euclidean space.
"""
function setall!(vi::UntypedVarInfo, val)
for r in vi.metadata.ranges
vi.metadata.vals[r] .= val[r]
end
end
setall!(vi::TypedVarInfo, val) = _setall!(vi.metadata, val)
@generated function _setall!(metadata::NamedTuple{names}, val) where {names}
expr = Expr(:block)
start = :(1)
for f in names
length = :(sum(length, metadata.$f.ranges))
finish = :($start + $length - 1)
push!(expr.args, :(copyto!(metadata.$f.vals, 1, val, $start, $length)))
start = :($start + $length)
end
return expr
end
"""
getgid(vi::VarInfo, vn::VarName)
Return the set of sampler selectors associated with `vn` in `vi`.
"""
getgid(vi::VarInfo, vn::VarName) = getmetadata(vi, vn).gids[getidx(vi, vn)]
function settrans!!(vi::VarInfo, trans::Bool, vn::VarName)
if trans
set_flag!(vi, vn, "trans")
else
unset_flag!(vi, vn, "trans")
end
return vi
end
function settrans!!(vi::VarInfo, trans::Bool)
for vn in keys(vi)
settrans!!(vi, trans, vn)
end
return vi
end
settrans!!(vi::VarInfo, trans::NoTransformation) = settrans!!(vi, false)
# HACK: This is necessary to make something like `link!!(transformation, vi, model)`
# work properly, which will transform the variables according to `transformation`
# and then call `settrans!!(vi, transformation)`. An alternative would be to add
# the `transformation` to the `VarInfo` object, but at the moment doesn't seem
# worth it as `VarInfo` has its own way of handling transformations.
settrans!!(vi::VarInfo, trans::AbstractTransformation) = settrans!!(vi, true)
"""
syms(vi::VarInfo)
Returns a tuple of the unique symbols of random variables sampled in `vi`.
"""
syms(vi::UntypedVarInfo) = Tuple(unique!(map(getsym, vi.metadata.vns))) # get all symbols
syms(vi::TypedVarInfo) = keys(vi.metadata)
# Get all indices of variables belonging to SampleFromPrior:
# if the gid/selector of a var is an empty Set, then that var is assumed to be assigned to
# the SampleFromPrior sampler
@inline function _getidcs(vi::UntypedVarInfo, ::SampleFromPrior)
return filter(i -> isempty(vi.metadata.gids[i]), 1:length(vi.metadata.gids))
end
# Get a NamedTuple of all the indices belonging to SampleFromPrior, one for each symbol
@inline function _getidcs(vi::TypedVarInfo, ::SampleFromPrior)
return _getidcs(vi.metadata)
end
@generated function _getidcs(metadata::NamedTuple{names}) where {names}
exprs = []
for f in names
push!(exprs, :($f = findinds(metadata.$f)))
end
length(exprs) == 0 && return :(NamedTuple())
return :($(exprs...),)
end
# Get all indices of variables belonging to a given sampler
@inline function _getidcs(vi::VarInfo, spl::Sampler)
# NOTE: 0b00 is the sanity flag for
# |\____ getidcs (mask = 0b10)
# \_____ getranges (mask = 0b01)
#if ~haskey(spl.info, :cache_updated) spl.info[:cache_updated] = CACHERESET end
# Checks if cache is valid, i.e. no new pushes were made, to return the cached idcs
# Otherwise, it recomputes the idcs and caches it
#if haskey(spl.info, :idcs) && (spl.info[:cache_updated] & CACHEIDCS) > 0
# spl.info[:idcs]
#else
#spl.info[:cache_updated] = spl.info[:cache_updated] | CACHEIDCS
idcs = _getidcs(vi, spl.selector, Val(getspace(spl)))
#spl.info[:idcs] = idcs
#end
return idcs
end
@inline _getidcs(vi::UntypedVarInfo, s::Selector, space) = findinds(vi.metadata, s, space)
@inline _getidcs(vi::TypedVarInfo, s::Selector, space) = _getidcs(vi.metadata, s, space)
# Get a NamedTuple for all the indices belonging to a given selector for each symbol
@generated function _getidcs(
metadata::NamedTuple{names}, s::Selector, ::Val{space}
) where {names,space}
exprs = []
# Iterate through each varname in metadata.
for f in names
# If the varname is in the sampler space
# or the sample space is empty (all variables)
# then return the indices for that variable.
if inspace(f, space) || length(space) == 0
push!(exprs, :($f = findinds(metadata.$f, s, Val($space))))
end
end
length(exprs) == 0 && return :(NamedTuple())
return :($(exprs...),)
end
@inline function findinds(f_meta, s, ::Val{space}) where {space}
# Get all the idcs of the vns in `space` and that belong to the selector `s`
return filter(
(i) ->
(s in f_meta.gids[i] || isempty(f_meta.gids[i])) &&
(isempty(space) || inspace(f_meta.vns[i], space)),
1:length(f_meta.gids),
)
end
@inline function findinds(f_meta)
# Get all the idcs of the vns
return filter((i) -> isempty(f_meta.gids[i]), 1:length(f_meta.gids))
end
# Get all vns of variables belonging to spl
_getvns(vi::VarInfo, spl::Sampler) = _getvns(vi, spl.selector, Val(getspace(spl)))
function _getvns(vi::VarInfo, spl::Union{SampleFromPrior,SampleFromUniform})
return _getvns(vi, Selector(), Val(()))
end
function _getvns(vi::UntypedVarInfo, s::Selector, space)
return view(vi.metadata.vns, _getidcs(vi, s, space))
end
function _getvns(vi::TypedVarInfo, s::Selector, space)
return _getvns(vi.metadata, _getidcs(vi, s, space))
end
# Get a NamedTuple for all the `vns` of indices `idcs`, one entry for each symbol
@generated function _getvns(metadata, idcs::NamedTuple{names}) where {names}
exprs = []
for f in names
push!(exprs, :($f = metadata.$f.vns[idcs.$f]))
end
length(exprs) == 0 && return :(NamedTuple())
return :($(exprs...),)
end
# Get the index (in vals) ranges of all the vns of variables belonging to spl
@inline function _getranges(vi::VarInfo, spl::Sampler)
## Uncomment the spl.info stuff when it is concretely typed, not Dict{Symbol, Any}
#if ~haskey(spl.info, :cache_updated) spl.info[:cache_updated] = CACHERESET end
#if haskey(spl.info, :ranges) && (spl.info[:cache_updated] & CACHERANGES) > 0
# spl.info[:ranges]
#else
#spl.info[:cache_updated] = spl.info[:cache_updated] | CACHERANGES
ranges = _getranges(vi, spl.selector, Val(getspace(spl)))
#spl.info[:ranges] = ranges
return ranges
#end
end
# Get the index (in vals) ranges of all the vns of variables belonging to selector `s` in `space`
@inline function _getranges(vi::VarInfo, s::Selector, space)
return _getranges(vi, _getidcs(vi, s, space))
end
@inline function _getranges(vi::UntypedVarInfo, idcs::Vector{Int})
return mapreduce(i -> vi.metadata.ranges[i], vcat, idcs; init=Int[])
end
@inline _getranges(vi::TypedVarInfo, idcs::NamedTuple) = _getranges(vi.metadata, idcs)
@generated function _getranges(metadata::NamedTuple, idcs::NamedTuple{names}) where {names}
exprs = []
for f in names
push!(exprs, :($f = findranges(metadata.$f.ranges, idcs.$f)))
end
length(exprs) == 0 && return :(NamedTuple())
return :($(exprs...),)
end
@inline function findranges(f_ranges, f_idcs)
# Old implementation was using `mapreduce` but turned out
# to be type-unstable.
results = Int[]
for i in f_idcs
append!(results, f_ranges[i])
end
return results
end
"""
set_flag!(vi::VarInfo, vn::VarName, flag::String)
Set `vn`'s value for `flag` to `true` in `vi`.
"""
function set_flag!(vi::VarInfo, vn::VarName, flag::String)
return getmetadata(vi, vn).flags[flag][getidx(vi, vn)] = true
end
####
#### APIs for typed and untyped VarInfo
####
# VarInfo
VarInfo(meta=Metadata()) = VarInfo(meta, Ref{Float64}(0.0), Ref(0))
"""
TypedVarInfo(vi::UntypedVarInfo)
This function finds all the unique `sym`s from the instances of `VarName{sym}` found in
`vi.metadata.vns`. It then extracts the metadata associated with each symbol from the
global `vi.metadata` field. Finally, a new `VarInfo` is created with a new `metadata` as
a `NamedTuple` mapping from symbols to type-stable `Metadata` instances, one for each
symbol.
"""
function TypedVarInfo(vi::UntypedVarInfo)
meta = vi.metadata
new_metas = Metadata[]
# Symbols of all instances of `VarName{sym}` in `vi.vns`
syms_tuple = Tuple(syms(vi))
for s in syms_tuple
# Find all indices in `vns` with symbol `s`
inds = findall(vn -> getsym(vn) === s, meta.vns)
n = length(inds)
# New `vns`
sym_vns = getindex.((meta.vns,), inds)
# New idcs
sym_idcs = Dict(a => i for (i, a) in enumerate(sym_vns))
# New dists
sym_dists = getindex.((meta.dists,), inds)
# New gids, can make a resizeable FillArray
sym_gids = getindex.((meta.gids,), inds)
@assert length(sym_gids) <= 1 || all(x -> x == sym_gids[1], @view sym_gids[2:end])
# New orders
sym_orders = getindex.((meta.orders,), inds)
# New flags
sym_flags = Dict(a => meta.flags[a][inds] for a in keys(meta.flags))
# Extract new ranges and vals
_ranges = getindex.((meta.ranges,), inds)
# `copy.()` is a workaround to reduce the eltype from Real to Int or Float64
_vals = [copy.(meta.vals[_ranges[i]]) for i in 1:n]
sym_ranges = Vector{eltype(_ranges)}(undef, n)
start = 0
for i in 1:n
sym_ranges[i] = (start + 1):(start + length(_vals[i]))
start += length(_vals[i])
end
sym_vals = foldl(vcat, _vals)
push!(
new_metas,
Metadata(
sym_idcs,
sym_vns,
sym_ranges,
sym_vals,
sym_dists,
sym_gids,
sym_orders,
sym_flags,
),
)
end
logp = getlogp(vi)
num_produce = get_num_produce(vi)
nt = NamedTuple{syms_tuple}(Tuple(new_metas))
return VarInfo(nt, Ref(logp), Ref(num_produce))
end
TypedVarInfo(vi::TypedVarInfo) = vi
function BangBang.empty!!(vi::VarInfo)
_empty!(vi.metadata)
resetlogp!!(vi)
reset_num_produce!(vi)
return vi
end
@inline _empty!(metadata::Metadata) = empty!(metadata)
@generated function _empty!(metadata::NamedTuple{names}) where {names}
expr = Expr(:block)
for f in names
push!(expr.args, :(empty!(metadata.$f)))
end
return expr
end
# Functions defined only for UntypedVarInfo
Base.keys(vi::UntypedVarInfo) = keys(vi.metadata.idcs)
# HACK: Necessary to avoid returning `Any[]` which won't dispatch correctly
# on other methods in the codebase which requires `Vector{<:VarName}`.
Base.keys(vi::TypedVarInfo{<:NamedTuple{()}}) = VarName[]
@generated function Base.keys(vi::TypedVarInfo{<:NamedTuple{names}}) where {names}
expr = Expr(:call)
push!(expr.args, :vcat)
for n in names
push!(expr.args, :(vi.metadata.$n.vns))
end
return expr
end
"""
setgid!(vi::VarInfo, gid::Selector, vn::VarName)
Add `gid` to the set of sampler selectors associated with `vn` in `vi`.
"""
function setgid!(vi::VarInfo, gid::Selector, vn::VarName)
return push!(getmetadata(vi, vn).gids[getidx(vi, vn)], gid)
end
istrans(vi::VarInfo, vn::VarName) = is_flagged(vi, vn, "trans")
getlogp(vi::VarInfo) = vi.logp[]
function setlogp!!(vi::VarInfo, logp)
vi.logp[] = logp
return vi
end
function acclogp!!(vi::VarInfo, logp)
vi.logp[] += logp
return vi
end
"""
get_num_produce(vi::VarInfo)
Return the `num_produce` of `vi`.
"""
get_num_produce(vi::VarInfo) = vi.num_produce[]
"""
set_num_produce!(vi::VarInfo, n::Int)
Set the `num_produce` field of `vi` to `n`.
"""
set_num_produce!(vi::VarInfo, n::Int) = vi.num_produce[] = n
"""
increment_num_produce!(vi::VarInfo)
Add 1 to `num_produce` in `vi`.
"""
increment_num_produce!(vi::VarInfo) = vi.num_produce[] += 1
"""
reset_num_produce!(vi::VarInfo)
Reset the value of `num_produce` the log of the joint probability of the observed data
and parameters sampled in `vi` to 0.
"""
reset_num_produce!(vi::VarInfo) = set_num_produce!(vi, 0)
isempty(vi::UntypedVarInfo) = isempty(vi.metadata.idcs)
isempty(vi::TypedVarInfo) = _isempty(vi.metadata)
@generated function _isempty(metadata::NamedTuple{names}) where {names}
expr = Expr(:&&, :true)
for f in names
push!(expr.args, :(isempty(metadata.$f.idcs)))
end
return expr
end
# X -> R for all variables associated with given sampler
function link!!(t::DynamicTransformation, vi::VarInfo, spl::AbstractSampler, model::Model)
# Call `_link!` instead of `link!` to avoid deprecation warning.
_link!(vi, spl)
return vi
end
function link!!(
t::DynamicTransformation,
vi::ThreadSafeVarInfo{<:VarInfo},
spl::AbstractSampler,
model::Model,
)
# By default this will simply evaluate the model with `DynamicTransformationContext`, and so
# we need to specialize to avoid this.
return Accessors.@set vi.varinfo = DynamicPPL.link!!(t, vi.varinfo, spl, model)
end
"""
link!(vi::VarInfo, spl::Sampler)
Transform the values of the random variables sampled by `spl` in `vi` from the support
of their distributions to the Euclidean space and set their corresponding `"trans"`
flag values to `true`.
"""
function link!(vi::VarInfo, spl::AbstractSampler)
Base.depwarn(
"`link!(varinfo, sampler)` is deprecated, use `link!!(varinfo, sampler, model)` instead.",
:link!,
)
return _link!(vi, spl)
end
function link!(vi::VarInfo, spl::AbstractSampler, spaceval::Val)
Base.depwarn(
"`link!(varinfo, sampler, spaceval)` is deprecated, use `link!!(varinfo, sampler, model)` instead.",
:link!,
)
return _link!(vi, spl, spaceval)
end
function _link!(vi::UntypedVarInfo, spl::AbstractSampler)
# TODO: Change to a lazy iterator over `vns`
vns = _getvns(vi, spl)
if ~istrans(vi, vns[1])
for vn in vns