Skip to content

Fix XLA truncated normal sampling in far one-sided tails - #129984

Merged
copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
adi-IL:fix-xla-truncated-normal-far-tail
Nov 9, 2026
Merged

copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
adi-IL:fix-xla-truncated-normal-far-tail

Conversation

@adi-IL

@adi-IL adi-IL commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Why

stateless_parameterized_truncated_normal under XLA collapses every sample onto a bound when both limits sit on one side of the mean and far from it. For example, bounds [6, 7] return 6.0 for every element with jit_compile=True. Float32 CDFs round to 0 or 1, so the existing inverse-CDF path loses the tail.

Fixes #128959

Change

For one-sided intervals, sample from the upper tail (mirrored for the lower side) by inverting log P(Z > t). Use erfc below 8 and the Mills-ratio asymptotic above it, then refine with Newton steps. F16 and BF16 run the tail math in F32. F64 switches to the asymptotic expansion at 26. Intervals that straddle zero keep the previous path.

The test helper computed the expected median with ndtri in f32, which returns inf for upper-tail intervals. It now uses f64 and evaluates the lower tail symmetrically with the upper one.

The parameterized truncated normal tests now convert their parameters to each dtype, so they exercise f16, f32, and f64 instead of always running f32. bf16 is excluded because stateless_parameterized_truncated_normal rejects it.

Evidence

Fail-before (new tests on unfixed random.cc):

  • testParameterizedTruncatedNormalFarRightTail FAILED
  • testParameterizedTruncatedNormalFarLeftTail FAILED

Pass-after (full fix):

  • both tests OK under //tensorflow/compiler/tests:stateless_random_ops_test_cpu

Logs: worktree evidence/fail-before.log and evidence/pass-after.log.

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Nov 5, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements a more robust sampling method for truncated normals in the tails by utilizing log tail probabilities to maintain precision, including a fallback to F32 for F16 types. It also adds new test cases for far-tail scenarios and updates the probit function in the Python test utilities to ensure consistent float precision. The review feedback suggests extending the type promotion logic to explicitly include BF16 for better numerical stability and improving variable naming for constants to enhance code maintainability.

@nithyak0204 nithyak0204 self-assigned this Nov 5, 2026
@nithyak0204
nithyak0204 requested a review from a team November 5, 2026 05:41
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Nov 5, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Nov 5, 2026
@nithyak0204 nithyak0204 added the prtype:bugfix PR to fix a bug label Nov 5, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for fixing one-sided tail sampling in ParameterizedTruncatedNormal. Please address three issues in the tail math and tests.

  1. Fix 16-bit overflow and float32 cancellation in tensorflow/compiler/tf2xla/lib/random.cc:
    Lines 53-54 compute alpha and beta in the input dtype before casting to tail_type. Small sigma values in float16 or bfloat16 (such as sigma=1e-3 on [70, 80]) overflow alpha and beta to infinity and produce NaN. Keeping -0.5 * t^2 inside log_upper_tail also causes float32 cancellation in log_q - log_q_lo and in the Newton slope when lo is large. Upcast uniform, mu, sigma, a, and b to tail_type (promoting both F16 and BF16 to F32) before computing tail_alpha and tail_beta. Factor -0.5 * t^2 - log_sqrt_2pi out of the tail helper, keep delta separate, and guard non-finite tail_x values with xla::IsFinite. Also reuse primitive_type, keep distinct tail_* scalar names, use a 26.0 cutover for F64, and update the function comment:
// Implements the sampling of truncated normal distribution using the
// inversed cumulative distribution function (CDF) method as described in
// https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf,
// and log-tail-probability Newton inversion when both bounds lie on one
// side of the mean.
  // When (alpha, beta) lies on one side of zero, the CDF values above can
  // round to 0 or 1 and the samples collapse onto a bound. Sample those
  // regions from the upper tail (mirrored for the lower side) using log
  // tail probabilities, which keep their precision far from the mean. F16
  // and BF16 lack the range and precision for these probabilities, so the
  // tail is computed in F32.
  xla::PrimitiveType tail_type =
      (primitive_type == xla::F16 || primitive_type == xla::BF16)
          ? xla::F32
          : primitive_type;
  xla::XlaOp u = xla::ConvertElementType(uniform, tail_type);
  xla::XlaOp tail_mu = xla::ConvertElementType(mu, tail_type);
  xla::XlaOp tail_sigma = xla::ConvertElementType(sigma, tail_type);
  xla::XlaOp tail_a = xla::ConvertElementType(a, tail_type);
  xla::XlaOp tail_b = xla::ConvertElementType(b, tail_type);
  xla::XlaOp tail_alpha = (tail_a - tail_mu) / tail_sigma;
  xla::XlaOp tail_beta = (tail_b - tail_mu) / tail_sigma;
  xla::XlaOp tail_zero = xla::ScalarLike(u, 0.0);
  xla::XlaOp tail_half = xla::ScalarLike(u, 0.5);
  xla::XlaOp tail_one = xla::ScalarLike(u, 1.0);
  xla::XlaOp tail_two = xla::ScalarLike(u, 2.0);
  xla::XlaOp tail_sqrt_2 = xla::ScalarLike(u, std::sqrt(2.0));
  xla::XlaOp log_sqrt_2pi = xla::ScalarLike(u, 0.5 * std::log(2 * M_PI));
  xla::XlaOp series_start =
      xla::ScalarLike(u, tail_type == xla::F64 ? 26.0 : 8.0);
  // log(P(Z > t)) + 0.5 * t^2 + 0.5 * log(2 * pi) for t >= 0. Factoring
  // out -0.5 * t^2 avoids catastrophic cancellation for large t; erfc
  // underflows for large t, so switch to the Mills-ratio asymptotic
  // expansion at series_start.
  auto log_scaled_upper_tail = [&](xla::XlaOp t) {
    xla::XlaOp td = xla::Min(t, series_start);
    xla::XlaOp direct = xla::Log(xla::Erfc(td / tail_sqrt_2) / tail_two) +
                        tail_half * td * td + log_sqrt_2pi;
    xla::XlaOp ts = xla::Max(t, series_start);
    xla::XlaOp inv_ts = tail_one / ts;
    xla::XlaOp z = inv_ts * inv_ts;
    xla::XlaOp series = xla::ScalarLike(u, 10395.0);
    for (double c : {-945.0, 105.0, -15.0, 3.0, -1.0, 1.0}) {
      series = xla::ScalarLike(u, c) + z * series;
    }
    xla::XlaOp asymptotic = xla::Log(series) - xla::Log(ts);
    return xla::Select(xla::Lt(t, series_start), direct, asymptotic);
  };
  xla::XlaOp upper = xla::Gt(tail_alpha, tail_zero);
  xla::XlaOp lo = xla::Select(upper, tail_alpha, -tail_beta);
  xla::XlaOp hi = xla::Select(upper, tail_beta, -tail_alpha);
  xla::XlaOp rest_lo = log_scaled_upper_tail(lo);
  xla::XlaOp rest_hi = log_scaled_upper_tail(hi);
  xla::XlaOp log_q_diff =
      (rest_hi - rest_lo) - (hi - lo) * (tail_half * hi + tail_half * lo);
  xla::XlaOp delta =
      xla::Log(u + (tail_one - u) * xla::Exp(log_q_diff));
  xla::XlaOp t_small = xla::Sqrt(lo * lo - tail_two * delta);
  xla::XlaOp t_large =
      lo * xla::Sqrt(tail_one - tail_two * (delta / lo) / lo);
  xla::XlaOp t = xla::Select(xla::Lt(lo, series_start), t_small, t_large);
  for (int i = 0; i < 3; ++i) {
    // Newton step on log(P(Z > t)) = log_q.
    xla::XlaOp rest_t = log_scaled_upper_tail(t);
    xla::XlaOp err = (rest_t - rest_lo - delta) -
                     (t - lo) * (tail_half * t + tail_half * lo);
    xla::XlaOp slope = -xla::Exp(-rest_t);
    t = xla::Clamp(lo, t - err / slope, hi);
  }
  xla::XlaOp tail_x =
      tail_mu + tail_sigma * xla::Select(upper, t, -t);
  xla::XlaOp tail_clamped = xla::ConvertElementType(
      xla::Clamp(tail_a, tail_x, tail_b), primitive_type);
  xla::XlaOp one_sided =
      xla::And(xla::Or(upper, xla::Lt(tail_beta, tail_zero)),
               xla::IsFinite(tail_x));
  x = xla::Select(one_sided, tail_clamped, x);
  1. Avoid float64 cancellation for upper-tail expectations in tensorflow/python/kernel_tests/random/util.py:
    When alpha > 0, _normal_cdf evaluates math.erfc near 2.0 and loses precision above 8 sigma. At [8, 9] the expected mean drops below 8.0, and at [9, 10] the normalizer z rounds to zero. Use normal symmetry when alpha > 0 so math.erfc stays in the lower tail:
  alpha = (a - mu) / sigma
  beta = (b - mu) / sigma
  if alpha > 0:
    z = _normal_cdf(-alpha) - _normal_cdf(-beta)
    median_norm = -probit((_normal_cdf(-alpha) + _normal_cdf(-beta)) / 2.)
  else:
    z = _normal_cdf(beta) - _normal_cdf(alpha)
    median_norm = probit((_normal_cdf(alpha) + _normal_cdf(beta)) / 2.)

  assert_equal((y >= a).sum(), n)
  assert_equal((y <= b).sum(), n)

  # For more information on these calculations, see:
  # Burkardt, John. "The Truncated Normal Distribution".
  # Department of Scientific Computing website. Florida State University.
  expected_mean = mu + (normal_pdf(alpha) - normal_pdf(beta)) / z * sigma
  y = y.astype(float)
  actual_mean = np.mean(y)
  assert_all_close(actual_mean, expected_mean, atol=mean_atol)

  expected_median = mu + median_norm * sigma
  actual_median = np.median(y)
  assert_all_close(actual_median, expected_median, atol=median_atol)
  1. Cover all dtypes and tail regimes in tensorflow/compiler/tests/stateless_random_ops_test.py:
    _testParameterizedTruncatedNormal loops over self._random_types(), but it passes Python floats and runs float32 on every iteration. Convert the inputs to dtype, pass the quantized bounds to test_truncated_normal, and avoid mutating variance_rtol across iterations. Also remove the skipTest calls in RightTail and LeftTail, add [8, 9] and [-9, -8] asymptotic tests, and test small-stddev float16 bounds:
    for dtype in self._random_types():
      with self.session() as sess, self.test_scope():
        np_dtype = dtype.as_numpy_dtype
        means_dt = float(np.asarray(means, dtype=np_dtype))
        stddevs_dt = float(np.asarray(stddevs, dtype=np_dtype))
        minvals_dt = float(np.asarray(minvals, dtype=np_dtype))
        maxvals_dt = float(np.asarray(maxvals, dtype=np_dtype))
        seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
        x = stateless.stateless_parameterized_truncated_normal(
            shape=[n],
            seed=seed_t,
            means=ops.convert_to_tensor(means_dt, dtype=dtype),
            stddevs=ops.convert_to_tensor(stddevs_dt, dtype=dtype),
            minvals=ops.convert_to_tensor(minvals_dt, dtype=dtype),
            maxvals=ops.convert_to_tensor(maxvals_dt, dtype=dtype))
        y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]})
        mean_atol = 2e-2 if dtype == dtypes.bfloat16 else (
            4e-3 if dtype == dtypes.float16 else 1e-3)
        median_atol = 4e-2 if dtype == dtypes.bfloat16 else (
            4e-3 if dtype == dtypes.float16 else 1e-3)
        var_rtol = variance_rtol
        if var_rtol is None:
          var_rtol = 6e-3 if dtype == dtypes.bfloat16 else 1e-3
        elif dtype == dtypes.bfloat16:
          var_rtol = max(var_rtol, 8e-2)
        elif dtype == dtypes.float16:
          var_rtol = max(var_rtol, 5e-2)
        random_test_util.test_truncated_normal(
            self.assertEqual,
            self.assertAllClose,
            n,
            y,
            means=means_dt,
            stddevs=stddevs_dt,
            minvals=minvals_dt,
            maxvals=maxvals_dt,
            mean_atol=mean_atol,
            median_atol=median_atol,
            variance_rtol=var_rtol)
  def testParameterizedTruncatedNormalRightTail(self):
    self._testParameterizedTruncatedNormal(0., 1., 4., 20., variance_rtol=2e-2)

  def testParameterizedTruncatedNormalLeftTail(self):
    self._testParameterizedTruncatedNormal(
        0., 1., -20., -4., variance_rtol=5e-2)

  def testParameterizedTruncatedNormalLeftTailTwoSidedBounds(self):
    self._testParameterizedTruncatedNormal(
        0., 1., -6., -3., variance_rtol=5e-2)

  def testParameterizedTruncatedNormalFarRightTail(self):
    self._testParameterizedTruncatedNormal(0., 1., 6., 7., variance_rtol=2e-2)

  def testParameterizedTruncatedNormalFarLeftTail(self):
    self._testParameterizedTruncatedNormal(
        0., 1., -7., -6., variance_rtol=2e-2)

  def testParameterizedTruncatedNormalAsymptoticRightTail(self):
    self._testParameterizedTruncatedNormal(0., 1., 8., 9., variance_rtol=2e-2)

  def testParameterizedTruncatedNormalAsymptoticLeftTail(self):
    self._testParameterizedTruncatedNormal(
        0., 1., -9., -8., variance_rtol=2e-2)

  def testParameterizedTruncatedNormalExtremeNormalizedBounds(self):
    for dtype in self._random_types():
      with self.session() as sess, self.test_scope():
        seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
        x = stateless.stateless_parameterized_truncated_normal(
            shape=[1000],
            seed=seed_t,
            means=ops.convert_to_tensor(0., dtype=dtype),
            stddevs=ops.convert_to_tensor(1e-3, dtype=dtype),
            minvals=ops.convert_to_tensor(70., dtype=dtype),
            maxvals=ops.convert_to_tensor(80., dtype=dtype))
        y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]})
        self.assertAllClose(y, np.full([1000], 70., dtype=y.dtype))

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Nov 5, 2026
@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Nov 6, 2026
@adi-IL

adi-IL commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@dmiltr3 pushed dcea9d3. tail_alpha and tail_beta are now computed in tail_type after uniform, mu, sigma, a, and b are converted, and both f16 and bf16 go to f32. The quadratic term is out of log_scaled_upper_tail and subtracted at the call sites, delta stays separate, tail_x is guarded with IsFinite, and series_start is 26 for f64 and 8 otherwise. The function comment is updated. I also ran clang-format 17.0.6 on random.cc.

In util.py the alpha > 0 branch computes z and the median from the lower tail. The tests build the bounds in each dtype with the per-dtype tolerances, the two skips are gone, and the [8,9], [-9,-8], and small-stddev cases are in.

I checked the numerics against mpmath at 80 digits. For [8,9] the max quantile error is 4.9e-7 in f32 and 1.8e-15 in f64. The old path pinned 100% of f32 samples and 8.4% of f64 samples to the bound. [4,20] goes from 0.20 to 6.1e-7, [-2,2] is unchanged, and the extreme f16 and f32 cases return exactly 70.

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Nov 6, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Add a float16 default variance tolerance in tensorflow/compiler/tests/stateless_random_ops_test.py (lines 473-475):
    Converting means, stddevs, minvals, and maxvals to dtype tensors makes testParameterizedTruncatedNormalDefault and testParameterizedTruncatedNormalShifted run in float16 on the two-sided inverse-CDF path. Our earlier snippet omitted dtypes.float16 inside if var_rtol is None:. That leaves both tests at 1e-3, so build-linux-x86-cpu / build-and-test fails on float16 variance (2.0e-3 and 5.9e-3). Include dtypes.float16 in the var_rtol is None branch:
        var_rtol = variance_rtol
        if var_rtol is None:
          var_rtol = 6e-3 if dtype == dtypes.bfloat16 else (
              1e-2 if dtype == dtypes.float16 else 1e-3)
        elif dtype == dtypes.bfloat16:
          var_rtol = max(var_rtol, 8e-2)
        elif dtype == dtypes.float16:
          var_rtol = max(var_rtol, 5e-2)
  1. Update the function comment above ParameterizedTruncatedNormal in tensorflow/compiler/tf2xla/lib/random.cc (lines 37-39):
    Update the header comment above ParameterizedTruncatedNormal so it mentions log-tail-probability Newton inversion for one-sided bounds:
// Implements the sampling of truncated normal distribution using the
// inversed cumulative distribution function (CDF) method as described in
// https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf,
// and log-tail-probability Newton inversion when both bounds lie on one
// side of the mean.
  1. Update the ## Change summary in the PR description:
    The ## Change section in the PR description still says only F16 runs the tail math in F32 with a cutover at 8. Update the ## Change summary in the PR description covering BF16 promotion to F32, the 26 cutover for F64, and symmetric lower-tail evaluation in test_truncated_normal.

@adi-IL

adi-IL commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 1e14bd1.

Added the float16 default variance tolerance in the test helper, updated the comment above ParameterizedTruncatedNormal, and rewrote the Change section to cover bf16 promotion to f32, the f64 cutover at 26, and the symmetric lower tail in test_truncated_normal.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction to our earlier review: our first review asked to convert means, stddevs, minvals, and maxvals for every dtype in self._random_types(). On accelerator tests, self._random_types() includes bfloat16, while StatelessParameterizedTruncatedNormal only allows float16, float32, and float64. Sorry for the extra round.

  1. Exclude bfloat16 and use n = int(1e7) in tensorflow/compiler/tests/stateless_random_ops_test.py (lines 448-480 and 525):
    Internal presubmit tests on accelerators fail in two places. First, passing bfloat16 tensors to stateless.stateless_parameterized_truncated_normal raises TypeError: Value passed to parameter 'means' has DataType bfloat16 not in list of allowed values: float16, float32, float64. Second, n = int(10e7) (100 million elements) in _testParameterizedTruncatedNormal requires 10.71 GB of HLO temporaries with the unrolled tail Newton steps. That exceeds the 7.75 GB memory limit on 8 GB accelerators. Set n = int(1e7) (matching testTruncatedNormal on line 412) and exclude dtypes.bfloat16 in _testParameterizedTruncatedNormal and testParameterizedTruncatedNormalExtremeNormalizedBounds:
  def _testParameterizedTruncatedNormal(self,
                                        means,
                                        stddevs,
                                        minvals,
                                        maxvals,
                                        variance_rtol=None):
    n = int(1e7)
    for dtype in self._random_types() - {dtypes.bfloat16}:
      with self.session() as sess, self.test_scope():
        np_dtype = dtype.as_numpy_dtype
        means_dt = float(np.asarray(means, dtype=np_dtype))
        stddevs_dt = float(np.asarray(stddevs, dtype=np_dtype))
        minvals_dt = float(np.asarray(minvals, dtype=np_dtype))
        maxvals_dt = float(np.asarray(maxvals, dtype=np_dtype))
        seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
        x = stateless.stateless_parameterized_truncated_normal(
            shape=[n],
            seed=seed_t,
            means=ops.convert_to_tensor(means_dt, dtype=dtype),
            stddevs=ops.convert_to_tensor(stddevs_dt, dtype=dtype),
            minvals=ops.convert_to_tensor(minvals_dt, dtype=dtype),
            maxvals=ops.convert_to_tensor(maxvals_dt, dtype=dtype))
        y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]})
        mean_atol = 4e-3 if dtype == dtypes.float16 else 1e-3
        median_atol = 4e-3 if dtype == dtypes.float16 else 1e-3
        var_rtol = variance_rtol
        if var_rtol is None:
          var_rtol = 1e-2 if dtype == dtypes.float16 else 1e-3
        elif dtype == dtypes.float16:
          var_rtol = max(var_rtol, 5e-2)
        random_test_util.test_truncated_normal(
            self.assertEqual,
            self.assertAllClose,
            n,
            y,
            means=means_dt,
            stddevs=stddevs_dt,
            minvals=minvals_dt,
            maxvals=maxvals_dt,
            mean_atol=mean_atol,
            median_atol=median_atol,
            variance_rtol=var_rtol)
  def testParameterizedTruncatedNormalExtremeNormalizedBounds(self):
    for dtype in self._random_types() - {dtypes.bfloat16}:
      with self.session() as sess, self.test_scope():
        seed_t = array_ops.placeholder(dtypes.int32, shape=[2])
        x = stateless.stateless_parameterized_truncated_normal(
            shape=[1000],
            seed=seed_t,
            means=ops.convert_to_tensor(0., dtype=dtype),
            stddevs=ops.convert_to_tensor(1e-3, dtype=dtype),
            minvals=ops.convert_to_tensor(70., dtype=dtype),
            maxvals=ops.convert_to_tensor(80., dtype=dtype))
        y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]})
        self.assertAllClose(y, np.full([1000], 70., dtype=y.dtype))
  1. Include <initializer_list> in tensorflow/compiler/tf2xla/lib/random.cc (line 18):
    Line 118 loops over a braced initializer list (for (double c : {-945.0, 105.0, -15.0, 3.0, -1.0, 1.0})), which uses std::initializer_list<double>. Include <initializer_list> directly instead of relying on transitive headers:
#include <cmath>
#include <initializer_list>
  1. Update the Newton loop comment in tensorflow/compiler/tf2xla/lib/random.cc (line 136):
    Line 136 still mentions log_q, which was removed when delta was factored out. Update the comment to match the equation solved on lines 138-139:
  for (int i = 0; i < 3; ++i) {
    // Newton step on log(P(Z > t)) = log(P(Z > lo)) + delta.
    xla::XlaOp rest_t = log_scaled_upper_tail(t);

@adi-IL

adi-IL commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Fixed all three in af6e4f5.

The helper now uses n = int(1e7) on every device and skips bfloat16 in both parameterized tests. That keeps the accelerator HLO under the memory limit and matches the dtypes the op accepts. I dropped the bfloat16 tolerance branches along with it.

random.cc now includes <initializer_list> directly, and the Newton loop comment says log(P(Z > t)) = log(P(Z > lo)) + delta.

I ran testParameterizedTruncatedNormalAsymptoticRightTail and testParameterizedTruncatedNormalExtremeNormalizedBounds on CPU in the default and MLIR bridge variants. Both pass.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Nov 6, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Nov 6, 2026
When both bounds of stateless_parameterized_truncated_normal lie on one
side of zero and far from the mean, the normal CDF values computed in f32
round to 0 or 1 and every sample collapses onto a bound. For example,
[6, 7] returns 6.0 for every element under jit_compile.

For one-sided intervals, sample the upper tail (mirrored for the lower
side) by inverting log P(Z > t), using erfc below 8 and the asymptotic
Mills ratio expansion above it, refined with Newton steps. F16 computes
the tail in F32. Intervals that straddle zero keep the existing path.

The test util computed the expected median with ndtri in f32, which
returns inf for upper-tail intervals; it now uses f64.

Fixes tensorflow#128959
Compute tail_alpha and tail_beta in the promoted tail type so bf16
bounds keep their range, factor the quadratic term out of the tail
helper, guard tail_x with IsFinite, and start the asymptotic series at
26 for f64. The test util now uses the symmetric survival form for
one-sided intervals, and the tests build the bounds in each dtype.
The parameterized truncated normal tests now convert their parameters to
each dtype, so float16 reaches the inverse-CDF path for the first time
and misses the 1e-3 variance tolerance on the default and shifted cases.
Give float16 a 1e-2 default tolerance.

Also document the log-tail Newton inversion in the function comment.
Use n = int(1e7) on every device and skip bfloat16, which stateless_parameterized_truncated_normal does not accept. Remove the bfloat16 tolerance branches and include <initializer_list> directly. Fix the Newton step comment to name the equation the loop actually solves.
@dmiltr3
dmiltr3 force-pushed the fix-xla-truncated-normal-far-tail branch from af6e4f5 to c0b246f Compare November 9, 2026 07:17
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Nov 9, 2026
@dmiltr3 dmiltr3 added the ready to pull PR ready for merge process label Nov 9, 2026
@copybara-service
copybara-service Bot merged commit aad13d4 into tensorflow:master Nov 9, 2026
15 of 17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kokoro:force-run Tests on submitted change prtype:bugfix PR to fix a bug ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

[XLA] Far-tail truncated normal sampling collapses to the lower bound

3 participants