Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

float precision check in rational quadratic spline discriminant #71

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions nflows/transforms/splines/rational_quadratic.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,16 @@ def rational_quadratic_spline(
c = -input_delta * (inputs - input_cumheights)

discriminant = b.pow(2) - 4 * a * c

# Correcting for floating-point errors in the discriminant calculation.
# The float_precision_mask identifies elements where the discriminant is essentially zero,
# compared to the magnitude of b.pow(2),
# but appears nonzero due to machine precision limitations.
# Threshold values (1e-8 and 1e-6) are heuristic-based to manage numerical stability.
float_precision_mask = (torch.abs(discriminant) / (b.pow(2) + 1e-8)) < 1e-6
discriminant = torch.where(float_precision_mask,
torch.zeros_like(discriminant), discriminant)

assert (discriminant >= 0).all()

root = (2 * c) / (-b - torch.sqrt(discriminant))
Expand Down