Skip to content

Utilities

These helpers keep fuzzy computations away from numerical singularities, such as the logarithm of zero, by clamping to a margin. The clamp moves exact boundary values and changes gradients (PyTorch Contributors, 2021) near them, which matters when a model distinguishes impossible events from very unlikely ones or learns morphism parameters. They are importable from quivers.core, and the default margin EPS is documented on the core overview.

_util

Numerical utilities for stable fuzzy-logic operations.

clamp_probs

clamp_probs(x: Tensor, eps: float = EPS) -> Tensor

Clamp tensor values to the open interval (eps, 1 - eps).

PARAMETER DESCRIPTION
x

Input tensor with values nominally in [0, 1].

TYPE: Tensor

eps

Clamping margin.

TYPE: float DEFAULT: EPS

RETURNS DESCRIPTION
Tensor

Clamped tensor.

Source code in src/quivers/core/_util.py
def clamp_probs(x: torch.Tensor, eps: float = EPS) -> torch.Tensor:
    """Clamp tensor values to the open interval (eps, 1 - eps).

    Parameters
    ----------
    x : torch.Tensor
        Input tensor with values nominally in [0, 1].
    eps : float
        Clamping margin.

    Returns
    -------
    torch.Tensor
        Clamped tensor.
    """
    return x.clamp(min=eps, max=1.0 - eps)

safe_log1p_neg

safe_log1p_neg(x: Tensor, eps: float = EPS) -> Tensor

Compute log(1 - x) in a numerically stable way.

Uses torch.log1p(-x) after clamping x away from 1.

PARAMETER DESCRIPTION
x

Input tensor with values in [0, 1].

TYPE: Tensor

eps

Clamping margin.

TYPE: float DEFAULT: EPS

RETURNS DESCRIPTION
Tensor

log(1 - x), with values in (-inf, 0].

Source code in src/quivers/core/_util.py
def safe_log1p_neg(x: torch.Tensor, eps: float = EPS) -> torch.Tensor:
    """Compute log(1 - x) in a numerically stable way.

    Uses torch.log1p(-x) after clamping x away from 1.

    Parameters
    ----------
    x : torch.Tensor
        Input tensor with values in [0, 1].
    eps : float
        Clamping margin.

    Returns
    -------
    torch.Tensor
        log(1 - x), with values in (-inf, 0].
    """
    return torch.log1p(-clamp_probs(x, eps))

Cited sources

PyTorch Contributors. Automatic differentiation with torch.autograd. PyTorch Tutorials, 2021. Created February 10, 2021; updated January 16, 2024. URL: https://docs.pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html (visited on 2026-11-06).