aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/compiler/tf2xla/lib/random.cc
blob: 3dfa66029ca84fad9c511e7b32a906ee41d37812 (plain)
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
/* Copyright 2018 The TensorFlow 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.
==============================================================================*/

#include "tensorflow/compiler/tf2xla/lib/random.h"

#include <cmath>
#include <limits>

#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/xla_client/xla_builder.h"
#include "tensorflow/compiler/xla/status_macros.h"

namespace tensorflow {

xla::XlaOp TruncatedNormal(const DataType dtype, xla::XlaOp uniform) {
  xla::XlaBuilder* builder = uniform.builder();
  auto normal_cdf = [](double x) {
    return (1.0 + std::erf(x / std::sqrt(2.0))) / 2.0;
  };

  const double kA = -2.0;
  const double kB = 2.0;
  const double kMu = 0.0;
  const double kSigma = 1.0;
  const double kAlpha = (kA - kMu) / kSigma;
  const double kBeta = (kB - kMu) / kSigma;
  const double kAlphaNormalCdf = normal_cdf(kAlpha);
  const double kBetaNormalCdf = normal_cdf(kBeta);
  const double kZ = kBetaNormalCdf - kAlphaNormalCdf;

  xla::XlaOp one = XlaHelpers::FloatLiteral(builder, dtype, 1.0);
  xla::XlaOp two = XlaHelpers::FloatLiteral(builder, dtype, 2.0);
  xla::XlaOp sqrt_2 = XlaHelpers::FloatLiteral(builder, dtype, std::sqrt(2.0));

  xla::XlaOp z = XlaHelpers::FloatLiteral(builder, dtype, kZ);
  xla::XlaOp alpha_normal_cdf =
      XlaHelpers::FloatLiteral(builder, dtype, kAlphaNormalCdf);

  // probit(p) = sqrt(2) * erfinv(2*p-1)
  auto p = xla::Add(alpha_normal_cdf, xla::Mul(z, uniform));
  auto erfinv_input = xla::Sub(xla::Mul(p, two), one);
  return xla::Mul(sqrt_2, ErfInv(erfinv_input));
}

}  // namespace tensorflow