-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
opvi.py
1658 lines (1388 loc) · 59.5 KB
/
opvi.py
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
R"""
Variational inference is a great approach for doing really complex,
often intractable Bayesian inference in approximate form. Common methods
(e.g. ADVI) lack from complexity so that approximate posterior does not
reveal the true nature of underlying problem. In some applications it can
yield unreliable decisions.
Recently on NIPS 2017 `OPVI <https://arxiv.org/abs/1610.09033/>`_ framework
was presented. It generalizes variational inference so that the problem is
build with blocks. The first and essential block is Model itself. Second is
Approximation, in some cases :math:`log Q(D)` is not really needed. Necessity
depends on the third and fourth part of that black box, Operator and
Test Function respectively.
Operator is like an approach we use, it constructs loss from given Model,
Approximation and Test Function. The last one is not needed if we minimize
KL Divergence from Q to posterior. As a drawback we need to compute :math:`loq Q(D)`.
Sometimes approximation family is intractable and :math:`loq Q(D)` is not available,
here comes LS(Langevin Stein) Operator with a set of test functions.
Test Function has more unintuitive meaning. It is usually used with LS operator
and represents all we want from our approximate distribution. For any given vector
based function of :math:`z` LS operator yields zero mean function under posterior.
:math:`loq Q(D)` is no more needed. That opens a door to rich approximation
families as neural networks.
References
----------
- Rajesh Ranganath, Jaan Altosaar, Dustin Tran, David M. Blei
Operator Variational Inference
https://arxiv.org/abs/1610.09033 (2016)
"""
import collections
import itertools
import warnings
import numpy as np
import theano
import theano.tensor as tt
import pymc3 as pm
from pymc3.util import get_transformed
from .updates import adagrad_window
from ..blocking import (
ArrayOrdering, DictToArrayBijection, VarMap
)
from ..backends import NDArray, Text, SQLite, HDF5
from ..model import modelcontext
from ..theanof import tt_rng, change_flags, identity
from ..util import get_default_varnames
from ..memoize import WithMemoization, memoize
__all__ = [
'ObjectiveFunction',
'Operator',
'TestFunction',
'Group',
'Approximation'
]
class VariationalInferenceError(Exception):
"""Exception for VI specific cases"""
class ExplicitInferenceError(VariationalInferenceError, TypeError):
"""Exception for bad explicit inference"""
class AEVBInferenceError(VariationalInferenceError, TypeError):
"""Exception for bad aevb inference"""
class ParametrizationError(VariationalInferenceError, ValueError):
"""Error raised in case of bad parametrization"""
class GroupError(VariationalInferenceError, TypeError):
"""Error related to VI groups"""
class BatchedGroupError(GroupError):
"""Error with batched variables"""
class LocalGroupError(BatchedGroupError, AEVBInferenceError):
"""Error raised in case of bad local_rv usage"""
def append_name(name):
def wrap(f):
if name is None:
return f
def inner(*args, **kwargs):
res = f(*args, **kwargs)
res.name = name
return res
return inner
return wrap
def node_property(f):
"""A shortcut for wrapping method to accessible tensor
"""
if isinstance(f, str):
def wrapper(fn):
return property(memoize(change_flags(compute_test_value='off')(append_name(f)(fn)), bound=True))
return wrapper
else:
return property(memoize(change_flags(compute_test_value='off')(f), bound=True))
@change_flags(compute_test_value='ignore')
def try_to_set_test_value(node_in, node_out, s):
_s = s
if s is None:
s = 1
s = theano.compile.view_op(tt.as_tensor(s))
if not isinstance(node_in, (list, tuple)):
node_in = [node_in]
if not isinstance(node_out, (list, tuple)):
node_out = [node_out]
for i, o in zip(node_in, node_out):
if hasattr(i.tag, 'test_value'):
if not hasattr(s.tag, 'test_value'):
continue
else:
tv = i.tag.test_value[None, ...]
tv = np.repeat(tv, s.tag.test_value, 0)
if _s is None:
tv = tv[0]
o.tag.test_value = tv
class ObjectiveUpdates(theano.OrderedUpdates):
"""OrderedUpdates extension for storing loss
"""
loss = None
def _warn_not_used(smth, where):
warnings.warn('`%s` is not used for %s and ignored' % (smth, where))
class ObjectiveFunction:
"""Helper class for construction loss and updates for variational inference
Parameters
----------
op : :class:`Operator`
OPVI Functional operator
tf : :class:`TestFunction`
OPVI TestFunction
"""
def __init__(self, op, tf):
self.op = op
self.tf = tf
obj_params = property(lambda self: self.op.approx.params)
test_params = property(lambda self: self.tf.params)
approx = property(lambda self: self.op.approx)
def updates(self, obj_n_mc=None, tf_n_mc=None, obj_optimizer=adagrad_window, test_optimizer=adagrad_window,
more_obj_params=None, more_tf_params=None, more_updates=None,
more_replacements=None, total_grad_norm_constraint=None):
"""Calculate gradients for objective function, test function and then
constructs updates for optimization step
Parameters
----------
obj_n_mc : `int`
Number of monte carlo samples used for approximation of objective gradients
tf_n_mc : `int`
Number of monte carlo samples used for approximation of test function gradients
obj_optimizer : function (loss, params) -> updates
Optimizer that is used for objective params
test_optimizer : function (loss, params) -> updates
Optimizer that is used for test function params
more_obj_params : `list`
Add custom params for objective optimizer
more_tf_params : `list`
Add custom params for test function optimizer
more_updates : `dict`
Add custom updates to resulting updates
more_replacements : `dict`
Apply custom replacements before calculating gradients
total_grad_norm_constraint : `float`
Bounds gradient norm, prevents exploding gradient problem
Returns
-------
:class:`ObjectiveUpdates`
"""
if more_updates is None:
more_updates = dict()
resulting_updates = ObjectiveUpdates()
if self.test_params:
self.add_test_updates(
resulting_updates,
tf_n_mc=tf_n_mc,
test_optimizer=test_optimizer,
more_tf_params=more_tf_params,
more_replacements=more_replacements,
total_grad_norm_constraint=total_grad_norm_constraint
)
else:
if tf_n_mc is not None:
_warn_not_used('tf_n_mc', self.op)
if more_tf_params:
_warn_not_used('more_tf_params', self.op)
self.add_obj_updates(
resulting_updates,
obj_n_mc=obj_n_mc,
obj_optimizer=obj_optimizer,
more_obj_params=more_obj_params,
more_replacements=more_replacements,
total_grad_norm_constraint=total_grad_norm_constraint
)
resulting_updates.update(more_updates)
return resulting_updates
def add_test_updates(self, updates, tf_n_mc=None, test_optimizer=adagrad_window,
more_tf_params=None, more_replacements=None,
total_grad_norm_constraint=None):
if more_tf_params is None:
more_tf_params = []
if more_replacements is None:
more_replacements = dict()
tf_target = self(tf_n_mc, more_tf_params=more_tf_params, more_replacements=more_replacements)
grads = pm.updates.get_or_compute_grads(tf_target, self.obj_params + more_tf_params)
if total_grad_norm_constraint is not None:
grads = pm.total_norm_constraint(grads, total_grad_norm_constraint)
updates.update(
test_optimizer(
grads,
self.test_params +
more_tf_params))
def add_obj_updates(self, updates, obj_n_mc=None, obj_optimizer=adagrad_window,
more_obj_params=None, more_replacements=None,
total_grad_norm_constraint=None):
if more_obj_params is None:
more_obj_params = []
if more_replacements is None:
more_replacements = dict()
obj_target = self(obj_n_mc, more_obj_params=more_obj_params, more_replacements=more_replacements)
grads = pm.updates.get_or_compute_grads(obj_target, self.obj_params + more_obj_params)
if total_grad_norm_constraint is not None:
grads = pm.total_norm_constraint(grads, total_grad_norm_constraint)
updates.update(
obj_optimizer(
grads,
self.obj_params +
more_obj_params))
if self.op.returns_loss:
updates.loss = obj_target
@change_flags(compute_test_value='off')
def step_function(self, obj_n_mc=None, tf_n_mc=None,
obj_optimizer=adagrad_window, test_optimizer=adagrad_window,
more_obj_params=None, more_tf_params=None,
more_updates=None, more_replacements=None,
total_grad_norm_constraint=None,
score=False, fn_kwargs=None):
R"""Step function that should be called on each optimization step.
Generally it solves the following problem:
.. math::
\mathbf{\lambda^{\*}} = \inf_{\lambda} \sup_{\theta} t(\mathbb{E}_{\lambda}[(O^{p,q}f_{\theta})(z)])
Parameters
----------
obj_n_mc : `int`
Number of monte carlo samples used for approximation of objective gradients
tf_n_mc : `int`
Number of monte carlo samples used for approximation of test function gradients
obj_optimizer : function (grads, params) -> updates
Optimizer that is used for objective params
test_optimizer : function (grads, params) -> updates
Optimizer that is used for test function params
more_obj_params : `list`
Add custom params for objective optimizer
more_tf_params : `list`
Add custom params for test function optimizer
more_updates : `dict`
Add custom updates to resulting updates
total_grad_norm_constraint : `float`
Bounds gradient norm, prevents exploding gradient problem
score : `bool`
calculate loss on each step? Defaults to False for speed
fn_kwargs : `dict`
Add kwargs to theano.function (e.g. `{'profile': True}`)
more_replacements : `dict`
Apply custom replacements before calculating gradients
Returns
-------
`theano.function`
"""
if fn_kwargs is None:
fn_kwargs = {}
if score and not self.op.returns_loss:
raise NotImplementedError('%s does not have loss' % self.op)
updates = self.updates(obj_n_mc=obj_n_mc, tf_n_mc=tf_n_mc,
obj_optimizer=obj_optimizer,
test_optimizer=test_optimizer,
more_obj_params=more_obj_params,
more_tf_params=more_tf_params,
more_updates=more_updates,
more_replacements=more_replacements,
total_grad_norm_constraint=total_grad_norm_constraint)
if score:
step_fn = theano.function(
[], updates.loss, updates=updates, **fn_kwargs)
else:
step_fn = theano.function([], None, updates=updates, **fn_kwargs)
return step_fn
@change_flags(compute_test_value='off')
def score_function(self, sc_n_mc=None, more_replacements=None, fn_kwargs=None): # pragma: no cover
R"""Compile scoring function that operates which takes no inputs and returns Loss
Parameters
----------
sc_n_mc : `int`
number of scoring MC samples
more_replacements:
Apply custom replacements before compiling a function
fn_kwargs: `dict`
arbitrary kwargs passed to `theano.function`
Returns
-------
theano.function
"""
if fn_kwargs is None:
fn_kwargs = {}
if not self.op.returns_loss:
raise NotImplementedError('%s does not have loss' % self.op)
if more_replacements is None:
more_replacements = {}
loss = self(sc_n_mc, more_replacements=more_replacements)
return theano.function([], loss, **fn_kwargs)
@change_flags(compute_test_value='off')
def __call__(self, nmc, **kwargs):
if 'more_tf_params' in kwargs:
m = -1.
else:
m = 1.
a = self.op.apply(self.tf)
a = self.approx.set_size_and_deterministic(a, nmc, 0, kwargs.get('more_replacements'))
return m * self.op.T(a)
class Operator:
R"""**Base class for Operator**
Parameters
----------
approx : :class:`Approximation`
an approximation instance
Notes
-----
For implementing custom operator it is needed to define :func:`Operator.apply` method
"""
has_test_function = False
returns_loss = True
require_logq = True
objective_class = ObjectiveFunction
supports_aevb = property(lambda self: not self.approx.any_histograms)
T = identity
def __init__(self, approx):
self.approx = approx
if not self.supports_aevb and approx.has_local:
raise AEVBInferenceError('%s does not support AEVB, '
'please change inference method' % self)
if self.require_logq and not approx.has_logq:
raise ExplicitInferenceError('%s requires logq, but %s does not implement it'
'please change inference method' % (self, approx))
inputs = property(lambda self: self.approx.inputs)
logp = property(lambda self: self.approx.logp)
varlogp = property(lambda self: self.approx.varlogp)
datalogp = property(lambda self: self.approx.datalogp)
logq = property(lambda self: self.approx.logq)
logp_norm = property(lambda self: self.approx.logp_norm)
varlogp_norm = property(lambda self: self.approx.varlogp_norm)
datalogp_norm = property(lambda self: self.approx.datalogp_norm)
logq_norm = property(lambda self: self.approx.logq_norm)
model = property(lambda self: self.approx.model)
def apply(self, f): # pragma: no cover
R"""Operator itself
.. math::
(O^{p,q}f_{\theta})(z)
Parameters
----------
f : :class:`TestFunction` or None
function that takes `z = self.input` and returns
same dimensional output
Returns
-------
TensorVariable
symbolically applied operator
"""
raise NotImplementedError
def __call__(self, f=None):
if self.has_test_function:
if f is None:
raise ParametrizationError('Operator %s requires TestFunction' % self)
else:
if not isinstance(f, TestFunction):
f = TestFunction.from_function(f)
else:
if f is not None:
warnings.warn(
'TestFunction for %s is redundant and removed' %
self, stacklevel=3)
else:
pass
f = TestFunction()
f.setup(self.approx)
return self.objective_class(self, f)
def __str__(self): # pragma: no cover
return '%(op)s[%(ap)s]' % dict(op=self.__class__.__name__,
ap=self.approx.__class__.__name__)
def collect_shared_to_list(params):
"""Helper function for getting a list from
usable representation of parameters
Parameters
----------
params : {dict|None}
Returns
-------
List
"""
if isinstance(params, dict):
return list(
t[1] for t in sorted(params.items(), key=lambda t: t[0])
if isinstance(t[1], theano.compile.SharedVariable)
)
elif params is None:
return []
else:
raise TypeError(
'Unknown type %s for %r, need dict or None')
class TestFunction:
def __init__(self):
self._inited = False
self.shared_params = None
@property
def params(self):
return collect_shared_to_list(self.shared_params)
def __call__(self, z):
raise NotImplementedError
def setup(self, approx):
pass
@classmethod
def from_function(cls, f):
if not callable(f):
raise ParametrizationError('Need callable, got %r' % f)
obj = TestFunction()
obj.__call__ = f
return obj
class Group(WithMemoization):
R"""**Base class for grouping variables in VI**
Grouped Approximation is used for modelling mutual dependencies
for a specified group of variables. Base for local and global group.
Parameters
----------
group : list
List of PyMC3 variables or None indicating that group takes all the rest variables
vfam : str
String that marks the corresponding variational family for the group.
Cannot be passed both with `params`
params : dict
Dict with variational family parameters, full description can be found below.
Cannot be passed both with `vfam`
random_seed : int
Random seed for underlying random generator
model :
PyMC3 Model
local : bool
Indicates whether this group is local. Cannot be passed without `params`.
Such group should have only one variable
rowwise : bool
Indicates whether this group is independently parametrized over first dim.
Such group should have only one variable
options : dict
Special options for the group
kwargs : Other kwargs for the group
Notes
-----
Group instance/class has some important constants:
- **supports_batched**
Determines whether such variational family can be used for AEVB or rowwise approx.
AEVB approx is such approx that somehow depends on input data. It can be treated
as conditional distribution. You can see more about in the corresponding paper
mentioned in references.
Rowwise mode is a special case approximation that treats every 'row', of a tensor as
independent from each other. Some distributions can't do that by
definition e.g. :class:`Empirical` that consists of particles only.
- **has_logq**
Tells that distribution is defined explicitly
These constants help providing the correct inference method for given parametrization
Examples
--------
**Basic Initialization**
:class:`Group` is a factory class. You do not need to call every ApproximationGroup explicitly.
Passing the correct `vfam` (Variational FAMily) argument you'll tell what
parametrization is desired for the group. This helps not to overload code with lots of classes.
.. code:: python
>>> group = Group([latent1, latent2], vfam='mean_field')
The other way to select approximation is to provide `params` dictionary that has some
predefined well shaped parameters. Keys of the dict serve as an identifier for variational family and help
to autoselect the correct group class. To identify what approximation to use, params dict should
have the full set of needed parameters. As there are 2 ways to instantiate the :class:`Group`
passing both `vfam` and `params` is prohibited. Partial parametrization is prohibited by design to
avoid corner cases and possible problems.
.. code:: python
>>> group = Group([latent3], params=dict(mu=my_mu, rho=my_rho))
Important to note that in case you pass custom params they will not be autocollected by optimizer, you'll
have to provide them with `more_obj_params` keyword.
**Supported dict keys:**
- `{'mu', 'rho'}`: :class:`MeanFieldGroup`
- `{'mu', 'L_tril'}`: :class:`FullRankGroup`
- `{'histogram'}`: :class:`EmpiricalGroup`
- `{0, 1, 2, 3, ..., k-1}`: :class:`NormalizingFlowGroup` of depth `k`
NormalizingFlows have other parameters than ordinary groups and should be
passed as nested dicts with the following keys:
- `{'u', 'w', 'b'}`: :class:`PlanarFlow`
- `{'a', 'b', 'z_ref'}`: :class:`RadialFlow`
- `{'loc'}`: :class:`LocFlow`
- `{'rho'}`: :class:`ScaleFlow`
- `{'v'}`: :class:`HouseholderFlow`
Note that all integer keys should be present in the dictionary. An example
of NormalizingFlow initialization can be found below.
**Using AEVB**
Autoencoding variational Bayes is a powerful tool to get conditional :math:`q(\lambda|X)` distribution
on latent variables. It is well supported by PyMC3 and all you need is to provide a dictionary
with well shaped variational parameters, the correct approximation will be autoselected as mentioned
in section above. However we have some implementation restrictions in AEVB. They require autoencoded
variable to have first dimension as *batch* dimension and other dimensions should stay fixed.
With this assumptions it is possible to generalize all variational approximation families as
batched approximations that have flexible parameters and leading axis.
Only single variable local group is supported. Params are required.
>>> # for mean field
>>> group = Group([latent3], params=dict(mu=my_mu, rho=my_rho), local=True)
>>> # or for full rank
>>> group = Group([latent3], params=dict(mu=my_mu, L_tril=my_L_tril), local=True)
- An Approximation class is selected automatically based on the keys in dict.
- `my_mu` and `my_rho` are usually estimated with neural network or function approximator.
**Using Row-Wise Group**
Batch groups have independent row wise approximations, thus using batched
mean field will give no effect. It is more interesting if you want each row of a matrix
to be parametrized independently with normalizing flow or full rank gaussian.
To tell :class:`Group` that group is batched you need set `batched` kwarg as `True`.
Only single variable group is allowed due to implementation details.
>>> group = Group([latent3], vfam='fr', rowwise=True) # 'fr' is alias for 'full_rank'
The resulting approximation for this variable will have the following structure
.. math::
latent3_{i, \dots} \sim \mathcal{N}(\mu_i, \Sigma_i) \forall i
**Note**: Using rowwise and user-parametrized approximation is ok, but
shape should be checked beforehand, it is impossible to infer it by PyMC3
**Normalizing Flow Group**
In case you use simple initialization pattern using `vfam` you'll not meet any changes.
Passing flow formula to `vfam` you'll get correct flow parametrization for group
.. code:: python
>>> group = Group([latent3], vfam='scale-hh*5-radial*4-loc')
**Note**: Consider passing location flow as the last one and scale as the first one for stable inference.
Rowwise normalizing flow is supported as well
.. code:: python
>>> group = Group([latent3], vfam='scale-hh*2-radial-loc', rowwise=True)
Custom parameters for normalizing flow can be a real trouble for the first time.
They have quite different format from the rest variational families.
.. code:: python
>>> # int is used as key, it also tells the flow position
... flow_params = {
... # `rho` parametrizes scale flow, softplus is used to map (-inf; inf) -> (0, inf)
... 0: dict(rho=my_scale),
... 1: dict(v=my_v1), # Householder Flow, `v` is parameter name from the original paper
... 2: dict(v=my_v2), # do not miss any number in dict, or else error is raised
... 3: dict(a=my_a, b=my_b, z_ref=my_z_ref), # Radial flow
... 4: dict(loc=my_loc) # Location Flow
... }
... group = Group([latent3], params=flow_params)
... # local=True can be added in case you do AEVB inference
... group = Group([latent3], params=flow_params, local=True)
**Delayed Initialization**
When you have a lot of latent variables it is impractical to do it all manually.
To make life much simpler, You can pass `None` instead of list of variables. That case
you'll not create shared parameters until you pass all collected groups to
Approximation object that collects all the groups together and checks that every group is
correctly initialized. For those groups which have group equal to `None` it will collect all
the rest variables not covered by other groups and perform delayed init.
.. code:: python
>>> group_1 = Group([latent1], vfam='fr') # latent1 has full rank approximation
>>> group_other = Group(None, vfam='mf') # other variables have mean field Q
>>> approx = Approximation([group_1, group_other])
**Summing Up**
When you have created all the groups they need to pass all the groups to :class:`Approximation`.
It does not accept any other parameter rather than `groups`
.. code:: python
>>> approx = Approximation(my_groups)
See Also
--------
:class:`Approximation`
References
----------
- Kingma, D. P., & Welling, M. (2014).
`Auto-Encoding Variational Bayes. stat, 1050, 1. <https://arxiv.org/abs/1312.6114>`_
"""
# needs to be defined in init
shared_params = None
symbolic_initial = None
replacements = None
input = None
# defined by approximation
supports_batched = True
has_logq = True
# some important defaults
initial_dist_name = 'normal'
initial_dist_map = 0.
# for handy access using class methods
__param_spec__ = dict()
short_name = ''
alias_names = frozenset()
__param_registry = dict()
__name_registry = dict()
@classmethod
def register(cls, sbcls):
assert frozenset(sbcls.__param_spec__) not in cls.__param_registry, 'Duplicate __param_spec__'
cls.__param_registry[frozenset(sbcls.__param_spec__)] = sbcls
assert sbcls.short_name not in cls.__name_registry, 'Duplicate short_name'
cls.__name_registry[sbcls.short_name] = sbcls
for alias in sbcls.alias_names:
assert alias not in cls.__name_registry, 'Duplicate alias_name'
cls.__name_registry[alias] = sbcls
return sbcls
@classmethod
def group_for_params(cls, params):
if pm.variational.flows.seems_like_flow_params(params):
return pm.variational.approximations.NormalizingFlowGroup
if frozenset(params) not in cls.__param_registry:
raise KeyError('No such group for the following params: {!r}, '
'only the following are supported\n\n{}'
.format(params, cls.__param_registry))
return cls.__param_registry[frozenset(params)]
@classmethod
def group_for_short_name(cls, name):
if pm.variational.flows.seems_like_formula(name):
return pm.variational.approximations.NormalizingFlowGroup
if name.lower() not in cls.__name_registry:
raise KeyError('No such group: {!r}, '
'only the following are supported\n\n{}'
.format(name, cls.__name_registry))
return cls.__name_registry[name.lower()]
def __new__(cls, group=None, vfam=None, params=None, *args, **kwargs):
if cls is Group:
if vfam is not None and params is not None:
raise TypeError('Cannot call Group with both `vfam` and `params` provided')
elif vfam is not None:
return super().__new__(cls.group_for_short_name(vfam))
elif params is not None:
return super().__new__(cls.group_for_params(params))
else:
raise TypeError('Need to call Group with either `vfam` or `params` provided')
else:
return super().__new__(cls)
def __init__(self, group,
vfam=None,
params=None,
random_seed=None,
model=None,
local=False,
rowwise=False,
options=None,
**kwargs):
if local and not self.supports_batched:
raise LocalGroupError('%s does not support local groups' % self.__class__)
if local and rowwise:
raise LocalGroupError('%s does not support local grouping in rowwise mode')
if isinstance(vfam, str):
vfam = vfam.lower()
if options is None:
options = dict()
self.options = options
self._vfam = vfam
self._local = local
self._batched = rowwise
self._rng = tt_rng(random_seed)
model = modelcontext(model)
self.model = model
self.group = group
self.user_params = params
self._user_params = None
# save this stuff to use in __init_group__ later
self._kwargs = kwargs
if self.group is not None:
# init can be delayed
self.__init_group__(self.group)
@classmethod
def get_param_spec_for(cls, **kwargs):
res = dict()
for name, fshape in cls.__param_spec__.items():
res[name] = tuple(eval(s, kwargs) for s in fshape)
return res
def _check_user_params(self, **kwargs):
R"""*Dev* - checks user params, allocates them if they are correct, returns True.
If they are not present, returns False
Parameters
----------
kwargs : special kwargs needed sometimes
Returns
-------
bool indicating whether to allocate new shared params
"""
user_params = self.user_params
if user_params is None:
return False
if not isinstance(user_params, dict):
raise TypeError('params should be a dict')
givens = set(user_params.keys())
needed = set(self.__param_spec__)
if givens != needed:
raise ParametrizationError(
'Passed parameters do not have a needed set of keys, '
'they should be equal, got {givens}, needed {needed}'.format(
givens=givens, needed=needed))
self._user_params = dict()
spec = self.get_param_spec_for(d=self.ddim, **kwargs.pop('spec_kw', {}))
for name, param in self.user_params.items():
shape = spec[name]
if self.local:
shape = (-1, ) + shape
elif self.batched:
shape = (self.bdim, ) + shape
self._user_params[name] = tt.as_tensor(param).reshape(shape)
return True
def _initial_type(self, name):
R"""*Dev* - initial type with given name. The correct type depends on `self.batched`
Parameters
----------
name : str
name for tensor
Returns
-------
tensor
"""
if self.batched:
return tt.tensor3(name)
else:
return tt.matrix(name)
def _input_type(self, name):
R"""*Dev* - input type with given name. The correct type depends on `self.batched`
Parameters
----------
name : str
name for tensor
Returns
-------
tensor
"""
if self.batched:
return tt.matrix(name)
else:
return tt.vector(name)
@change_flags(compute_test_value='off')
def __init_group__(self, group):
if not group:
raise GroupError('Got empty group')
if self.group is None:
# delayed init
self.group = group
if self.batched and len(group) > 1:
if self.local: # better error message
raise LocalGroupError('Local groups with more than 1 variable are not supported')
else:
raise BatchedGroupError('Batched groups with more than 1 variable are not supported')
self.symbolic_initial = self._initial_type(
self.__class__.__name__ + '_symbolic_initial_tensor'
)
self.input = self._input_type(
self.__class__.__name__ + '_symbolic_input'
)
# I do some staff that is not supported by standard __init__
# so I have to to it by myself
self.ordering = ArrayOrdering([])
self.replacements = dict()
self.group = [get_transformed(var) for var in self.group]
for var in self.group:
if isinstance(var.distribution, pm.Discrete):
raise ParametrizationError('Discrete variables are not supported by VI: {}'
.format(var))
begin = self.ddim
if self.batched:
if var.ndim < 1:
if self.local:
raise LocalGroupError('Local variable should not be scalar')
else:
raise BatchedGroupError('Batched variable should not be scalar')
self.ordering.size += (np.prod(var.dshape[1:])).astype(int)
if self.local:
shape = (-1, ) + var.dshape[1:]
else:
shape = var.dshape
else:
self.ordering.size += var.dsize
shape = var.dshape
end = self.ordering.size
vmap = VarMap(var.name, slice(begin, end), shape, var.dtype)
self.ordering.vmap.append(vmap)
self.ordering.by_name[vmap.var] = vmap
vr = self.input[..., vmap.slc].reshape(shape).astype(vmap.dtyp)
vr.name = vmap.var + '_vi_replacement'
self.replacements[var] = vr
self.bij = DictToArrayBijection(self.ordering, {})
def _finalize_init(self):
"""*Dev* - clean up after init
"""
del self._kwargs
local = property(lambda self: self._local)
batched = property(lambda self: self._local or self._batched)
@property
def params_dict(self):
# prefixed are correctly reshaped
if self._user_params is not None:
return self._user_params
else:
return self.shared_params
@property
def params(self):
# raw user params possibly not reshaped
if self.user_params is not None:
return collect_shared_to_list(self.user_params)
else:
return collect_shared_to_list(self.shared_params)
def _new_initial_shape(self, size, dim, more_replacements=None):
"""*Dev* - correctly proceeds sampling with variable batch size
Parameters
----------
size : scalar
sample size
dim : scalar
latent fixed dim
more_replacements : dict
replacements for latent batch shape
Returns
-------
shape vector
"""
if self.batched:
bdim = tt.as_tensor(self.bdim)
bdim = theano.clone(bdim, more_replacements)
return tt.stack([size, bdim, dim])
else:
return tt.stack([size, dim])
@node_property
def bdim(self):
if not self.local:
if self.batched:
return self.ordering.vmap[0].shp[0]
else:
return 1
else:
return next(iter(self.params_dict.values())).shape[0]
@node_property
def ndim(self):
return self.ordering.size * self.bdim
@property
def ddim(self):
return self.ordering.size
def _new_initial(self, size, deterministic, more_replacements=None):
"""*Dev* - allocates new initial random generator
Parameters
----------
size : scalar
sample size