test_kl_static.py 7.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

import unittest

17 18
import config
import mock_data as mock
19
import numpy as np
20
import parameterize as param
21 22 23
import scipy.special
import scipy.stats

24 25
import paddle
from paddle.distribution import kl
26

27 28
np.random.seed(2022)
paddle.seed(2022)
29 30 31
paddle.enable_static()


32
@param.place(config.DEVICES)
33 34 35 36 37 38 39 40 41 42 43 44
@param.param_cls(
    (param.TEST_CASE_NAME, 'a1', 'b1', 'a2', 'b2'),
    [
        (
            'test_regular_input',
            6.0 * np.random.random((4, 5)) + 1e-4,
            6.0 * np.random.random((4, 5)) + 1e-4,
            6.0 * np.random.random((4, 5)) + 1e-4,
            6.0 * np.random.random((4, 5)) + 1e-4,
        ),
    ],
)
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
class TestKLBetaBeta(unittest.TestCase):
    def setUp(self):
        self.mp = paddle.static.Program()
        self.sp = paddle.static.Program()
        self.executor = paddle.static.Executor(self.place)

        with paddle.static.program_guard(self.mp, self.sp):
            a1 = paddle.static.data('a1', self.a1.shape, dtype=self.a1.dtype)
            b1 = paddle.static.data('b1', self.b1.shape, dtype=self.b1.dtype)
            a2 = paddle.static.data('a2', self.a2.shape, dtype=self.a2.dtype)
            b2 = paddle.static.data('b2', self.b2.shape, dtype=self.b2.dtype)

            self.p = paddle.distribution.Beta(a1, b1)
            self.q = paddle.distribution.Beta(a2, b2)
            self.feeds = {
                'a1': self.a1,
                'b1': self.b1,
                'a2': self.a2,
63
                'b2': self.b2,
64 65 66 67 68 69
            }

    def test_kl_divergence(self):
        with paddle.static.program_guard(self.mp, self.sp):
            out = paddle.distribution.kl_divergence(self.p, self.q)
            self.executor.run(self.sp)
70 71 72
            [out] = self.executor.run(
                self.mp, feed=self.feeds, fetch_list=[out]
            )
73

74 75 76 77 78 79
            np.testing.assert_allclose(
                out,
                self.scipy_kl_beta_beta(self.a1, self.b1, self.a2, self.b2),
                rtol=config.RTOL.get(str(self.a1.dtype)),
                atol=config.ATOL.get(str(self.a1.dtype)),
            )
80 81

    def scipy_kl_beta_beta(self, a1, b1, a2, b2):
82 83 84 85 86 87 88
        return (
            scipy.special.betaln(a2, b2)
            - scipy.special.betaln(a1, b1)
            + (a1 - a2) * scipy.special.digamma(a1)
            + (b1 - b2) * scipy.special.digamma(b1)
            + (a2 - a1 + b2 - b1) * scipy.special.digamma(a1 + b1)
        )
89 90


91
@param.place(config.DEVICES)
92 93 94 95 96 97 98 99 100 101
@param.param_cls(
    (param.TEST_CASE_NAME, 'conc1', 'conc2'),
    [
        (
            'test-regular-input',
            np.random.random((5, 7, 8, 10)),
            np.random.random((5, 7, 8, 10)),
        ),
    ],
)
102 103 104 105 106 107
class TestKLDirichletDirichlet(unittest.TestCase):
    def setUp(self):
        self.mp = paddle.static.Program()
        self.sp = paddle.static.Program()
        self.executor = paddle.static.Executor(self.place)
        with paddle.static.program_guard(self.mp, self.sp):
108 109 110 111 112 113
            conc1 = paddle.static.data(
                'conc1', self.conc1.shape, self.conc1.dtype
            )
            conc2 = paddle.static.data(
                'conc2', self.conc2.shape, self.conc2.dtype
            )
114 115 116 117 118 119 120 121 122
            self.p = paddle.distribution.Dirichlet(conc1)
            self.q = paddle.distribution.Dirichlet(conc2)
            self.feeds = {'conc1': self.conc1, 'conc2': self.conc2}

    def test_kl_divergence(self):

        with paddle.static.program_guard(self.mp, self.sp):
            out = paddle.distribution.kl_divergence(self.p, self.q)
            self.executor.run(self.sp)
123 124 125
            [out] = self.executor.run(
                self.mp, feed=self.feeds, fetch_list=[out]
            )
126 127 128 129
            np.testing.assert_allclose(
                out,
                self.scipy_kl_diric_diric(self.conc1, self.conc2),
                rtol=config.RTOL.get(str(self.conc1.dtype)),
130 131
                atol=config.ATOL.get(str(self.conc1.dtype)),
            )
132 133 134

    def scipy_kl_diric_diric(self, conc1, conc2):
        return (
135 136 137 138 139
            scipy.special.gammaln(np.sum(conc1, -1))
            - scipy.special.gammaln(np.sum(conc2, -1))
            - np.sum(
                scipy.special.gammaln(conc1) - scipy.special.gammaln(conc2), -1
            )
140
            + np.sum(
141 142 143 144 145 146 147 148
                (conc1 - conc2)
                * (
                    scipy.special.digamma(conc1)
                    - scipy.special.digamma(np.sum(conc1, -1, keepdims=True))
                ),
                -1,
            )
        )
149 150 151 152 153 154


class DummyDistribution(paddle.distribution.Distribution):
    pass


155
@param.place(config.DEVICES)
156 157 158
@param.param_cls(
    (param.TEST_CASE_NAME, 'p', 'q'), [('test-dispatch-exception')]
)
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
class TestDispatch(unittest.TestCase):
    def setUp(self):
        self.mp = paddle.static.Program()
        self.sp = paddle.static.Program()
        self.executor = paddle.static.Executor(self.place)
        with paddle.static.program_guard(self.mp, self.sp):
            self.p = DummyDistribution()
            self.q = DummyDistribution()

    def test_dispatch_with_unregister(self):
        with self.assertRaises(NotImplementedError):
            with paddle.static.program_guard(self.mp, self.sp):
                out = paddle.distribution.kl_divergence(self.p, self.q)
                self.executor.run(self.sp)
                self.executor.run(self.mp, feed={}, fetch_list=[out])


176
@param.place(config.DEVICES)
177 178 179 180 181 182 183 184 185 186 187
@param.param_cls(
    (config.TEST_CASE_NAME, 'rate1', 'rate2'),
    [
        (
            'test-diff-dist',
            np.random.rand(100, 200, 100) + 1.0,
            np.random.rand(100, 200, 100) + 2.0,
        ),
        ('test-same-dist', np.array([1.0]), np.array([1.0])),
    ],
)
188 189 190 191 192 193
class TestKLExpfamilyExpFamily(unittest.TestCase):
    def setUp(self):
        self.mp = paddle.static.Program()
        self.sp = paddle.static.Program()
        self.executor = paddle.static.Executor(self.place)
        with paddle.static.program_guard(self.mp, self.sp):
194 195 196 197 198 199
            rate1 = paddle.static.data(
                'rate1', shape=self.rate1.shape, dtype=self.rate1.dtype
            )
            rate2 = paddle.static.data(
                'rate2', shape=self.rate2.shape, dtype=self.rate2.dtype
            )
200 201 202 203 204 205 206 207 208
            self.p = mock.Exponential(rate1)
            self.q = mock.Exponential(rate2)
            self.feeds = {'rate1': self.rate1, 'rate2': self.rate2}

    def test_kl_expfamily_expfamily(self):
        with paddle.static.program_guard(self.mp, self.sp):
            out1 = paddle.distribution.kl_divergence(self.p, self.q)
            out2 = kl._kl_expfamily_expfamily(self.p, self.q)
            self.executor.run(self.sp)
209 210 211
            [out1, out2] = self.executor.run(
                self.mp, feed=self.feeds, fetch_list=[out1, out2]
            )
212 213 214 215 216

            np.testing.assert_allclose(
                out1,
                out2,
                rtol=config.RTOL.get(config.DEFAULT_DTYPE),
217 218
                atol=config.ATOL.get(config.DEFAULT_DTYPE),
            )
219 220 221 222


if __name__ == '__main__':
    unittest.main()