/
bijector.py
1735 lines (1442 loc) · 69.4 KB
/
bijector.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
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Bijector base."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import contextlib
# Dependency imports
import numpy as np
import six
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import assert_util
from tensorflow_probability.python.internal import cache_util
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import name_util
from tensorflow_probability.python.internal import nest_util
from tensorflow_probability.python.internal import prefer_static as ps
from tensorflow_probability.python.math import gradient
from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import
__all__ = [
'Bijector',
]
SKIP_DTYPE_CHECKS = False
# Singleton object representing "no value", in cases where "None" is meaningful.
UNSPECIFIED = object()
@six.add_metaclass(abc.ABCMeta)
class Bijector(tf.Module):
r"""Interface for transformations of a `Distribution` sample.
Bijectors can be used to represent any differentiable and injective
(one to one) function defined on an open subset of `R^n`. Some non-injective
transformations are also supported (see 'Non Injective Transforms' below).
#### Mathematical Details
A `Bijector` implements a [smooth covering map](
https://en.wikipedia.org/wiki/Local_diffeomorphism), i.e., a local
diffeomorphism such that every point in the target has a neighborhood evenly
covered by a map ([see also](
https://en.wikipedia.org/wiki/Covering_space#Covering_of_a_manifold)).
A `Bijector` is used by `TransformedDistribution` but can be generally used
for transforming a `Distribution` generated `Tensor`. A `Bijector` is
characterized by three operations:
1. Forward
Useful for turning one random outcome into another random outcome from a
different distribution.
2. Inverse
Useful for 'reversing' a transformation to compute one probability in
terms of another.
3. `log_det_jacobian(x)`
'The log of the absolute value of the determinant of the matrix of all
first-order partial derivatives of the inverse function.'
Useful for inverting a transformation to compute one probability in terms
of another. Geometrically, the Jacobian determinant is the volume of the
transformation and is used to scale the probability.
We take the absolute value of the determinant before log to avoid NaN
values. Geometrically, a negative determinant corresponds to an
orientation-reversing transformation. It is ok for us to discard the sign
of the determinant because we only integrate everywhere-nonnegative
functions (probability densities) and the correct orientation is always the
one that produces a nonnegative integrand.
By convention, transformations of random variables are named in terms of the
forward transformation. The forward transformation creates samples, the
inverse is useful for computing probabilities.
#### Example Uses
- Basic properties:
```python
x = ... # A tensor.
# Evaluate forward transformation.
fwd_x = my_bijector.forward(x)
x == my_bijector.inverse(fwd_x)
x != my_bijector.forward(fwd_x) # Not equal because x != g(g(x)).
```
- Computing a log-likelihood:
```python
def transformed_log_prob(bijector, log_prob, x):
return (bijector.inverse_log_det_jacobian(x, event_ndims=0) +
log_prob(bijector.inverse(x)))
```
- Transforming a random outcome:
```python
def transformed_sample(bijector, x):
return bijector.forward(x)
```
#### Example Bijectors
- 'Exponential'
```none
Y = g(X) = exp(X)
X ~ Normal(0, 1) # Univariate.
```
Implies:
```none
g^{-1}(Y) = log(Y)
|Jacobian(g^{-1})(y)| = 1 / y
Y ~ LogNormal(0, 1), i.e.,
prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
= (1 / y) Normal(log(y); 0, 1)
```
Here is an example of how one might implement the `Exp` bijector:
```python
class Exp(Bijector):
def __init__(self, validate_args=False, name='exp'):
super(Exp, self).__init__(
validate_args=validate_args,
forward_min_event_ndims=0,
name=name)
def _forward(self, x):
return tf.exp(x)
def _inverse(self, y):
return tf.log(y)
def _inverse_log_det_jacobian(self, y):
return -self._forward_log_det_jacobian(self._inverse(y))
def _forward_log_det_jacobian(self, x):
# Notice that we needn't do any reducing, even when`event_ndims > 0`.
# The base Bijector class will handle reducing for us; it knows how
# to do so because we called `super` `__init__` with
# `forward_min_event_ndims = 0`.
return x
```
- 'Affine'
```none
Y = g(X) = sqrtSigma * X + mu
X ~ MultivariateNormal(0, I_d)
```
Implies:
```none
g^{-1}(Y) = inv(sqrtSigma) * (Y - mu)
|Jacobian(g^{-1})(y)| = det(inv(sqrtSigma))
Y ~ MultivariateNormal(mu, sqrtSigma) , i.e.,
prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
= det(sqrtSigma)^(-d) *
MultivariateNormal(inv(sqrtSigma) * (y - mu); 0, I_d)
```
#### Min_event_ndims and Naming
Bijectors are named for the dimensionality of data they act on (i.e. without
broadcasting). We can think of bijectors having an intrinsic `min_event_ndims`
, which is the minimum number of dimensions for the bijector act on. For
instance, a Cholesky decomposition requires a matrix, and hence
`min_event_ndims=2`.
Some examples:
`AffineScalar: min_event_ndims=0`
`Affine: min_event_ndims=1`
`Cholesky: min_event_ndims=2`
`Exp: min_event_ndims=0`
`Sigmoid: min_event_ndims=0`
`SoftmaxCentered: min_event_ndims=1`
Note the difference between `Affine` and `AffineScalar`. `AffineScalar`
operates on scalar events, whereas `Affine` operates on vector-valued events.
More generally, there is a `forward_min_event_ndims` and an
`inverse_min_event_ndims`. In most cases, these will be the same.
However, for some shape changing bijectors, these will be different
(e.g. a bijector which pads an extra dimension at the end, might have
`forward_min_event_ndims=0` and `inverse_min_event_ndims=1`.
##### Additional Considerations for "Multi Tensor" Bijectors
Bijectors which operate on structures of `Tensor` require structured
`min_event_ndims` matching the structure of the inputs. In these cases,
`min_event_ndims` describes both the minimum dimensionality *and* the
structure of arguments to `forward` and `inverse`. For example:
```
Split([sizes], axis):
forward_min_event_ndims=-axis
inverse_min_event_ndims=[-axis] * len(sizes)
```
Note: By default, we require `shape(x[i])[-event_ndims:-min_event_ndims]` to
be identical for all elements `i` of the structured input `x`. Specifically,
broadcasting over non-minimal event-dims is not allowed for structured inputs.
In cases where broadcasting is used as a "computational shorthand" for a dense
operation (that is, the _broadcasted_ inputs are assumed to be independent),
users should set `bijector._allow_event_shape_broadcasting = True`.
Finally, some bijectors that operate on structures of inputs may not know
the minimum structured rank of their inputs without calltime shape information
(Composite bijectors, for example). In these cases, both `min_event_ndims`
properties will indicate the expected *structure* of inputs and outputs,
but the component values may be `None`.
#### Jacobian Determinant
The Jacobian determinant is a reduction over `event_ndims - min_event_ndims`
(`forward_min_event_ndims` for `forward_log_det_jacobian` and
`inverse_min_event_ndims` for `inverse_log_det_jacobian`).
To see this, consider the `Exp` `Bijector` applied to a `Tensor` which has
sample, batch, and event (S, B, E) shape semantics. Suppose the `Tensor`'s
partitioned-shape is `(S=[4], B=[2], E=[3, 3])`. The shape of the `Tensor`
returned by `forward` and `inverse` is unchanged, i.e., `[4, 2, 3, 3]`.
However the shape returned by `inverse_log_det_jacobian` is `[4, 2]` because
the Jacobian determinant is a reduction over the event dimensions.
Another example is the `Affine` `Bijector`. Because `min_event_ndims = 1`, the
Jacobian determinant reduction is over `event_ndims - 1`.
It is sometimes useful to implement the inverse Jacobian determinant as the
negative forward Jacobian determinant. For example,
```python
def _inverse_log_det_jacobian(self, y):
return -self._forward_log_det_jac(self._inverse(y)) # Note negation.
```
The correctness of this approach can be seen from the following claim.
- Claim:
Assume `Y = g(X)` is a bijection whose derivative exists and is nonzero
for its domain, i.e., `dY/dX = d/dX g(X) != 0`. Then:
```none
(log o det o jacobian o g^{-1})(Y) = -(log o det o jacobian o g)(X)
```
- Proof:
From the bijective, nonzero differentiability of `g`, the
[inverse function theorem](
https://en.wikipedia.org/wiki/Inverse_function_theorem)
implies `g^{-1}` is differentiable in the image of `g`.
Applying the chain rule to `y = g(x) = g(g^{-1}(y))` yields
`I = g'(g^{-1}(y))*g^{-1}'(y)`.
The same theorem also implies `g^{-1}'` is non-singular therefore:
`inv[ g'(g^{-1}(y)) ] = g^{-1}'(y)`.
The claim follows from [properties of determinant](
https://en.wikipedia.org/wiki/Determinant#Multiplicativity_and_matrix_groups).
Generally its preferable to directly implement the inverse Jacobian
determinant. This should have superior numerical stability and will often
share subgraphs with the `_inverse` implementation.
#### Is_constant_jacobian
Certain bijectors will have constant jacobian matrices. For instance, the
`Affine` bijector encodes multiplication by a matrix plus a shift, with
jacobian matrix, the same aforementioned matrix.
`is_constant_jacobian` encodes the fact that the jacobian matrix is constant.
The semantics of this argument are the following:
* Repeated calls to 'log_det_jacobian' functions with the same
`event_ndims` (but not necessarily same input), will return the first
computed jacobian (because the matrix is constant, and hence is input
independent).
* `log_det_jacobian` implementations are merely broadcastable to the true
`log_det_jacobian` (because, again, the jacobian matrix is input
independent). Specifically, `log_det_jacobian` is implemented as the
log jacobian determinant for a single input.
```python
class Identity(Bijector):
def __init__(self, validate_args=False, name='identity'):
super(Identity, self).__init__(
is_constant_jacobian=True,
validate_args=validate_args,
forward_min_event_ndims=0,
name=name)
def _forward(self, x):
return x
def _inverse(self, y):
return y
def _inverse_log_det_jacobian(self, y):
return -self._forward_log_det_jacobian(self._inverse(y))
def _forward_log_det_jacobian(self, x):
# The full log jacobian determinant would be tf.zero_like(x).
# However, we circumvent materializing that, since the jacobian
# calculation is input independent, and we specify it for one input.
return tf.constant(0., x.dtype)
```
#### Subclass Requirements
- Subclasses typically implement:
- `_forward`,
- `_inverse`,
- `_inverse_log_det_jacobian`,
- `_forward_log_det_jacobian` (optional),
- `_is_increasing` (scalar bijectors only)
The `_forward_log_det_jacobian` is called when the bijector is inverted via
the `Invert` bijector. If undefined, a slightly less efficiently
calculation, `-1 * _inverse_log_det_jacobian`, is used.
If the bijector changes the shape of the input, you must also implement:
- _forward_event_shape_tensor,
- _forward_event_shape (optional),
- _inverse_event_shape_tensor,
- _inverse_event_shape (optional).
By default the event-shape is assumed unchanged from input.
Multipart bijectors, which operate on structures of tensors, may implement
additional methods to propogate calltime dtype information over any changes
to structure. These methods are:
- _forward_dtype
- _inverse_dtype
- If the `Bijector`'s use is limited to `TransformedDistribution` (or friends
like `QuantizedDistribution`) then depending on your use, you may not need
to implement all of `_forward` and `_inverse` functions.
Examples:
1. Sampling (e.g., `sample`) only requires `_forward`.
2. Probability functions (e.g., `prob`, `cdf`, `survival`) only require
`_inverse` (and related).
3. Only calling probability functions on the output of `sample` means
`_inverse` can be implemented as a cache lookup.
See 'Example Uses' [above] which shows how these functions are used to
transform a distribution. (Note: `_forward` could theoretically be
implemented as a cache lookup but this would require controlling the
underlying sample generation mechanism.)
#### Non Injective Transforms
**WARNING** Handling of non-injective transforms is subject to change.
Non injective maps `g` are supported, provided their domain `D` can be
partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that,
ignoring sets of measure zero, the restriction of `g` to each subset is a
differentiable bijection onto `g(D)`. In particular, this implies that for
`y in g(D)`, the set inverse, i.e. `g^{-1}(y) = {x in D : g(x) = y}`, always
contains exactly `k` distinct points.
The property, `_is_injective` is set to `False` to indicate that the bijector
is not injective, yet satisfies the above condition.
The usual bijector API is modified in the case `_is_injective is False` (see
method docstrings for specifics). Here we show by example the `AbsoluteValue`
bijector. In this case, the domain `D = (-inf, inf)`, can be partitioned
into `D1 = (-inf, 0)`, `D2 = {0}`, and `D3 = (0, inf)`. Let `gi` be the
restriction of `g` to `Di`, then both `g1` and `g3` are bijections onto
`(0, inf)`, with `g1^{-1}(y) = -y`, and `g3^{-1}(y) = y`. We will use
`g1` and `g3` to define bijector methods over `D1` and `D3`. `D2 = {0}` is
an oddball in that `g2` is one to one, and the derivative is not well defined.
Fortunately, when considering transformations of probability densities
(e.g. in `TransformedDistribution`), sets of measure zero have no effect in
theory, and only a small effect in 32 or 64 bit precision. For that reason,
we define `inverse(0)` and `inverse_log_det_jacobian(0)` both as `[0, 0]`,
which is convenient and results in a left-semicontinuous pdf.
```python
abs = tfp.bijectors.AbsoluteValue()
abs.forward(-1.)
==> 1.
abs.forward(1.)
==> 1.
abs.inverse(1.)
==> (-1., 1.)
# The |dX/dY| is constant, == 1. So Log|dX/dY| == 0.
abs.inverse_log_det_jacobian(1., event_ndims=0)
==> (0., 0.)
# Special case handling of 0.
abs.inverse(0.)
==> (0., 0.)
abs.inverse_log_det_jacobian(0., event_ndims=0)
==> (0., 0.)
```
"""
_TF_MODULE_IGNORED_PROPERTIES = tf.Module._TF_MODULE_IGNORED_PROPERTIES.union(
(
'_graph_parents',
'_is_constant_jacobian',
'_cache',
'_forward_min_event_ndims',
'_inverse_min_event_ndims',
))
_cache = cache_util.BijectorCache()
@abc.abstractmethod
def __init__(self,
graph_parents=None,
is_constant_jacobian=False,
validate_args=False,
dtype=None,
forward_min_event_ndims=UNSPECIFIED,
inverse_min_event_ndims=UNSPECIFIED,
parameters=None,
name=None):
"""Constructs Bijector.
A `Bijector` transforms random variables into new random variables.
Examples:
```python
# Create the Y = g(X) = X transform.
identity = Identity()
# Create the Y = g(X) = exp(X) transform.
exp = Exp()
```
See `Bijector` subclass docstring for more details and specific examples.
Args:
graph_parents: Python list of graph prerequisites of this `Bijector`.
is_constant_jacobian: Python `bool` indicating that the Jacobian matrix is
not a function of the input.
validate_args: Python `bool`, default `False`. Whether to validate input
with asserts. If `validate_args` is `False`, and the inputs are invalid,
correct behavior is not guaranteed.
dtype: `tf.dtype` supported by this `Bijector`. `None` means dtype is not
enforced. For multipart bijectors, this value is expected to be the
same for all elements of the input and output structures.
forward_min_event_ndims: Python `integer` (structure) indicating the
minimum number of dimensions on which `forward` operates.
inverse_min_event_ndims: Python `integer` (structure) indicating the
minimum number of dimensions on which `inverse` operates. Will be set to
`forward_min_event_ndims` by default, if no value is provided.
parameters: Python `dict` of parameters used to instantiate this
`Bijector`. Bijector instances with identical types, names, and
`parameters` share an input/output cache. `parameters` dicts are
keyed by strings and are identical if their keys are identical and if
corresponding values have identical hashes (or object ids, for
unhashable objects).
name: The name to give Ops created by the initializer.
Raises:
ValueError: If neither `forward_min_event_ndims` and
`inverse_min_event_ndims` are specified, or if either of them is
negative.
ValueError: If a member of `graph_parents` is not a `Tensor`.
"""
if not name:
name = type(self).__name__
name = name_util.camel_to_lower_snake(name)
name = name_util.get_name_scope_name(name)
name = name_util.strip_invalid_chars(name)
super(Bijector, self).__init__(name=name)
self._name = name
# TODO(b/176242804): Infer `parameters` if not specified by the child class.
self._parameters = self._no_dependency(parameters)
self._graph_parents = self._no_dependency(graph_parents or [])
self._is_constant_jacobian = is_constant_jacobian
self._validate_args = validate_args
self._dtype = dtype
self._initial_parameter_control_dependencies = tuple(
d for d in self._parameter_control_dependencies(is_init=True)
if d is not None)
if self._initial_parameter_control_dependencies:
self._initial_parameter_control_dependencies = (
tf.group(*self._initial_parameter_control_dependencies),)
# Validate min_event_ndims, if all values are known.
# Note that bijectors without known min_event_ndims (eg, Composite)
# must override `_call_{ldj_func}` instead of `_{ldj_func}`.
if (forward_min_event_ndims is UNSPECIFIED
and inverse_min_event_ndims is UNSPECIFIED):
raise ValueError('Must specify at least one of `forward_min_event_ndims` '
'and `inverse_min_event_ndims`.')
elif forward_min_event_ndims is UNSPECIFIED:
forward_min_event_ndims = inverse_min_event_ndims
elif inverse_min_event_ndims is UNSPECIFIED:
inverse_min_event_ndims = forward_min_event_ndims
# Prevent tf.Module from wrapping structured min_event_ndims in proxies.
# We use (forward|inverse)_min_event_ndims to specify input/output
# structures, so it is important that we retain the original containers.
self._forward_min_event_ndims = self._no_dependency(forward_min_event_ndims)
self._inverse_min_event_ndims = self._no_dependency(inverse_min_event_ndims)
self._has_static_min_event_ndims = None not in (
nest.flatten([forward_min_event_ndims, inverse_min_event_ndims]))
# Whether to allow broadcasting over the (non-minimal) event-shape for
# structured inputs. When `False` (default), assert that LDJ reduction
# shapes are identical for all components of nested inputs. When `True`,
# event-shape broadcasing is allow, but LDJ may be incorrect.
self._allow_event_shape_broadcasting = False
# Batch shape implied by the bijector's parameters, for use in validating
# LDJ shapes (currently only used in multipart bijectors.)
self._parameter_batch_shape = None
for i, t in enumerate(self._graph_parents):
if t is None or not tf.is_tensor(t):
raise ValueError('Graph parent item %d is not a Tensor; %s.' % (i, t))
@property
def graph_parents(self):
"""Returns this `Bijector`'s graph_parents as a Python list."""
return self._graph_parents
@property
def forward_min_event_ndims(self):
"""Returns the minimal number of dimensions bijector.forward operates on.
Multipart bijectors return structured `ndims`, which indicates the
expected structure of their inputs. Some multipart bijectors, notably
Composites, may return structures of `None`.
"""
return self._forward_min_event_ndims
@property
def inverse_min_event_ndims(self):
"""Returns the minimal number of dimensions bijector.inverse operates on.
Multipart bijectors return structured `event_ndims`, which indicates the
expected structure of their outputs. Some multipart bijectors, notably
Composites, may return structures of `None`.
"""
return self._inverse_min_event_ndims
@property
def has_static_min_event_ndims(self):
"""Returns True if the bijector has statically-known `min_event_ndims`."""
return self._has_static_min_event_ndims
@property
def is_constant_jacobian(self):
"""Returns true iff the Jacobian matrix is not a function of x.
Note: Jacobian matrix is either constant for both forward and inverse or
neither.
Returns:
is_constant_jacobian: Python `bool`.
"""
return self._is_constant_jacobian
@property
def _is_injective(self):
"""Returns true iff the forward map `g` is injective (one-to-one function).
**WARNING** This hidden property and its behavior are subject to change.
Note: Non-injective maps `g` are supported, provided their domain `D` can
be partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that,
ignoring sets of measure zero, the restriction of `g` to each subset is a
differentiable bijection onto `g(D)`.
Returns:
is_injective: Python `bool`.
"""
return True
@property
def _is_scalar(self):
return (tf.get_static_value(self._forward_min_event_ndims) == 0 and
tf.get_static_value(self._inverse_min_event_ndims) == 0)
@property
def _is_permutation(self):
"""Whether `y` is purely a reordering / restructuring of `x`."""
return False
@property
def validate_args(self):
"""Returns True if Tensor arguments will be validated."""
return self._validate_args
@property
def dtype(self):
return self._dtype
@property
def name(self):
"""Returns the string name of this `Bijector`."""
return self._name
@property
def parameters(self):
"""Dictionary of parameters used to instantiate this `Bijector`."""
# Remove "self", "__class__", or other special variables. These can appear
# if the subclass used:
# `parameters = dict(locals())`.
if self._parameters is None:
return None
return {k: v for k, v in self._parameters.items()
if not k.startswith('__') and k != 'self'}
def __hash__(self):
return hash(cache_util.hashable_structure((
type(self), self._get_parameterization())))
def __eq__(self, other):
if type(self) is not type(other):
return False
try:
tf.nest.assert_same_structure(self._get_parameterization(),
other._get_parameterization())
except (ValueError, TypeError):
return False
self_params = tf.nest.flatten(self._get_parameterization())
other_params = tf.nest.flatten(other._get_parameterization())
for (p1, p2) in zip(self_params, other_params):
if p1 is p2:
continue
if tf.is_tensor(p1):
p1 = tf.get_static_value(p1)
if tf.is_tensor(p2):
p2 = tf.get_static_value(p2)
p1_isarray = getattr(p1, '__array__', None) is not None
p2_isarray = getattr(p2, '__array__', None) is not None
if p1_isarray != p2_isarray:
return False
if p1_isarray and p2_isarray:
if p1.shape != p2.shape:
return False
if not np.all(np.equal(p1, p2)):
return False
if p1 != p2:
return False
return True
def _get_parameterization(self):
if self.parameters is None:
# If a user-written bijector doesn't specify `parameters`, we must assume
# that all instances are unique.
# TODO(b/176242804): this can be removed if we always infer `parameters`.
return id(self)
return self.parameters
def __call__(self, value, name=None, **kwargs):
"""Applies or composes the `Bijector`, depending on input type.
This is a convenience function which applies the `Bijector` instance in
three different ways, depending on the input:
1. If the input is a `tfd.Distribution` instance, return
`tfd.TransformedDistribution(distribution=input, bijector=self)`.
2. If the input is a `tfb.Bijector` instance, return
`tfb.Chain([self, input])`.
3. Otherwise, return `self.forward(input)`
Args:
value: A `tfd.Distribution`, `tfb.Bijector`, or a (structure of) `Tensor`.
name: Python `str` name given to ops created by this function.
**kwargs: Additional keyword arguments passed into the created
`tfd.TransformedDistribution`, `tfb.Bijector`, or `self.forward`.
Returns:
composition: A `tfd.TransformedDistribution` if the input was a
`tfd.Distribution`, a `tfb.Chain` if the input was a `tfb.Bijector`, or
a (structure of) `Tensor` computed by `self.forward`.
#### Examples
```python
sigmoid = tfb.Reciprocal()(
tfb.Shift(shift=1.)(
tfb.Exp()(
tfb.Scale(scale=-1.))))
# ==> `tfb.Chain([
# tfb.Reciprocal(),
# tfb.Shift(shift=1.),
# tfb.Exp(),
# tfb.Scale(scale=-1.),
# ])` # ie, `tfb.Sigmoid()`
log_normal = tfb.Exp()(tfd.Normal(0, 1))
# ==> `tfd.TransformedDistribution(tfd.Normal(0, 1), tfb.Exp())`
tfb.Exp()([-1., 0., 1.])
# ==> tf.exp([-1., 0., 1.])
```
"""
# To avoid circular dependencies and keep the implementation local to the
# `Bijector` class, we violate PEP8 guidelines and import here rather than
# at the top of the file.
from tensorflow_probability.python.bijectors import chain # pylint: disable=g-import-not-at-top
from tensorflow_probability.python.distributions import distribution # pylint: disable=g-import-not-at-top
from tensorflow_probability.python.distributions import transformed_distribution # pylint: disable=g-import-not-at-top
# TODO(b/128841942): Handle Conditional distributions and bijectors.
if type(value) is transformed_distribution.TransformedDistribution: # pylint: disable=unidiomatic-typecheck
# We cannot accept subclasses with different constructors here, because
# subclass constructors may accept constructor arguments TD doesn't know
# how to handle. e.g. `TypeError: __init__() got an unexpected keyword
# argument 'allow_nan_stats'` when doing
# `tfb.Identity()(tfd.Chi(df=1., allow_nan_stats=True))`.
new_kwargs = value.parameters
new_kwargs.update(kwargs)
new_kwargs['name'] = name or new_kwargs.get('name', None)
new_kwargs['bijector'] = self(value.bijector)
return transformed_distribution.TransformedDistribution(**new_kwargs)
if isinstance(value, distribution.Distribution):
return transformed_distribution.TransformedDistribution(
distribution=value,
bijector=self,
name=name,
**kwargs)
if isinstance(value, chain.Chain):
new_kwargs = kwargs.copy()
new_kwargs['bijectors'] = [self] + ([] if value.bijectors is None
else list(value.bijectors))
if 'validate_args' not in new_kwargs:
new_kwargs['validate_args'] = value.validate_args
new_kwargs['name'] = name or value.name
return chain.Chain(**new_kwargs)
if isinstance(value, Bijector):
return chain.Chain([self, value], name=name, **kwargs)
return self.forward(value, name=name or 'forward', **kwargs)
def _forward_event_shape_tensor(self, input_shape):
"""Subclass implementation for `forward_event_shape_tensor` function."""
# By default, we assume event_shape is unchanged.
return input_shape
def forward_event_shape_tensor(self,
input_shape,
name='forward_event_shape_tensor'):
"""Shape of a single sample from a single batch as an `int32` 1D `Tensor`.
Args:
input_shape: `Tensor`, `int32` vector (structure) indicating event-portion
shape passed into `forward` function.
name: name to give to the op
Returns:
forward_event_shape_tensor: `Tensor`, `int32` vector (structure)
indicating event-portion shape after applying `forward`.
"""
with self._name_and_control_scope(name):
# Use statically-known structure from min_event_ndims.
input_shape_dtype = nest_util.broadcast_structure(
self.forward_min_event_ndims, tf.int32)
input_shape = nest_util.convert_to_nested_tensor(
input_shape, dtype_hint=input_shape_dtype,
name='input_event_shape', allow_packing=True)
# Wrap inputs in identity to make sure control_scope is respected.
input_shape = nest.map_structure(tf.identity, input_shape)
# Refer to static-dtype to get structure; we don't care about ntype here.
output_shape_dtype = nest_util.broadcast_structure(
self.inverse_min_event_ndims, tf.int32)
return nest_util.convert_to_nested_tensor(
self._forward_event_shape_tensor(input_shape),
dtype_hint=output_shape_dtype,
name='output_event_shape', allow_packing=True)
def _forward_event_shape(self, input_shape):
"""Subclass implementation for `forward_event_shape` public function."""
# By default, we assume event_shape is unchanged.
return input_shape
def forward_event_shape(self, input_shape):
"""Shape of a single sample from a single batch as a `TensorShape`.
Same meaning as `forward_event_shape_tensor`. May be only partially defined.
Args:
input_shape: `TensorShape` (structure) indicating event-portion shape
passed into `forward` function.
Returns:
forward_event_shape_tensor: `TensorShape` (structure) indicating
event-portion shape after applying `forward`. Possibly unknown.
"""
# Use statically-known dtype attribute to infer structure.
input_shape = nest.map_structure_up_to(
self.forward_min_event_ndims, tf.TensorShape,
nest_util.coerce_structure(self.forward_min_event_ndims, input_shape),
check_types=False)
return nest.map_structure_up_to(
self.inverse_min_event_ndims, tf.TensorShape,
self._forward_event_shape(input_shape))
def _inverse_event_shape_tensor(self, output_shape):
"""Subclass implementation for `inverse_event_shape_tensor` function."""
# By default, we assume event_shape is unchanged.
return output_shape
def inverse_event_shape_tensor(self,
output_shape,
name='inverse_event_shape_tensor'):
"""Shape of a single sample from a single batch as an `int32` 1D `Tensor`.
Args:
output_shape: `Tensor`, `int32` vector (structure) indicating
event-portion shape passed into `inverse` function.
name: name to give to the op
Returns:
inverse_event_shape_tensor: `Tensor`, `int32` vector (structure)
indicating event-portion shape after applying `inverse`.
"""
with self._name_and_control_scope(name):
output_shape = nest_util.convert_to_nested_tensor(
output_shape, name='output_event_shape',
dtype_hint=nest_util.broadcast_structure(
self.inverse_min_event_ndims, tf.int32),
allow_packing=True)
# Wrap inputs in identity to make sure control_scope is respected.
output_shape = nest.map_structure(tf.identity, output_shape)
return nest_util.convert_to_nested_tensor(
self._inverse_event_shape_tensor(output_shape),
name='input_event_shape',
dtype_hint=nest_util.broadcast_structure(
self.forward_min_event_ndims, tf.int32),
allow_packing=True)
def _inverse_event_shape(self, output_shape):
"""Subclass implementation for `inverse_event_shape` public function."""
# By default, we assume event_shape is unchanged.
return output_shape
def inverse_event_shape(self, output_shape):
"""Shape of a single sample from a single batch as a `TensorShape`.
Same meaning as `inverse_event_shape_tensor`. May be only partially defined.
Args:
output_shape: `TensorShape` (structure) indicating event-portion shape
passed into `inverse` function.
Returns:
inverse_event_shape_tensor: `TensorShape` (structure) indicating
event-portion shape after applying `inverse`. Possibly unknown.
"""
# Use statically-known dtype attribute to infer structure.
output_shape = nest.map_structure_up_to(
self.inverse_min_event_ndims, tf.TensorShape,
nest_util.coerce_structure(self.inverse_min_event_ndims, output_shape),
check_types=False)
return nest.map_structure_up_to(
self.forward_min_event_ndims, tf.TensorShape,
self._inverse_event_shape(output_shape))
def _forward(self, x):
"""Subclass implementation for `forward` public function."""
raise NotImplementedError('forward not implemented.')
def _call_forward(self, x, name, **kwargs):
"""Wraps call to _forward, allowing extra shared logic."""
with self._name_and_control_scope(name):
dtype = self.inverse_dtype(**kwargs)
x = nest_util.convert_to_nested_tensor(
x, name='x', dtype_hint=dtype,
dtype=None if SKIP_DTYPE_CHECKS else dtype,
allow_packing=True)
if not self._is_injective: # No caching for non-injective
return self._forward(x, **kwargs)
return self._cache.forward(x, **kwargs)
def forward(self, x, name='forward', **kwargs):
"""Returns the forward `Bijector` evaluation, i.e., X = g(Y).
Args:
x: `Tensor` (structure). The input to the 'forward' evaluation.
name: The name to give this op.
**kwargs: Named arguments forwarded to subclass implementation.
Returns:
`Tensor` (structure).
Raises:
TypeError: if `self.dtype` is specified and `x.dtype` is not
`self.dtype`.
NotImplementedError: if `_forward` is not implemented.
"""
return self._call_forward(x, name, **kwargs)
@classmethod
def _is_increasing(cls, **kwargs):
"""Subclass implementation for `is_increasing` public function."""
raise NotImplementedError('`_is_increasing` not implemented.')
def _call_is_increasing(self, name, **kwargs):
"""Wraps call to _is_increasing, allowing extra shared logic."""
with self._name_and_control_scope(name):
return tf.identity(self._is_increasing(**kwargs))
def _internal_is_increasing(self, name='is_increasing', **kwargs):
"""For scalar bijectors, returns True where `d forward(x) / d x > 0`.
This method, like `_is_injective`, is part of a contract with
`TransformedDistribution`. This method supports the correctness of scalar
`quantile` / `cdf` / `survival_function` for transformed distributions.
Args:
name: The name to give this op.
**kwargs: Named arguments forwarded to subclass implementation.
Returns:
A python `bool` or a `tf.bool` `Tensor`.
"""
return self._call_is_increasing(name, **kwargs)
def _inverse(self, y):
"""Subclass implementation for `inverse` public function."""
raise NotImplementedError('inverse not implemented')
def _call_inverse(self, y, name, **kwargs):
"""Wraps call to _inverse, allowing extra shared logic."""
with self._name_and_control_scope(name):
dtype = self.forward_dtype(**kwargs)
y = nest_util.convert_to_nested_tensor(
y, name='y', dtype_hint=dtype,
dtype=None if SKIP_DTYPE_CHECKS else dtype,
allow_packing=True)
if not self._is_injective: # No caching for non-injective
return self._inverse(y, **kwargs)
return self._cache.inverse(y, **kwargs)
def inverse(self, y, name='inverse', **kwargs):
"""Returns the inverse `Bijector` evaluation, i.e., X = g^{-1}(Y).
Args:
y: `Tensor` (structure). The input to the 'inverse' evaluation.
name: The name to give this op.
**kwargs: Named arguments forwarded to subclass implementation.
Returns: