test_distribution_normal.py 27.9 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
3 4 5
# 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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14 15 16 17
# 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 math
import unittest

18
import config
19
import numpy as np
20 21 22 23
import scipy.stats
from parameterize import TEST_CASE_NAME, parameterize_cls, place, xrand
from test_distribution import DistributionNumpy

24 25
import paddle
from paddle import fluid
26
from paddle.distribution import Normal
27

28 29
np.random.seed(2022)

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

class NormalNumpy(DistributionNumpy):
    def __init__(self, loc, scale):
        self.loc = np.array(loc)
        self.scale = np.array(scale)
        if str(self.loc.dtype) not in ['float32', 'float64']:
            self.loc = self.loc.astype('float32')
            self.scale = self.scale.astype('float32')

    def sample(self, shape):
        shape = tuple(shape) + (self.loc + self.scale).shape
        return self.loc + (np.random.randn(*shape) * self.scale)

    def log_prob(self, value):
        var = self.scale * self.scale
        log_scale = np.log(self.scale)
46 47 48 49 50
        return (
            -((value - self.loc) * (value - self.loc)) / (2.0 * var)
            - log_scale
            - math.log(math.sqrt(2.0 * math.pi))
        )
51 52 53

    def probs(self, value):
        var = self.scale * self.scale
54 55 56
        return np.exp(
            -1.0 * ((value - self.loc) * (value - self.loc)) / (2.0 * var)
        ) / (math.sqrt(2 * math.pi) * self.scale)
57 58

    def entropy(self):
59 60 61 62 63
        return (
            0.5
            + 0.5 * np.log(np.array(2.0 * math.pi).astype(self.loc.dtype))
            + np.log(self.scale)
        )
64 65

    def kl_divergence(self, other):
66
        var_ratio = self.scale / other.scale
67
        var_ratio = var_ratio * var_ratio
68 69
        t1 = (self.loc - other.loc) / other.scale
        t1 = t1 * t1
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
        return 0.5 * (var_ratio + t1 - 1 - np.log(var_ratio))


class NormalTest(unittest.TestCase):
    def setUp(self, use_gpu=False, batch_size=2, dims=3):
        self.use_gpu = use_gpu
        if not use_gpu:
            self.place = fluid.CPUPlace()
            self.gpu_id = -1
        else:
            self.place = fluid.CUDAPlace(0)
            self.gpu_id = 0

        self.init_numpy_data(batch_size, dims)

        paddle.disable_static(self.place)
        self.init_dynamic_data(batch_size, dims)

        paddle.enable_static()
        self.test_program = fluid.Program()
        self.executor = fluid.Executor(self.place)
        self.init_static_data(batch_size, dims)

    def init_numpy_data(self, batch_size, dims):
        # loc ans scale are 'float'
        self.loc_np = (np.random.ranf() - 0.5) * 4
        self.scale_np = (np.random.ranf() - 0.5) * 4
        while self.scale_np < 0:
            self.scale_np = (np.random.ranf() - 0.5) * 4
        # used to construct another Normal object to calculate kl_divergence
        self.other_loc_np = (np.random.ranf() - 0.5) * 4
        self.other_scale_np = (np.random.ranf() - 0.5) * 4
        while self.other_scale_np < 0:
            self.other_scale_np = (np.random.ranf() - 0.5) * 4
        self.values_np = np.random.ranf(1).astype('float32')

    def init_dynamic_data(self, batch_size, dims):
        self.dynamic_loc = self.loc_np
        self.dynamic_scale = self.scale_np
        self.dynamic_other_loc = self.other_loc_np
        self.dynamic_other_scale = self.other_scale_np
        self.dynamic_values = paddle.to_tensor(self.values_np)

    def init_static_data(self, batch_size, dims):
        self.static_loc = self.loc_np
        self.static_scale = self.scale_np
        self.static_other_loc = self.other_loc_np
        self.static_other_scale = self.other_scale_np
        with fluid.program_guard(self.test_program):
G
GGBond8488 已提交
119 120
            self.static_values = paddle.static.data(
                name='values', shape=[-1], dtype='float32'
121
            )
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

    def compare_with_numpy(self, fetch_list, sample_shape=7, tolerance=1e-6):
        sample, entropy, log_prob, probs, kl = fetch_list

        np_normal = NormalNumpy(self.loc_np, self.scale_np)
        np_sample = np_normal.sample([sample_shape])
        np_entropy = np_normal.entropy()
        np_lp = np_normal.log_prob(self.values_np)
        np_p = np_normal.probs(self.values_np)
        np_other_normal = NormalNumpy(self.other_loc_np, self.other_scale_np)
        np_kl = np_normal.kl_divergence(np_other_normal)

        # Because assign op does not support the input of numpy.ndarray whose dtype is FP64.
        # When loc and scale are FP64 numpy.ndarray, we need to use assign op to convert it
        #  to FP32 Tensor. And then use cast op to convert it to a FP64 Tensor.
        # There is a loss of accuracy in this conversion.
        # So set the tolerance from 1e-6 to 1e-4.
        log_tolerance = 1e-4
        np.testing.assert_equal(sample.shape, np_sample.shape)
141 142 143 144 145 146 147 148 149 150 151 152
        np.testing.assert_allclose(
            entropy, np_entropy, rtol=tolerance, atol=tolerance
        )
        np.testing.assert_allclose(
            log_prob, np_lp, rtol=log_tolerance, atol=log_tolerance
        )
        np.testing.assert_allclose(
            probs, np_p, rtol=log_tolerance, atol=log_tolerance
        )
        np.testing.assert_allclose(
            kl, np_kl, rtol=log_tolerance, atol=log_tolerance
        )
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

    def test_normal_distribution_dygraph(self, sample_shape=7, tolerance=1e-6):
        paddle.disable_static(self.place)
        normal = Normal(self.dynamic_loc, self.dynamic_scale)

        sample = normal.sample([sample_shape]).numpy()
        entropy = normal.entropy().numpy()
        log_prob = normal.log_prob(self.dynamic_values).numpy()
        probs = normal.probs(self.dynamic_values).numpy()
        other_normal = Normal(self.dynamic_other_loc, self.dynamic_other_scale)
        kl = normal.kl_divergence(other_normal).numpy()

        fetch_list = [sample, entropy, log_prob, probs, kl]
        self.compare_with_numpy(fetch_list)

    def test_normal_distribution_static(self, sample_shape=7, tolerance=1e-6):
        paddle.enable_static()
        with fluid.program_guard(self.test_program):
            normal = Normal(self.static_loc, self.static_scale)

            sample = normal.sample([sample_shape])
            entropy = normal.entropy()
            log_prob = normal.log_prob(self.static_values)
            probs = normal.probs(self.static_values)
177 178 179
            other_normal = Normal(
                self.static_other_loc, self.static_other_scale
            )
180 181 182 183 184 185 186 187 188
            kl = normal.kl_divergence(other_normal)

            fetch_list = [sample, entropy, log_prob, probs, kl]

        feed_vars = {
            'loc': self.loc_np,
            'scale': self.scale_np,
            'values': self.values_np,
            'other_loc': self.other_loc_np,
189
            'other_scale': self.other_scale_np,
190 191 192
        }

        self.executor.run(fluid.default_startup_program())
193 194 195
        fetch_list = self.executor.run(
            program=self.test_program, feed=feed_vars, fetch_list=fetch_list
        )
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

        self.compare_with_numpy(fetch_list)


class NormalTest2(NormalTest):
    def init_numpy_data(self, batch_size, dims):
        # loc ans scale are 'int'
        self.loc_np = int((np.random.ranf() - 0.5) * 8)
        self.scale_np = int((np.random.ranf() - 0.5) * 8)
        while self.scale_np < 0:
            self.scale_np = int((np.random.ranf() - 0.5) * 8)
        # used to construct another Normal object to calculate kl_divergence
        self.other_loc_np = int((np.random.ranf() - 0.5) * 8)
        self.other_scale_np = int((np.random.ranf() - 0.5) * 8)
        while self.other_scale_np < 0:
            self.other_scale_np = int((np.random.ranf() - 0.5) * 8)
        self.values_np = np.random.ranf(1).astype('float32')


class NormalTest3(NormalTest):
    def init_numpy_data(self, batch_size, dims):
        # test broadcast: loc is float, scale is numpy.ndarray with dtype 'float32'.
        self.loc_np = (np.random.ranf() - 0.5) * 4
        self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        while not np.all(self.scale_np > 0):
            self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        self.values_np = np.random.randn(batch_size, dims).astype('float32')
        # used to construct another Normal object to calculate kl_divergence
        self.other_loc_np = (np.random.ranf() - 0.5) * 4
225 226 227
        self.other_scale_np = np.random.randn(batch_size, dims).astype(
            'float32'
        )
228
        while not np.all(self.scale_np > 0):
229 230 231
            self.other_scale_np = np.random.randn(batch_size, dims).astype(
                'float32'
            )
232 233 234 235 236 237 238

    def init_static_data(self, batch_size, dims):
        self.static_loc = self.loc_np
        self.static_scale = self.scale_np
        self.static_other_loc = self.other_loc_np
        self.static_other_scale = self.other_scale_np
        with fluid.program_guard(self.test_program):
G
GGBond8488 已提交
239 240
            self.static_values = paddle.static.data(
                name='values', shape=[-1, dims], dtype='float32'
241
            )
242 243 244 245 246 247 248 249 250 251 252 253


class NormalTest4(NormalTest):
    def init_numpy_data(self, batch_size, dims):
        # loc and scale are numpy.ndarray with dtype 'float32'.
        self.loc_np = np.random.randn(batch_size, dims).astype('float32')
        self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        while not np.all(self.scale_np > 0):
            self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        self.values_np = np.random.randn(batch_size, dims).astype('float32')
        # used to construct another Normal object to calculate kl_divergence
        self.other_loc_np = np.random.randn(batch_size, dims).astype('float32')
254 255 256
        self.other_scale_np = np.random.randn(batch_size, dims).astype(
            'float32'
        )
257
        while not np.all(self.scale_np > 0):
258 259 260
            self.other_scale_np = np.random.randn(batch_size, dims).astype(
                'float32'
            )
261 262 263 264 265 266 267

    def init_static_data(self, batch_size, dims):
        self.static_loc = self.loc_np
        self.static_scale = self.scale_np
        self.static_other_loc = self.other_loc_np
        self.static_other_scale = self.other_scale_np
        with fluid.program_guard(self.test_program):
G
GGBond8488 已提交
268 269
            self.static_values = paddle.static.data(
                name='values', shape=[-1, dims], dtype='float32'
270
            )
271 272 273 274 275 276 277 278 279 280 281 282


class NormalTest5(NormalTest):
    def init_numpy_data(self, batch_size, dims):
        # loc and scale are numpy.ndarray with dtype 'float64'.
        self.loc_np = np.random.randn(batch_size, dims).astype('float64')
        self.scale_np = np.random.randn(batch_size, dims).astype('float64')
        while not np.all(self.scale_np > 0):
            self.scale_np = np.random.randn(batch_size, dims).astype('float64')
        self.values_np = np.random.randn(batch_size, dims).astype('float64')
        # used to construct another Normal object to calculate kl_divergence
        self.other_loc_np = np.random.randn(batch_size, dims).astype('float64')
283 284 285
        self.other_scale_np = np.random.randn(batch_size, dims).astype(
            'float64'
        )
286
        while not np.all(self.scale_np > 0):
287 288 289
            self.other_scale_np = np.random.randn(batch_size, dims).astype(
                'float64'
            )
290 291 292 293 294 295 296 297 298 299 300 301 302 303

    def init_dynamic_data(self, batch_size, dims):
        self.dynamic_loc = self.loc_np
        self.dynamic_scale = self.scale_np
        self.dynamic_other_loc = self.other_loc_np
        self.dynamic_other_scale = self.other_scale_np
        self.dynamic_values = paddle.to_tensor(self.values_np, dtype='float64')

    def init_static_data(self, batch_size, dims):
        self.static_loc = self.loc_np
        self.static_scale = self.scale_np
        self.static_other_loc = self.other_loc_np
        self.static_other_scale = self.other_scale_np
        with fluid.program_guard(self.test_program):
G
GGBond8488 已提交
304 305
            self.static_values = paddle.static.data(
                name='values', shape=[-1, dims], dtype='float64'
306
            )
307 308 309 310 311 312 313 314 315 316 317 318


class NormalTest6(NormalTest):
    def init_numpy_data(self, batch_size, dims):
        # loc and scale are Tensor with dtype 'VarType.FP32'.
        self.loc_np = np.random.randn(batch_size, dims).astype('float32')
        self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        while not np.all(self.scale_np > 0):
            self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        self.values_np = np.random.randn(batch_size, dims).astype('float32')
        # used to construct another Normal object to calculate kl_divergence
        self.other_loc_np = np.random.randn(batch_size, dims).astype('float32')
319 320 321
        self.other_scale_np = np.random.randn(batch_size, dims).astype(
            'float32'
        )
322
        while not np.all(self.scale_np > 0):
323 324 325
            self.other_scale_np = np.random.randn(batch_size, dims).astype(
                'float32'
            )
326 327 328 329 330 331 332 333 334 335

    def init_dynamic_data(self, batch_size, dims):
        self.dynamic_loc = paddle.to_tensor(self.loc_np)
        self.dynamic_scale = paddle.to_tensor(self.scale_np)
        self.dynamic_values = paddle.to_tensor(self.values_np)
        self.dynamic_other_loc = paddle.to_tensor(self.other_loc_np)
        self.dynamic_other_scale = paddle.to_tensor(self.other_scale_np)

    def init_static_data(self, batch_size, dims):
        with fluid.program_guard(self.test_program):
G
GGBond8488 已提交
336 337
            self.static_loc = paddle.static.data(
                name='loc', shape=[-1, dims], dtype='float32'
338
            )
G
GGBond8488 已提交
339 340
            self.static_scale = paddle.static.data(
                name='scale', shape=[-1, dims], dtype='float32'
341
            )
G
GGBond8488 已提交
342 343
            self.static_values = paddle.static.data(
                name='values', shape=[-1, dims], dtype='float32'
344
            )
G
GGBond8488 已提交
345 346
            self.static_other_loc = paddle.static.data(
                name='other_loc', shape=[-1, dims], dtype='float32'
347
            )
G
GGBond8488 已提交
348 349
            self.static_other_scale = paddle.static.data(
                name='other_scale', shape=[-1, dims], dtype='float32'
350
            )
351 352 353 354 355 356 357 358 359 360 361 362


class NormalTest7(NormalTest):
    def init_numpy_data(self, batch_size, dims):
        # loc and scale are Tensor with dtype 'VarType.FP64'.
        self.loc_np = np.random.randn(batch_size, dims).astype('float64')
        self.scale_np = np.random.randn(batch_size, dims).astype('float64')
        while not np.all(self.scale_np > 0):
            self.scale_np = np.random.randn(batch_size, dims).astype('float64')
        self.values_np = np.random.randn(batch_size, dims).astype('float64')
        # used to construct another Normal object to calculate kl_divergence
        self.other_loc_np = np.random.randn(batch_size, dims).astype('float64')
363 364 365
        self.other_scale_np = np.random.randn(batch_size, dims).astype(
            'float64'
        )
366
        while not np.all(self.scale_np > 0):
367 368 369
            self.other_scale_np = np.random.randn(batch_size, dims).astype(
                'float64'
            )
370 371 372 373 374

    def init_dynamic_data(self, batch_size, dims):
        self.dynamic_loc = paddle.to_tensor(self.loc_np, dtype='float64')
        self.dynamic_scale = paddle.to_tensor(self.scale_np, dtype='float64')
        self.dynamic_values = paddle.to_tensor(self.values_np, dtype='float64')
375 376 377 378 379 380
        self.dynamic_other_loc = paddle.to_tensor(
            self.other_loc_np, dtype='float64'
        )
        self.dynamic_other_scale = paddle.to_tensor(
            self.other_scale_np, dtype='float64'
        )
381 382 383

    def init_static_data(self, batch_size, dims):
        with fluid.program_guard(self.test_program):
G
GGBond8488 已提交
384 385
            self.static_loc = paddle.static.data(
                name='loc', shape=[-1, dims], dtype='float64'
386
            )
G
GGBond8488 已提交
387 388
            self.static_scale = paddle.static.data(
                name='scale', shape=[-1, dims], dtype='float64'
389
            )
G
GGBond8488 已提交
390 391
            self.static_values = paddle.static.data(
                name='values', shape=[-1, dims], dtype='float64'
392
            )
G
GGBond8488 已提交
393 394
            self.static_other_loc = paddle.static.data(
                name='other_loc', shape=[-1, dims], dtype='float64'
395
            )
G
GGBond8488 已提交
396 397
            self.static_other_scale = paddle.static.data(
                name='other_scale', shape=[-1, dims], dtype='float64'
398
            )
399 400 401 402 403 404 405 406 407 408 409 410


class NormalTest8(NormalTest):
    def init_numpy_data(self, batch_size, dims):
        # loc and scale are Tensor with dtype 'VarType.FP64'. value's dtype is 'VarType.FP32'.
        self.loc_np = np.random.randn(batch_size, dims).astype('float64')
        self.scale_np = np.random.randn(batch_size, dims).astype('float64')
        while not np.all(self.scale_np > 0):
            self.scale_np = np.random.randn(batch_size, dims).astype('float64')
        self.values_np = np.random.randn(batch_size, dims).astype('float32')
        # used to construct another Normal object to calculate kl_divergence
        self.other_loc_np = np.random.randn(batch_size, dims).astype('float64')
411 412 413
        self.other_scale_np = np.random.randn(batch_size, dims).astype(
            'float64'
        )
414
        while not np.all(self.scale_np > 0):
415 416 417
            self.other_scale_np = np.random.randn(batch_size, dims).astype(
                'float64'
            )
418 419 420 421 422

    def init_dynamic_data(self, batch_size, dims):
        self.dynamic_loc = paddle.to_tensor(self.loc_np, dtype='float64')
        self.dynamic_scale = paddle.to_tensor(self.scale_np, dtype='float64')
        self.dynamic_values = paddle.to_tensor(self.values_np)
423 424 425 426 427 428
        self.dynamic_other_loc = paddle.to_tensor(
            self.other_loc_np, dtype='float64'
        )
        self.dynamic_other_scale = paddle.to_tensor(
            self.other_scale_np, dtype='float64'
        )
429 430 431

    def init_static_data(self, batch_size, dims):
        with fluid.program_guard(self.test_program):
G
GGBond8488 已提交
432 433
            self.static_loc = paddle.static.data(
                name='loc', shape=[-1, dims], dtype='float64'
434
            )
G
GGBond8488 已提交
435 436
            self.static_scale = paddle.static.data(
                name='scale', shape=[-1, dims], dtype='float64'
437
            )
G
GGBond8488 已提交
438 439
            self.static_values = paddle.static.data(
                name='values', shape=[-1, dims], dtype='float32'
440
            )
G
GGBond8488 已提交
441 442
            self.static_other_loc = paddle.static.data(
                name='other_loc', shape=[-1, dims], dtype='float64'
443
            )
G
GGBond8488 已提交
444 445
            self.static_other_scale = paddle.static.data(
                name='other_scale', shape=[-1, dims], dtype='float64'
446
            )
447 448 449 450 451


class NormalTest9(NormalTest):
    def init_numpy_data(self, batch_size, dims):
        # loc and scale are list.
452 453 454
        self.loc_np = (
            np.random.randn(batch_size, dims).astype('float32').tolist()
        )
455 456 457 458 459 460
        self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        while not np.all(self.scale_np > 0):
            self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        self.scale_np = self.scale_np.tolist()
        self.values_np = np.random.randn(batch_size, dims).astype('float32')
        # used to construct another Normal object to calculate kl_divergence
461 462 463 464 465 466
        self.other_loc_np = (
            np.random.randn(batch_size, dims).astype('float32').tolist()
        )
        self.other_scale_np = np.random.randn(batch_size, dims).astype(
            'float32'
        )
467
        while not np.all(self.other_scale_np > 0):
468 469 470
            self.other_scale_np = np.random.randn(batch_size, dims).astype(
                'float32'
            )
471 472 473 474 475 476 477 478
        self.other_scale_np = self.other_scale_np.tolist()

    def init_static_data(self, batch_size, dims):
        self.static_loc = self.loc_np
        self.static_scale = self.scale_np
        self.static_other_loc = self.other_loc_np
        self.static_other_scale = self.other_scale_np
        with fluid.program_guard(self.test_program):
G
GGBond8488 已提交
479 480
            self.static_values = paddle.static.data(
                name='values', shape=[-1, dims], dtype='float32'
481
            )
482 483 484 485 486 487


class NormalTest10(NormalTest):
    def init_numpy_data(self, batch_size, dims):
        # loc and scale are tuple.
        self.loc_np = tuple(
488 489
            np.random.randn(batch_size, dims).astype('float32').tolist()
        )
490 491 492 493 494 495 496
        self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        while not np.all(self.scale_np > 0):
            self.scale_np = np.random.randn(batch_size, dims).astype('float32')
        self.scale_np = tuple(self.scale_np.tolist())
        self.values_np = np.random.randn(batch_size, dims).astype('float32')
        # used to construct another Normal object to calculate kl_divergence
        self.other_loc_np = tuple(
497 498 499 500 501
            np.random.randn(batch_size, dims).astype('float32').tolist()
        )
        self.other_scale_np = np.random.randn(batch_size, dims).astype(
            'float32'
        )
502
        while not np.all(self.other_scale_np > 0):
503 504 505
            self.other_scale_np = np.random.randn(batch_size, dims).astype(
                'float32'
            )
506 507 508 509 510 511 512 513
        self.other_scale_np = tuple(self.other_scale_np.tolist())

    def init_static_data(self, batch_size, dims):
        self.static_loc = self.loc_np
        self.static_scale = self.scale_np
        self.static_other_loc = self.other_loc_np
        self.static_other_scale = self.other_scale_np
        with fluid.program_guard(self.test_program):
G
GGBond8488 已提交
514 515
            self.static_values = paddle.static.data(
                name='values', shape=[-1, dims], dtype='float32'
516
            )
517 518


519 520 521 522 523 524 525 526
def kstest(loc, scale, samples):
    # Uses the Kolmogorov-Smirnov test for goodness of fit.
    ks, _ = scipy.stats.kstest(
        samples, scipy.stats.norm(loc=loc, scale=scale).cdf
    )
    return ks < 0.02


527
@place(config.DEVICES)
528 529 530
@parameterize_cls(
    (TEST_CASE_NAME, 'loc', 'scale'), [('sample', xrand((4,)), xrand((4,)))]
)
531 532 533 534 535
class TestNormalSampleDygraph(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
        self.paddle_normal = Normal(loc=self.loc, scale=self.scale)
        n = 100000
536
        self.sample_shape = (n,)
537 538 539 540 541
        self.samples = self.paddle_normal.sample(self.sample_shape)

    def test_sample(self):
        samples_mean = self.samples.mean(axis=0)
        samples_var = self.samples.var(axis=0)
542 543 544 545 546 547
        np.testing.assert_allclose(
            samples_mean, self.paddle_normal.mean, rtol=0.1, atol=0
        )
        np.testing.assert_allclose(
            samples_var, self.paddle_normal.variance, rtol=0.1, atol=0
        )
548 549

        batch_shape = (self.loc + self.scale).shape
550 551 552
        self.assertEqual(
            self.samples.shape, list(self.sample_shape + batch_shape)
        )
553 554 555

        for i in range(len(self.scale)):
            self.assertTrue(
556
                kstest(self.loc[i], self.scale[i], self.samples[:, i])
557
            )
558 559 560


@place(config.DEVICES)
561 562 563
@parameterize_cls(
    (TEST_CASE_NAME, 'loc', 'scale'), [('sample', xrand((4,)), xrand((4,)))]
)
564 565 566 567 568 569 570 571
class TestNormalSampleStaic(unittest.TestCase):
    def setUp(self):
        paddle.enable_static()
        startup_program = paddle.static.Program()
        main_program = paddle.static.Program()
        executor = paddle.static.Executor(self.place)
        with paddle.static.program_guard(main_program, startup_program):
            loc = paddle.static.data('loc', self.loc.shape, self.loc.dtype)
572 573 574
            scale = paddle.static.data(
                'scale', self.scale.shape, self.scale.dtype
            )
575
            n = 100000
576
            self.sample_shape = (n,)
577 578 579 580
            self.paddle_normal = Normal(loc=loc, scale=scale)
            mean = self.paddle_normal.mean
            variance = self.paddle_normal.variance
            samples = self.paddle_normal.sample(self.sample_shape)
581
        fetch_list = [mean, variance, samples]
582 583 584
        self.feeds = {'loc': self.loc, 'scale': self.scale}

        executor.run(startup_program)
585
        [self.mean, self.variance, self.samples] = executor.run(
586 587
            main_program, feed=self.feeds, fetch_list=fetch_list
        )
588 589 590 591 592 593 594

    def test_sample(self):
        samples_mean = self.samples.mean(axis=0)
        samples_var = self.samples.var(axis=0)
        np.testing.assert_allclose(samples_mean, self.mean, rtol=0.1, atol=0)
        np.testing.assert_allclose(samples_var, self.variance, rtol=0.1, atol=0)

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
        batch_shape = (self.loc + self.scale).shape
        self.assertEqual(self.samples.shape, self.sample_shape + batch_shape)

        for i in range(len(self.scale)):
            self.assertTrue(
                kstest(self.loc[i], self.scale[i], self.samples[:, i])
            )


@place(config.DEVICES)
@parameterize_cls(
    (TEST_CASE_NAME, 'loc', 'scale'), [('rsample', xrand((4,)), xrand((4,)))]
)
class TestNormalRSampleDygraph(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()
        self.loc = paddle.to_tensor(self.loc)
        self.scale = paddle.to_tensor(self.scale)
        self.loc.stop_gradient = False
        self.scale.stop_gradient = False
        self.paddle_normal = Normal(loc=self.loc, scale=self.scale)
        n = 100000
        self.rsample_shape = [n]
        self.rsamples = self.paddle_normal.rsample(self.rsample_shape)

    def test_rsample(self):
621 622
        rsamples_mean = self.rsamples.mean(axis=0)
        rsamples_var = self.rsamples.var(axis=0)
623
        np.testing.assert_allclose(
624 625 626 627
            rsamples_mean, self.paddle_normal.mean, rtol=0.1, atol=0
        )
        np.testing.assert_allclose(
            rsamples_var, self.paddle_normal.variance, rtol=0.1, atol=0
628
        )
629 630 631 632 633 634

        batch_shape = (self.loc + self.scale).shape
        self.assertEqual(self.rsamples.shape, self.rsample_shape + batch_shape)

        for i in range(len(self.scale)):
            self.assertTrue(
635
                kstest(self.loc[i], self.scale[i], self.rsamples[:, i])
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

    def test_backpropagation(self):
        grads = paddle.grad([self.rsamples], [self.loc, self.scale])
        self.assertEqual(len(grads), 2)
        self.assertEqual(grads[0].dtype, self.loc.dtype)
        self.assertEqual(grads[0].shape, self.loc.shape)
        self.assertEqual(grads[1].dtype, self.scale.dtype)
        self.assertEqual(grads[1].shape, self.scale.shape)


@place(config.DEVICES)
@parameterize_cls(
    (TEST_CASE_NAME, 'loc', 'scale'), [('rsample', xrand((4,)), xrand((4,)))]
)
class TestNormalRSampleStaic(unittest.TestCase):
    def setUp(self):
        paddle.enable_static()
        startup_program = paddle.static.Program()
        main_program = paddle.static.Program()
        executor = paddle.static.Executor(self.place)
        with paddle.static.program_guard(main_program, startup_program):
            loc = paddle.static.data('loc', self.loc.shape, self.loc.dtype)
            scale = paddle.static.data(
                'scale', self.scale.shape, self.scale.dtype
661
            )
662 663 664 665 666 667 668 669 670 671 672 673 674
            n = 100000
            self.rsample_shape = (n,)
            self.paddle_normal = Normal(loc=loc, scale=scale)
            mean = self.paddle_normal.mean
            variance = self.paddle_normal.variance
            rsamples = self.paddle_normal.rsample(self.rsample_shape)
        fetch_list = [mean, variance, rsamples]
        self.feeds = {'loc': self.loc, 'scale': self.scale}

        executor.run(startup_program)
        [self.mean, self.variance, self.rsamples] = executor.run(
            main_program, feed=self.feeds, fetch_list=fetch_list
        )
675

676 677 678 679 680 681
    def test_rsample(self):
        rsamples_mean = self.rsamples.mean(axis=0)
        rsamples_var = self.rsamples.var(axis=0)
        np.testing.assert_allclose(rsamples_mean, self.mean, rtol=0.1, atol=0)
        np.testing.assert_allclose(
            rsamples_var, self.variance, rtol=0.1, atol=0
682
        )
683 684 685 686 687 688 689 690

        batch_shape = (self.loc + self.scale).shape
        self.assertEqual(self.rsamples.shape, self.rsample_shape + batch_shape)

        for i in range(len(self.scale)):
            self.assertTrue(
                kstest(self.loc[i], self.scale[i], self.rsamples[:, i])
            )
691 692


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