/
model.jl
1305 lines (998 loc) · 37.5 KB
/
model.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
"""
struct Model{F,argnames,defaultnames,missings,Targs,Tdefaults}
f::F
args::NamedTuple{argnames,Targs}
defaults::NamedTuple{defaultnames,Tdefaults}
end
A `Model` struct with model evaluation function of type `F`, arguments of names `argnames`
types `Targs`, default arguments of names `defaultnames` with types `Tdefaults`, and missing
arguments `missings`.
Here `argnames`, `defaultargnames`, and `missings` are tuples of symbols, e.g. `(:a, :b)`.
An argument with a type of `Missing` will be in `missings` by default. However, in
non-traditional use-cases `missings` can be defined differently. All variables in `missings`
are treated as random variables rather than observations.
The default arguments are used internally when constructing instances of the same model with
different arguments.
# Examples
```julia
julia> Model(f, (x = 1.0, y = 2.0))
Model{typeof(f),(:x, :y),(),(),Tuple{Float64,Float64},Tuple{}}(f, (x = 1.0, y = 2.0), NamedTuple())
julia> Model(f, (x = 1.0, y = 2.0), (x = 42,))
Model{typeof(f),(:x, :y),(:x,),(),Tuple{Float64,Float64},Tuple{Int64}}(f, (x = 1.0, y = 2.0), (x = 42,))
julia> Model{(:y,)}(f, (x = 1.0, y = 2.0), (x = 42,)) # with special definition of missings
Model{typeof(f),(:x, :y),(:x,),(:y,),Tuple{Float64,Float64},Tuple{Int64}}(f, (x = 1.0, y = 2.0), (x = 42,))
```
"""
struct Model{F,argnames,defaultnames,missings,Targs,Tdefaults,Ctx<:AbstractContext} <:
AbstractProbabilisticProgram
f::F
args::NamedTuple{argnames,Targs}
defaults::NamedTuple{defaultnames,Tdefaults}
context::Ctx
@doc """
Model{missings}(f, args::NamedTuple, defaults::NamedTuple)
Create a model with evaluation function `f` and missing arguments overwritten by
`missings`.
"""
function Model{missings}(
f::F,
args::NamedTuple{argnames,Targs},
defaults::NamedTuple{defaultnames,Tdefaults},
context::Ctx=DefaultContext(),
) where {missings,F,argnames,Targs,defaultnames,Tdefaults,Ctx}
return new{F,argnames,defaultnames,missings,Targs,Tdefaults,Ctx}(
f, args, defaults, context
)
end
end
"""
Model(f, args::NamedTuple[, defaults::NamedTuple = ()])
Create a model with evaluation function `f` and missing arguments deduced from `args`.
Default arguments `defaults` are used internally when constructing instances of the same
model with different arguments.
"""
@generated function Model(
f::F,
args::NamedTuple{argnames,Targs},
defaults::NamedTuple,
context::AbstractContext=DefaultContext(),
) where {F,argnames,Targs}
missings = Tuple(name for (name, typ) in zip(argnames, Targs.types) if typ <: Missing)
return :(Model{$missings}(f, args, defaults, context))
end
function Model(f, args::NamedTuple, context::AbstractContext=DefaultContext(); kwargs...)
return Model(f, args, NamedTuple(kwargs), context)
end
function contextualize(model::Model, context::AbstractContext)
return Model(model.f, model.args, model.defaults, context)
end
"""
model | (x = 1.0, ...)
Return a `Model` which now treats variables on the right-hand side as observations.
See [`condition`](@ref) for more information and examples.
"""
Base.:|(model::Model, values) = condition(model, values)
"""
condition(model::Model; values...)
condition(model::Model, values::NamedTuple)
Return a `Model` which now treats the variables in `values` as observations.
See also: [`decondition`](@ref), [`conditioned`](@ref)
# Limitations
This does currently _not_ work with variables that are
provided to the model as arguments, e.g. `@model function demo(x) ... end`
means that `condition` will not affect the variable `x`.
Therefore if one wants to make use of `condition` and [`decondition`](@ref)
one should not be specifying any random variables as arguments.
This is done for the sake of backwards compatibility.
# Examples
## Simple univariate model
```jldoctest condition
julia> using Distributions
julia> @model function demo()
m ~ Normal()
x ~ Normal(m, 1)
return (; m=m, x=x)
end
demo (generic function with 2 methods)
julia> model = demo();
julia> m, x = model(); (m ≠ 1.0 && x ≠ 100.0)
true
julia> # Create a new instance which treats `x` as observed
# with value `100.0`, and similarly for `m=1.0`.
conditioned_model = condition(model, x=100.0, m=1.0);
julia> m, x = conditioned_model(); (m == 1.0 && x == 100.0)
true
julia> # Let's only condition on `x = 100.0`.
conditioned_model = condition(model, x = 100.0);
julia> m, x =conditioned_model(); (m ≠ 1.0 && x == 100.0)
true
julia> # We can also use the nicer `|` syntax.
conditioned_model = model | (x = 100.0, );
julia> m, x = conditioned_model(); (m ≠ 1.0 && x == 100.0)
true
```
The above uses a `NamedTuple` to hold the conditioning variables, which allows us to perform some
additional optimizations; in many cases, the above has zero runtime-overhead.
But we can also use a `Dict`, which offers more flexibility in the conditioning
(see examples further below) but generally has worse performance than the `NamedTuple`
approach:
```jldoctest condition
julia> conditioned_model_dict = condition(model, Dict(@varname(x) => 100.0));
julia> m, x = conditioned_model_dict(); (m ≠ 1.0 && x == 100.0)
true
julia> # There's also an option using `|` by letting the right-hand side be a tuple
# with elements of type `Pair{<:VarName}`, i.e. `vn => value` with `vn isa VarName`.
conditioned_model_dict = model | (@varname(x) => 100.0, );
julia> m, x = conditioned_model_dict(); (m ≠ 1.0 && x == 100.0)
true
```
## Condition only a part of a multivariate variable
Not only can be condition on multivariate random variables, but
we can also use the standard mechanism of setting something to `missing`
in the call to `condition` to only condition on a part of the variable.
```jldoctest condition
julia> @model function demo_mv(::Type{TV}=Float64) where {TV}
m = Vector{TV}(undef, 2)
m[1] ~ Normal()
m[2] ~ Normal()
return m
end
demo_mv (generic function with 4 methods)
julia> model = demo_mv();
julia> conditioned_model = condition(model, m = [missing, 1.0]);
julia> # (✓) `m[1]` sampled while `m[2]` is fixed
m = conditioned_model(); (m[1] ≠ 1.0 && m[2] == 1.0)
true
```
Intuitively one might also expect to be able to write `model | (m[1] = 1.0, )`.
Unfortunately this is not supported as it has the potential of increasing compilation
times but without offering any benefit with respect to runtime:
```jldoctest condition
julia> # (×) `m[2]` is not set to 1.0.
m = condition(model, var"m[2]" = 1.0)(); m[2] == 1.0
false
```
But you _can_ do this if you use a `Dict` as the underlying storage instead:
```jldoctest condition
julia> # Alternatives:
# - `model | (@varname(m[2]) => 1.0,)`
# - `condition(model, Dict(@varname(m[2] => 1.0)))`
# (✓) `m[2]` is set to 1.0.
m = condition(model, @varname(m[2]) => 1.0)(); (m[1] ≠ 1.0 && m[2] == 1.0)
true
```
## Nested models
`condition` of course also supports the use of nested models through
the use of [`@submodel`](@ref).
```jldoctest condition
julia> @model demo_inner() = m ~ Normal()
demo_inner (generic function with 2 methods)
julia> @model function demo_outer()
@submodel m = demo_inner()
return m
end
demo_outer (generic function with 2 methods)
julia> model = demo_outer();
julia> model() ≠ 1.0
true
julia> conditioned_model = model | (m = 1.0, );
julia> conditioned_model()
1.0
```
But one needs to be careful when prefixing variables in the nested models:
```jldoctest condition
julia> @model function demo_outer_prefix()
@submodel prefix="inner" m = demo_inner()
return m
end
demo_outer_prefix (generic function with 2 methods)
julia> # (×) This doesn't work now!
conditioned_model = demo_outer_prefix() | (m = 1.0, );
julia> conditioned_model() == 1.0
false
julia> # (✓) `m` in `demo_inner` is referred to as `inner.m` internally, so we do:
conditioned_model = demo_outer_prefix() | (var"inner.m" = 1.0, );
julia> conditioned_model()
1.0
julia> # Note that the above `var"..."` is just standard Julia syntax:
keys((var"inner.m" = 1.0, ))
(Symbol("inner.m"),)
```
And similarly when using `Dict`:
```jldoctest condition
julia> conditioned_model_dict = demo_outer_prefix() | (@varname(var"inner.m") => 1.0);
julia> conditioned_model_dict()
1.0
```
The difference is maybe more obvious once we look at how these different
in their trace/`VarInfo`:
```jldoctest condition
julia> keys(VarInfo(demo_outer()))
1-element Vector{VarName{:m, typeof(identity)}}:
m
julia> keys(VarInfo(demo_outer_prefix()))
1-element Vector{VarName{Symbol("inner.m"), typeof(identity)}}:
inner.m
```
From this we can tell what the correct way to condition `m` within `demo_inner`
is in the two different models.
"""
AbstractPPL.condition(model::Model; values...) = condition(model, NamedTuple(values))
function AbstractPPL.condition(model::Model, value, values...)
return contextualize(model, condition(model.context, value, values...))
end
"""
decondition(model::Model)
decondition(model::Model, variables...)
Return a `Model` for which `variables...` are _not_ considered observations.
If no `variables` are provided, then all variables currently considered observations
will no longer be.
This is essentially the inverse of [`condition`](@ref). This also means that
it suffers from the same limitiations.
Note that currently we only support `variables` to take on explicit values
provided to `condition`.
# Examples
```jldoctest decondition
julia> using Distributions
julia> @model function demo()
m ~ Normal()
x ~ Normal(m, 1)
return (; m=m, x=x)
end
demo (generic function with 2 methods)
julia> conditioned_model = condition(demo(), m = 1.0, x = 10.0);
julia> conditioned_model()
(m = 1.0, x = 10.0)
julia> # By specifying the `VarName` to `decondition`.
model = decondition(conditioned_model, @varname(m));
julia> (m, x) = model(); (m ≠ 1.0 && x == 10.0)
true
julia> # When `NamedTuple` is used as the underlying, you can also provide
# the symbol directly (though the `@varname` approach is preferable if
# if the variable is known at compile-time).
model = decondition(conditioned_model, :m);
julia> (m, x) = model(); (m ≠ 1.0 && x == 10.0)
true
julia> # `decondition` multiple at once:
(m, x) = decondition(model, :m, :x)(); (m ≠ 1.0 && x ≠ 10.0)
true
julia> # `decondition` without any symbols will `decondition` all variables.
(m, x) = decondition(model)(); (m ≠ 1.0 && x ≠ 10.0)
true
julia> # Usage of `Val` to perform `decondition` at compile-time if possible
# is also supported.
model = decondition(conditioned_model, Val{:m}());
julia> (m, x) = model(); (m ≠ 1.0 && x == 10.0)
true
```
Similarly when using a `Dict`:
```jldoctest decondition
julia> conditioned_model_dict = condition(demo(), @varname(m) => 1.0, @varname(x) => 10.0);
julia> conditioned_model_dict()
(m = 1.0, x = 10.0)
julia> deconditioned_model_dict = decondition(conditioned_model_dict, @varname(m));
julia> (m, x) = deconditioned_model_dict(); m ≠ 1.0 && x == 10.0
true
```
But, as mentioned, `decondition` is only supported for variables explicitly
provided to `condition` earlier;
```jldoctest decondition
julia> @model function demo_mv(::Type{TV}=Float64) where {TV}
m = Vector{TV}(undef, 2)
m[1] ~ Normal()
m[2] ~ Normal()
return m
end
demo_mv (generic function with 4 methods)
julia> model = demo_mv();
julia> conditioned_model = condition(model, @varname(m) => [1.0, 2.0]);
julia> conditioned_model()
2-element Vector{Float64}:
1.0
2.0
julia> deconditioned_model = decondition(conditioned_model, @varname(m[1]));
julia> deconditioned_model() # (×) `m[1]` is still conditioned
2-element Vector{Float64}:
1.0
2.0
julia> # (✓) this works though
deconditioned_model_2 = deconditioned_model | (@varname(m[1]) => missing);
julia> m = deconditioned_model_2(); (m[1] ≠ 1.0 && m[2] == 2.0)
true
```
"""
function AbstractPPL.decondition(model::Model, syms...)
return contextualize(model, decondition(model.context, syms...))
end
"""
observations(model::Model)
Alias for [`conditioned`](@ref).
"""
observations(model::Model) = conditioned(model)
"""
conditioned(model::Model)
Return the conditioned values in `model`.
# Examples
```jldoctest
julia> using Distributions
julia> using DynamicPPL: conditioned, contextualize
julia> @model function demo()
m ~ Normal()
x ~ Normal(m, 1)
end
demo (generic function with 2 methods)
julia> m = demo();
julia> # Returns all the variables we have conditioned on + their values.
conditioned(condition(m, x=100.0, m=1.0))
(x = 100.0, m = 1.0)
julia> # Nested ones also work (note that `PrefixContext` does nothing to the result).
cm = condition(contextualize(m, PrefixContext{:a}(condition(m=1.0))), x=100.0);
julia> conditioned(cm)
(x = 100.0, m = 1.0)
julia> # Since we conditioned on `m`, not `a.m` as it will appear after prefixed,
# `a.m` is treated as a random variable.
keys(VarInfo(cm))
1-element Vector{VarName{Symbol("a.m"), typeof(identity)}}:
a.m
julia> # If we instead condition on `a.m`, `m` in the model will be considered an observation.
cm = condition(contextualize(m, PrefixContext{:a}(condition(var"a.m"=1.0))), x=100.0);
julia> conditioned(cm).x
100.0
julia> conditioned(cm).var"a.m"
1.0
julia> keys(VarInfo(cm)) # <= no variables are sampled
VarName[]
```
"""
conditioned(model::Model) = conditioned(model.context)
"""
fix(model::Model; values...)
fix(model::Model, values::NamedTuple)
Return a `Model` which now treats the variables in `values` as fixed.
See also: [`unfix`](@ref), [`fixed`](@ref)
# Examples
## Simple univariate model
```jldoctest fix
julia> using Distributions
julia> @model function demo()
m ~ Normal()
x ~ Normal(m, 1)
return (; m=m, x=x)
end
demo (generic function with 2 methods)
julia> model = demo();
julia> m, x = model(); (m ≠ 1.0 && x ≠ 100.0)
true
julia> # Create a new instance which treats `x` as observed
# with value `100.0`, and similarly for `m=1.0`.
fixed_model = fix(model, x=100.0, m=1.0);
julia> m, x = fixed_model(); (m == 1.0 && x == 100.0)
true
julia> # Let's only fix on `x = 100.0`.
fixed_model = fix(model, x = 100.0);
julia> m, x = fixed_model(); (m ≠ 1.0 && x == 100.0)
true
```
The above uses a `NamedTuple` to hold the fixed variables, which allows us to perform some
additional optimizations; in many cases, the above has zero runtime-overhead.
But we can also use a `Dict`, which offers more flexibility in the fixing
(see examples further below) but generally has worse performance than the `NamedTuple`
approach:
```jldoctest fix
julia> fixed_model_dict = fix(model, Dict(@varname(x) => 100.0));
julia> m, x = fixed_model_dict(); (m ≠ 1.0 && x == 100.0)
true
julia> # Alternative: pass `Pair{<:VarName}` as positional argument.
fixed_model_dict = fix(model, @varname(x) => 100.0, );
julia> m, x = fixed_model_dict(); (m ≠ 1.0 && x == 100.0)
true
```
## Fix only a part of a multivariate variable
We can not only fix multivariate random variables, but
we can also use the standard mechanism of setting something to `missing`
in the call to `fix` to only fix a part of the variable.
```jldoctest fix
julia> @model function demo_mv(::Type{TV}=Float64) where {TV}
m = Vector{TV}(undef, 2)
m[1] ~ Normal()
m[2] ~ Normal()
return m
end
demo_mv (generic function with 4 methods)
julia> model = demo_mv();
julia> fixed_model = fix(model, m = [missing, 1.0]);
julia> # (✓) `m[1]` sampled while `m[2]` is fixed
m = fixed_model(); (m[1] ≠ 1.0 && m[2] == 1.0)
true
```
Intuitively one might also expect to be able to write something like `fix(model, var\"m[1]\" = 1.0, )`.
Unfortunately this is not supported as it has the potential of increasing compilation
times but without offering any benefit with respect to runtime:
```jldoctest fix
julia> # (×) `m[2]` is not set to 1.0.
m = fix(model, var"m[2]" = 1.0)(); m[2] == 1.0
false
```
But you _can_ do this if you use a `Dict` as the underlying storage instead:
```jldoctest fix
julia> # Alternative: `fix(model, Dict(@varname(m[2] => 1.0)))`
# (✓) `m[2]` is set to 1.0.
m = fix(model, @varname(m[2]) => 1.0)(); (m[1] ≠ 1.0 && m[2] == 1.0)
true
```
## Nested models
`fix` of course also supports the use of nested models through
the use of [`@submodel`](@ref).
```jldoctest fix
julia> @model demo_inner() = m ~ Normal()
demo_inner (generic function with 2 methods)
julia> @model function demo_outer()
@submodel m = demo_inner()
return m
end
demo_outer (generic function with 2 methods)
julia> model = demo_outer();
julia> model() ≠ 1.0
true
julia> fixed_model = model | (m = 1.0, );
julia> fixed_model()
1.0
```
But one needs to be careful when prefixing variables in the nested models:
```jldoctest fix
julia> @model function demo_outer_prefix()
@submodel prefix="inner" m = demo_inner()
return m
end
demo_outer_prefix (generic function with 2 methods)
julia> # (×) This doesn't work now!
fixed_model = demo_outer_prefix() | (m = 1.0, );
julia> fixed_model() == 1.0
false
julia> # (✓) `m` in `demo_inner` is referred to as `inner.m` internally, so we do:
fixed_model = demo_outer_prefix() | (var"inner.m" = 1.0, );
julia> fixed_model()
1.0
julia> # Note that the above `var"..."` is just standard Julia syntax:
keys((var"inner.m" = 1.0, ))
(Symbol("inner.m"),)
```
And similarly when using `Dict`:
```jldoctest fix
julia> fixed_model_dict = demo_outer_prefix() | (@varname(var"inner.m") => 1.0);
julia> fixed_model_dict()
1.0
```
The difference is maybe more obvious once we look at how these different
in their trace/`VarInfo`:
```jldoctest fix
julia> keys(VarInfo(demo_outer()))
1-element Vector{VarName{:m, typeof(identity)}}:
m
julia> keys(VarInfo(demo_outer_prefix()))
1-element Vector{VarName{Symbol("inner.m"), typeof(identity)}}:
inner.m
```
From this we can tell what the correct way to fix `m` within `demo_inner`
is in the two different models.
## Difference from `condition`
A very similar functionality is also provided by [`condition`](@ref) which,
not surprisingly, _conditions_ variables instead of fixing them. The only
difference between fixing and conditioning is as follows:
- `condition`ed variables are considered to be observations, and are thus
included in the computation [`logjoint`](@ref) and [`loglikelihood`](@ref),
but not in [`logprior`](@ref).
- `fix`ed variables are considered to be constant, and are thus not included
in any log-probability computations.
```juliadoctest fix
julia> @model function demo()
m ~ Normal()
x ~ Normal(m, 1)
return (; m=m, x=x)
end
demo (generic function with 2 methods)
julia> model = demo();
julia> model_fixed = fix(model, m = 1.0);
julia> model_conditioned = condition(model, m = 1.0);
julia> logjoint(model_fixed, (x=1.0,))
-0.9189385332046728
julia> # Different!
logjoint(model_conditioned, (x=1.0,))
-2.3378770664093453
julia> # And the difference is the missing log-probability of `m`:
logjoint(model_fixed, (x=1.0,)) + logpdf(Normal(), 1.0) == logjoint(model_conditioned, (x=1.0,))
true
```
"""
fix(model::Model; values...) = contextualize(model, fix(model.context; values...))
function fix(model::Model, value, values...)
return contextualize(model, fix(model.context, value, values...))
end
"""
unfix(model::Model)
unfix(model::Model, variables...)
Return a `Model` for which `variables...` are _not_ considered fixed.
If no `variables` are provided, then all variables currently considered fixed
will no longer be.
This is essentially the inverse of [`fix`](@ref). This also means that
it suffers from the same limitiations.
Note that currently we only support `variables` to take on explicit values
provided to `fix`.
# Examples
```jldoctest unfix
julia> using Distributions
julia> @model function demo()
m ~ Normal()
x ~ Normal(m, 1)
return (; m=m, x=x)
end
demo (generic function with 2 methods)
julia> fixed_model = fix(demo(), m = 1.0, x = 10.0);
julia> fixed_model()
(m = 1.0, x = 10.0)
julia> # By specifying the `VarName` to `unfix`.
model = unfix(fixed_model, @varname(m));
julia> (m, x) = model(); (m ≠ 1.0 && x == 10.0)
true
julia> # When `NamedTuple` is used as the underlying, you can also provide
# the symbol directly (though the `@varname` approach is preferable if
# if the variable is known at compile-time).
model = unfix(fixed_model, :m);
julia> (m, x) = model(); (m ≠ 1.0 && x == 10.0)
true
julia> # `unfix` multiple at once:
(m, x) = unfix(model, :m, :x)(); (m ≠ 1.0 && x ≠ 10.0)
true
julia> # `unfix` without any symbols will `unfix` all variables.
(m, x) = unfix(model)(); (m ≠ 1.0 && x ≠ 10.0)
true
julia> # Usage of `Val` to perform `unfix` at compile-time if possible
# is also supported.
model = unfix(fixed_model, Val{:m}());
julia> (m, x) = model(); (m ≠ 1.0 && x == 10.0)
true
```
Similarly when using a `Dict`:
```jldoctest unfix
julia> fixed_model_dict = fix(demo(), @varname(m) => 1.0, @varname(x) => 10.0);
julia> fixed_model_dict()
(m = 1.0, x = 10.0)
julia> unfixed_model_dict = unfix(fixed_model_dict, @varname(m));
julia> (m, x) = unfixed_model_dict(); m ≠ 1.0 && x == 10.0
true
```
But, as mentioned, `unfix` is only supported for variables explicitly
provided to `fix` earlier:
```jldoctest unfix
julia> @model function demo_mv(::Type{TV}=Float64) where {TV}
m = Vector{TV}(undef, 2)
m[1] ~ Normal()
m[2] ~ Normal()
return m
end
demo_mv (generic function with 4 methods)
julia> model = demo_mv();
julia> fixed_model = fix(model, @varname(m) => [1.0, 2.0]);
julia> fixed_model()
2-element Vector{Float64}:
1.0
2.0
julia> unfixed_model = unfix(fixed_model, @varname(m[1]));
julia> unfixed_model() # (×) `m[1]` is still fixed
2-element Vector{Float64}:
1.0
2.0
julia> # (✓) this works though
unfixed_model_2 = fix(unfixed_model, @varname(m[1]) => missing);
julia> m = unfixed_model_2(); (m[1] ≠ 1.0 && m[2] == 2.0)
true
```
"""
unfix(model::Model, syms...) = contextualize(model, unfix(model.context, syms...))
"""
fixed(model::Model)
Return the fixed values in `model`.
# Examples
```jldoctest
julia> using Distributions
julia> using DynamicPPL: fixed, contextualize
julia> @model function demo()
m ~ Normal()
x ~ Normal(m, 1)
end
demo (generic function with 2 methods)
julia> m = demo();
julia> # Returns all the variables we have fixed on + their values.
fixed(fix(m, x=100.0, m=1.0))
(x = 100.0, m = 1.0)
julia> # Nested ones also work (note that `PrefixContext` does nothing to the result).
cm = fix(contextualize(m, PrefixContext{:a}(fix(m=1.0))), x=100.0);
julia> fixed(cm)
(x = 100.0, m = 1.0)
julia> # Since we fixed on `m`, not `a.m` as it will appear after prefixed,
# `a.m` is treated as a random variable.
keys(VarInfo(cm))
1-element Vector{VarName{Symbol("a.m"), typeof(identity)}}:
a.m
julia> # If we instead fix on `a.m`, `m` in the model will be considered an observation.
cm = fix(contextualize(m, PrefixContext{:a}(fix(var"a.m"=1.0))), x=100.0);
julia> fixed(cm).x
100.0
julia> fixed(cm).var"a.m"
1.0
julia> keys(VarInfo(cm)) # <= no variables are sampled
VarName[]
```
"""
fixed(model::Model) = fixed(model.context)
"""
(model::Model)([rng, varinfo, sampler, context])
Sample from the `model` using the `sampler` with random number generator `rng` and the
`context`, and store the sample and log joint probability in `varinfo`.
The method resets the log joint probability of `varinfo` and increases the evaluation
number of `sampler`.
"""
(model::Model)(args...) = first(evaluate!!(model, args...))
"""
use_threadsafe_eval(context::AbstractContext, varinfo::AbstractVarInfo)
Return `true` if evaluation of a model using `context` and `varinfo` should
wrap `varinfo` in `ThreadSafeVarInfo`, i.e. threadsafe evaluation, and `false` otherwise.
"""
function use_threadsafe_eval(context::AbstractContext, varinfo::AbstractVarInfo)
return Threads.nthreads() > 1
end
"""
evaluate!!(model::Model[, rng, varinfo, sampler, context])
Sample from the `model` using the `sampler` with random number generator `rng` and the
`context`, and store the sample and log joint probability in `varinfo`.
Returns both the return-value of the original model, and the resulting varinfo.
The method resets the log joint probability of `varinfo` and increases the evaluation
number of `sampler`.
"""
function AbstractPPL.evaluate!!(
model::Model, varinfo::AbstractVarInfo, context::AbstractContext
)
return if use_threadsafe_eval(context, varinfo)
evaluate_threadsafe!!(model, varinfo, context)
else
evaluate_threadunsafe!!(model, varinfo, context)
end
end
function AbstractPPL.evaluate!!(
model::Model,
rng::Random.AbstractRNG,
varinfo::AbstractVarInfo=VarInfo(),
sampler::AbstractSampler=SampleFromPrior(),
context::AbstractContext=DefaultContext(),
)
return evaluate!!(model, varinfo, SamplingContext(rng, sampler, context))
end
function AbstractPPL.evaluate!!(model::Model, context::AbstractContext)
return evaluate!!(model, VarInfo(), context)
end
function AbstractPPL.evaluate!!(model::Model, args...)
return evaluate!!(model, Random.default_rng(), args...)
end
# without VarInfo
function AbstractPPL.evaluate!!(
model::Model, rng::Random.AbstractRNG, sampler::AbstractSampler, args...
)
return evaluate!!(model, rng, VarInfo(), sampler, args...)
end
# without VarInfo and without AbstractSampler
function AbstractPPL.evaluate!!(
model::Model, rng::Random.AbstractRNG, context::AbstractContext
)
return evaluate!!(model, rng, VarInfo(), SampleFromPrior(), context)
end
"""
evaluate_threadunsafe!!(model, varinfo, context)
Evaluate the `model` without wrapping `varinfo` inside a `ThreadSafeVarInfo`.
If the `model` makes use of Julia's multithreading this will lead to undefined behaviour.
This method is not exposed and supposed to be used only internally in DynamicPPL.
See also: [`evaluate_threadsafe!!`](@ref)
"""
function evaluate_threadunsafe!!(model, varinfo, context)
return _evaluate!!(model, resetlogp!!(varinfo), context)
end
"""
evaluate_threadsafe!!(model, varinfo, context)
Evaluate the `model` with `varinfo` wrapped inside a `ThreadSafeVarInfo`.
With the wrapper, Julia's multithreading can be used for observe statements in the `model`
but parallel sampling will lead to undefined behaviour.
This method is not exposed and supposed to be used only internally in DynamicPPL.
See also: [`evaluate_threadunsafe!!`](@ref)
"""
function evaluate_threadsafe!!(model, varinfo, context)
wrapper = ThreadSafeVarInfo(resetlogp!!(varinfo))
result, wrapper_new = _evaluate!!(model, wrapper, context)
return result, setlogp!!(wrapper_new.varinfo, getlogp(wrapper_new))
end
"""
_evaluate!!(model::Model, varinfo, context)
Evaluate the `model` with the arguments matching the given `context` and `varinfo` object.
"""
function _evaluate!!(model::Model, varinfo::AbstractVarInfo, context::AbstractContext)
args, kwargs = make_evaluate_args_and_kwargs(model, varinfo, context)
return model.f(args...; kwargs...)
end
"""
make_evaluate_args_and_kwargs(model, varinfo, context)
Return the arguments and keyword arguments to be passed to the evaluator of the model, i.e. `model.f`e.
"""
@generated function make_evaluate_args_and_kwargs(
model::Model{_F,argnames}, varinfo::AbstractVarInfo, context::AbstractContext
) where {_F,argnames}
unwrap_args = [
if is_splat_symbol(var)
:($matchingvalue(context_new, varinfo, model.args.$var)...)
else
:($matchingvalue(context_new, varinfo, model.args.$var))
end for var in argnames
]
# We want to give `context` precedence over `model.context` while also
# preserving the leaf context of `context`. We can do this by
# 1. Set the leaf context of `model.context` to `leafcontext(context)`.
# 2. Set leaf context of `context` to the context resulting from (1).
# The result is:
# `context` -> `childcontext(context)` -> ... -> `model.context`
# -> `childcontext(model.context)` -> ... -> `leafcontext(context)`
return quote
context_new = setleafcontext(
context, setleafcontext(model.context, leafcontext(context))
)
args = (
model,
# Maybe perform `invlink!!` once prior to evaluation to avoid
# lazy `invlink`-ing of the parameters. This can be useful for
# speeding up computation. See docs for `maybe_invlink_before_eval!!`
# for more information.
maybe_invlink_before_eval!!(varinfo, context_new, model),
context_new,