Repository navigation
Fix XLA truncated normal sampling in far one-sided tails - #129984
copybara-service[bot] merged 4 commits into
Conversation
There was a problem hiding this comment.
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.
dmiltr3
left a comment
There was a problem hiding this comment.
Thanks for fixing one-sided tail sampling in ParameterizedTruncatedNormal. Please address three issues in the tail math and tests.
- Fix 16-bit overflow and float32 cancellation in
tensorflow/compiler/tf2xla/lib/random.cc:
Lines 53-54 computealphaandbetain the input dtype before casting totail_type. Smallsigmavalues infloat16orbfloat16(such assigma=1e-3on[70, 80]) overflowalphaandbetato infinity and produceNaN. Keeping-0.5 * t^2insidelog_upper_tailalso causesfloat32cancellation inlog_q - log_q_loand in the Newton slope whenlois large. Upcastuniform,mu,sigma,a, andbtotail_type(promoting bothF16andBF16toF32) before computingtail_alphaandtail_beta. Factor-0.5 * t^2 - log_sqrt_2piout of the tail helper, keepdeltaseparate, and guard non-finitetail_xvalues withxla::IsFinite. Also reuseprimitive_type, keep distincttail_*scalar names, use a26.0cutover forF64, 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);- Avoid float64 cancellation for upper-tail expectations in
tensorflow/python/kernel_tests/random/util.py:
Whenalpha > 0,_normal_cdfevaluatesmath.erfcnear2.0and loses precision above 8 sigma. At[8, 9]the expected mean drops below8.0, and at[9, 10]the normalizerzrounds to zero. Use normal symmetry whenalpha > 0somath.erfcstays 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)- Cover all dtypes and tail regimes in
tensorflow/compiler/tests/stateless_random_ops_test.py:
_testParameterizedTruncatedNormalloops overself._random_types(), but it passes Python floats and runsfloat32on every iteration. Convert the inputs todtype, pass the quantized bounds totest_truncated_normal, and avoid mutatingvariance_rtolacross iterations. Also remove theskipTestcalls inRightTailandLeftTail, add[8, 9]and[-9, -8]asymptotic tests, and test small-stddevfloat16bounds:
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))|
@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. |
dmiltr3
left a comment
There was a problem hiding this comment.
- Add a
float16default variance tolerance intensorflow/compiler/tests/stateless_random_ops_test.py(lines 473-475):
Convertingmeans,stddevs,minvals, andmaxvalstodtypetensors makestestParameterizedTruncatedNormalDefaultandtestParameterizedTruncatedNormalShiftedrun infloat16on the two-sided inverse-CDF path. Our earlier snippet omitteddtypes.float16insideif var_rtol is None:. That leaves both tests at1e-3, so build-linux-x86-cpu / build-and-test fails onfloat16variance (2.0e-3and5.9e-3). Includedtypes.float16in thevar_rtol is Nonebranch:
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)- Update the function comment above
ParameterizedTruncatedNormalintensorflow/compiler/tf2xla/lib/random.cc(lines 37-39):
Update the header comment aboveParameterizedTruncatedNormalso 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.- Update the
## Changesummary in the PR description:
The## Changesection in the PR description still says onlyF16runs the tail math inF32with a cutover at8. Update the## Changesummary in the PR description coveringBF16promotion toF32, the26cutover forF64, and symmetric lower-tail evaluation intest_truncated_normal.
|
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
left a comment
There was a problem hiding this comment.
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.
- Exclude
bfloat16and usen = int(1e7)intensorflow/compiler/tests/stateless_random_ops_test.py(lines 448-480 and 525):
Internal presubmit tests on accelerators fail in two places. First, passingbfloat16tensors tostateless.stateless_parameterized_truncated_normalraisesTypeError: 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_testParameterizedTruncatedNormalrequires 10.71 GB of HLO temporaries with the unrolled tail Newton steps. That exceeds the 7.75 GB memory limit on 8 GB accelerators. Setn = int(1e7)(matchingtestTruncatedNormalon line 412) and excludedtypes.bfloat16in_testParameterizedTruncatedNormalandtestParameterizedTruncatedNormalExtremeNormalizedBounds:
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))- Include
<initializer_list>intensorflow/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 usesstd::initializer_list<double>. Include<initializer_list>directly instead of relying on transitive headers:
#include <cmath>
#include <initializer_list>- Update the Newton loop comment in
tensorflow/compiler/tf2xla/lib/random.cc(line 136):
Line 136 still mentionslog_q, which was removed whendeltawas 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);|
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. |
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.
af6e4f5 to
c0b246f
Compare
aad13d4
into
tensorflow:master
Why
stateless_parameterized_truncated_normalunder 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]return6.0for every element withjit_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). Useerfcbelow 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
ndtriin 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_normalrejects it.Evidence
Fail-before (new tests on unfixed
random.cc):testParameterizedTruncatedNormalFarRightTailFAILEDtestParameterizedTruncatedNormalFarLeftTailFAILEDPass-after (full fix):
//tensorflow/compiler/tests:stateless_random_ops_test_cpuLogs: worktree
evidence/fail-before.logandevidence/pass-after.log.