cjd_flows.radial

Lp-radial base distributions with learnable 1-D norm (radius) distributions.

A radial base p(z) = h(||z - loc||_p) is described by the law of its radius R; h(r) = p_R(r) / (d V_p r^{d-1}). Learning the 1-D law of R closes the expressivity gap of constant-Jacobian flows with a fixed base (cf. the non-universality result of Draxler et al., ICML 2024), and monotone profiles make every density level set an Lp ball (see cjd_flows.radial.levelsets).

Example:

from cjd_flows.radial import RadialBase, KhinchineNorm
base = RadialBase((784,), p=2.0)                       # learnable GG norm, init = N(0, I)
base = RadialBase((784,), p=1.0, norm=KhinchineNorm(784, 1.0))  # monotone by construction

The main classes are also importable from cjd_flows.radial.

Radial base distributions

Lp-radial base distributions and multi-centre radial mixtures.

class cjd_flows.radial.base.RadialBase[source]

Bases: BaseDistribution

Lp-radial distribution p(z) = h(||z - loc||_p) with a learnable norm law.

Z = loc + R · U with R ~ norm and U uniform on the Lp unit sphere w.r.t. the cone measure; h(r) = p_R(r) / (d V_p r^{d-1}).

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – event shape, d = prod(event_shape).

  • p (float) – norm exponent (p > 0 or inf).

  • norm (Optional[NormDistribution]) – distribution of R (built for the same d and p). Default: learnable GeneralizedGamma initialized at the reference law (standard normal for p = 2).

  • loc (Optional[Tensor]) – centre (default zeros).

  • learn_loc (bool) – make the centre a parameter.

__init__(event_shape, p=2.0, norm=None, loc=None, learn_loc=False)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
classmethod gaussian(event_shape, learnable=False)[source]

Standard normal as chi(d) norm with p = 2 (exact).

Return type:

RadialBase

Parameters:
classmethod laplace(event_shape, learnable=False)[source]

Product of standard Laplace distributions (p = 1, R ~ Gamma(d, 1)).

Return type:

RadialBase

Parameters:
classmethod generalized_gaussian(event_shape, p, learnable=False)[source]

Product of generalized normals ∝ exp(-|z_i|^p / p) (finite p).

Return type:

RadialBase

Parameters:
norm_of(z)[source]

||z - loc||_p over the event dimensions.

Return type:

Tensor

Parameters:

z (Tensor)

log_profile(r)[source]

log h(r) – the log-density at any point with ||z - loc||_p = r.

Return type:

Tensor

Parameters:

r (Tensor)

is_monotone()[source]

Whether the profile is non-increasing (upper level sets are Lp balls).

Return type:

bool

rsample(sample_shape=())[source]

Samples, differentiable w.r.t. loc and the norm parameters.

Return type:

Tensor

Parameters:

sample_shape (int | Sequence[int] | Size)

class cjd_flows.radial.base.RadialMixture[source]

Bases: BaseDistribution

Mixture of K Lp-radial distributions with distinct learnable centres.

p(z) = Σ_k π_k h_k(||z - μ_k||_p) (exact log_prob via logsumexp).

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – event shape.

  • n_components (Optional[int]) – K (required if norms is not given).

  • p (float) – norm exponent shared by all components.

  • norms (Optional[Sequence[NormDistribution]]) – per-component norm distributions (default: independent learnable GeneralizedGamma at the reference law).

  • locs (Optional[Tensor]) – initial centres (K, *event_shape) (default init_scale * randn).

  • weights (Optional[Sequence[float]]) – initial mixture weights (default uniform).

  • learn_locs (bool) – learn the centres.

  • learn_weights (bool) – learn the mixture weights.

  • init_scale (float) – scale of the random initial centres.

__init__(event_shape, n_components=None, p=2.0, norms=None, locs=None, weights=None, learn_locs=True, learn_weights=True, init_scale=1.0)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
component_norms(z)[source]

||z - μ_k||_p of shape (..., K).

Return type:

Tensor

Parameters:

z (Tensor)

component_log_prob(z)[source]

log h_k(||z - μ_k||_p) (without weights), shape (..., K).

Return type:

Tensor

Parameters:

z (Tensor)

responsibilities(z)[source]

Posterior component probabilities (..., K).

Return type:

Tensor

Parameters:

z (Tensor)

rsample(sample_shape=())[source]

Samples, reparameterized w.r.t. centres and norm parameters (not the weights).

Return type:

Tensor

Parameters:

sample_shape (int | Sequence[int] | Size)

is_monotone()[source]

Whether every component profile is non-increasing.

Return type:

bool

level_set_sandwich(log_t)[source]

Per-component ball radii sandwiching the upper level set {p ≥ t}.

With B_k(ρ) = {z : ||z - μ_k||_p ≤ ρ}:

∪_k B_k(inner_k)  ⊆  {p ≥ t}  ⊆  ∪_k B_k(outer_k)

where inner_k solves π_k h_k(ρ) = t and outer_k solves π_k h_k(ρ) = t / K (since p ≥ π_k h_k and p ≤ K max_k π_k h_k). Requires monotone component profiles. A radius of 0 denotes an empty ball.

Parameters:

log_t (Union[float, Tensor]) – log-density threshold log t.

Return type:

Tuple[Tensor, Tensor]

Returns:

(inner, outer), each of shape (K,).

Norm distributions

Learnable 1-D distributions of the radius R = ||Z - loc||_p.

Every family is a NormDistribution, i.e. an nn.Module that knows the ambient dimension d and norm exponent p and provides

  • log_prob(r) / log_prob_log_radius(s) (density of R resp. log R),

  • log_profile(r) = log h(r), the log-density of the d-dimensional radial distribution at any point of norm r,

  • sample / rsample (reparameterized w.r.t. all parameters except mixture weights), cdf, icdf,

  • profile_is_monotone(d) – whether h is non-increasing, i.e. whether upper density level sets are balls.

Parametrization conventions

  • All parameters are unconstrained (log/softplus/logits).

  • Families are initialized relative to the reference law of reference_log_radius() (chi(d) for p = 2, Gamma(d, 1) for p = 1), so the default works for any d. Location-type parameters (log-scales) are stored in standardized units u with location = center + s0 * u where s0 ≈ 1/sqrt(β d) is the reference standard deviation of log R; one unit of u is one natural “radial standard deviation” regardless of d.

  • learn_scale=False fixes the overall scale of the radius (it is redundant with the global log-determinant of a flow). Mixtures keep the relative offsets of the components learnable but pin their mean.

class cjd_flows.radial.norms.NormDistribution[source]

Bases: Module

Base class for distributions of the radius R on (0, ∞).

Subclasses implement log_prob_log_radius(), rsample() and log_radius_bounds(); exact cdf() / icdf() / log_profile_log_radius() overrides are optional (the defaults use a tabulated density on the log-radius axis and bisection).

Parameters:
  • d (int) – ambient dimension of the radial distribution.

  • p (float) – exponent of the Lp norm (p > 0 or inf).

grid_size: int = 4096

Number of nodes of the default log-radius quadrature grid.

__init__(d, p=2.0)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
log_prob_log_radius(s)[source]

Log-density of S = log R at s.

Return type:

Tensor

Parameters:

s (Tensor)

log_prob(r)[source]

Log-density of R at r > 0 (any shape).

Return type:

Tensor

Parameters:

r (Tensor)

log_profile_log_radius(s, d=None)[source]

log h(e^s) – log-density of the radial distribution at norm e^s.

h(r) = p_R(r) / (d V_p r^{d-1}). d defaults to self.d.

Return type:

Tensor

Parameters:
log_profile(r)[source]

log h(r) – the log-density of the d-dimensional radial distribution at norm r.

Return type:

Tensor

Parameters:

r (Tensor)

log_prob_volume(t)[source]

Log-density of the volume coordinate T = V_p R^d (equals log h(r)).

Return type:

Tensor

Parameters:

t (Tensor)

forward(r)[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

r (Tensor)

rsample(sample_shape=())[source]

Reparameterized samples of shape sample_shape.

Return type:

Tensor

Parameters:

sample_shape (int | Sequence[int] | Size)

sample(sample_shape=())[source]

Samples of shape sample_shape (no gradient).

Return type:

Tensor

Parameters:

sample_shape (int | Sequence[int] | Size)

log_radius_bounds()[source]

Interval [lo, hi] of log R that contains all but ~1e-12 of the mass.

Return type:

Tuple[float, float]

grid_table(n=None)[source]

Tabulated density of log R on a uniform grid over log_radius_bounds().

Return type:

GridTable

Parameters:

n (int | None)

cdf(r)[source]

P(R <= r).

Return type:

Tensor

Parameters:

r (Tensor)

icdf(q)[source]

Quantile function (inverse of cdf()).

Return type:

Tensor

Parameters:

q (Tensor)

profile_is_monotone(d=None)[source]

Whether the radial profile h (in dimension d) is non-increasing.

The default is a numerical check on the support grid.

Return type:

bool

Parameters:

d (int | None)

extra_repr()[source]

Return the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

Return type:

str

class cjd_flows.radial.norms.GeneralizedGammaMixture[source]

Bases: NormDistribution

Mixture of generalized gamma (Stacy) distributions.

Component density (shape a, power β, scale θ):

p(r) = β / (θ Γ(a/β)) (r/θ)^{a-1} exp(-(r/θ)^β),   R = θ G^{1/β}, G ~ Gamma(a/β).

Special cases: Gamma (β = 1), Weibull (a = β), chi (a = d, β = 2, θ = sqrt 2), Lp-generalized-normal radius (a = d, β = p, θ = p^{1/p}). The radial profile of a component is h(r) ∝ r^{a-d} exp(-(r/θ)^β): it is monotone iff a ≤ d and bounded at 0 iff a ≥ d. monotone=True ties a = d for all components (bounded and monotone).

Parameters:
  • d (int) – dimension.

  • p (float) – norm exponent.

  • n_components (int) – number of components K.

  • a (Union[float, Sequence[float], None]) – initial values (scalars or length-K). Defaults give the reference law (a = d, β = p or 2 for p = inf, θ = β^{1/β}).

  • beta (Union[float, Sequence[float], None]) – initial values (scalars or length-K). Defaults give the reference law (a = d, β = p or 2 for p = inf, θ = β^{1/β}).

  • theta (Union[float, Sequence[float], None]) – initial values (scalars or length-K). Defaults give the reference law (a = d, β = p or 2 for p = inf, θ = β^{1/β}).

  • weights (Optional[Sequence[float]]) – initial mixture weights (default uniform).

  • monotone (bool) – tie a = d.

  • learn_shape (bool) – learn a and β.

  • learn_scale (bool) – learn the global scale (mean of log θ_k).

  • learn_weights (bool) – learn the mixture weights.

  • spread (float) – initial spread of the components’ log θ in reference standard deviations (u_k = spread * linspace(-1, 1, K)).

__init__(d, p=2.0, n_components=1, a=None, beta=None, theta=None, weights=None, monotone=False, learn_shape=True, learn_scale=True, learn_weights=True, spread=1.0)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
property log_theta: Tensor

log θ_k of shape (K,).

log_prob_log_radius(s)[source]

Log-density of S = log R at s.

Return type:

Tensor

Parameters:

s (Tensor)

log_profile_log_radius(s, d=None)[source]

log h(e^s) – log-density of the radial distribution at norm e^s.

h(r) = p_R(r) / (d V_p r^{d-1}). d defaults to self.d.

Return type:

Tensor

Parameters:
cdf(r)[source]

P(R <= r).

Return type:

Tensor

Parameters:

r (Tensor)

icdf(q)[source]

Quantile function (inverse of cdf()).

Return type:

Tensor

Parameters:

q (Tensor)

rsample(sample_shape=())[source]

Reparameterized samples of shape sample_shape.

Return type:

Tensor

Parameters:

sample_shape (int | Sequence[int] | Size)

log_radius_bounds()[source]

Interval [lo, hi] of log R that contains all but ~1e-12 of the mass.

Return type:

Tuple[float, float]

profile_is_monotone(d=None)[source]

Whether the radial profile h (in dimension d) is non-increasing.

The default is a numerical check on the support grid.

Return type:

bool

Parameters:

d (int | None)

class cjd_flows.radial.norms.GeneralizedGamma[source]

Bases: GeneralizedGammaMixture

Single generalized gamma (Stacy) norm distribution GG(a, β, θ).

The default (a = d, β = p, θ = p^{1/p}; β = 2 for p = inf) is the norm law of the Lp-generalized normal p(z) ∝ exp(-||z||_p^β / β), e.g. chi(d) for p = 2. monotone=True ties a = d.

__init__(d, p=2.0, a=None, beta=None, theta=None, monotone=False, learn_shape=True, learn_scale=True)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
class cjd_flows.radial.norms.GammaMixture[source]

Bases: GeneralizedGammaMixture

Mixture of Gamma distributions (β = 1 fixed).

The radial profile of Gamma(k, θ) is monotone iff k ≤ d and bounded iff k ≥ d (monotone=True ties k = d, i.e. Laplace-type profiles exp(-r/θ)). By default the shape is moment-matched to the reference law of log R (which gives k ≈ 2d for p = 2, a shell profile).

__init__(d, p=2.0, n_components=1, shape=None, scale=None, weights=None, monotone=False, learn_shape=True, learn_scale=True, learn_weights=True, spread=1.0)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
class cjd_flows.radial.norms.WeibullMixture[source]

Bases: GeneralizedGammaMixture

Mixture of Weibull distributions (a = β = k).

The profile h ∝ r^{k-d} exp(-(r/λ)^k) is monotone iff k ≤ d; monotone=True parametrizes k = d · sigmoid(raw). The default shape matches the reference standard deviation of log R (k = π / (sqrt 6 s0)).

__init__(d, p=2.0, n_components=1, shape=None, scale=None, weights=None, monotone=False, learn_shape=True, learn_scale=True, learn_weights=True, spread=1.0)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
profile_is_monotone(d=None)[source]

Whether the radial profile h (in dimension d) is non-increasing.

The default is a numerical check on the support grid.

Return type:

bool

Parameters:

d (int | None)

class cjd_flows.radial.norms.LogNormalMixture[source]

Bases: NormDistribution

Mixture of log-normal distributions, log R ~ Σ π_k N(μ_k, σ_k²).

Never monotone: p_R vanishes faster than any power of r at 0, so h(r) -> 0 as r -> 0 and the profile is a “shell”. Upper density level sets are then annuli, not balls. Default: one component matching the reference mean and standard deviation of log R.

Parameters:
  • d (int) – dimension and norm exponent.

  • p (float) – dimension and norm exponent.

  • n_components (int) – number of components.

  • loc (Union[float, Sequence[float], None]) – initial μ_k (absolute, in log-radius units).

  • scale (Union[float, Sequence[float], None]) – initial σ_k.

  • weights (Optional[Sequence[float]]) – initial mixture weights.

  • learn_scale (bool) – learn the global location (mean of μ_k).

  • learn_shape (bool) – learn σ_k.

  • learn_weights (bool) – learn the mixture weights.

  • spread (float) – initial spread of μ_k in reference standard deviations.

__init__(d, p=2.0, n_components=1, loc=None, scale=None, weights=None, learn_scale=True, learn_shape=True, learn_weights=True, spread=1.0)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
log_prob_log_radius(s)[source]

Log-density of S = log R at s.

Return type:

Tensor

Parameters:

s (Tensor)

cdf(r)[source]

P(R <= r).

Return type:

Tensor

Parameters:

r (Tensor)

icdf(q)[source]

Quantile function (inverse of cdf()).

Return type:

Tensor

Parameters:

q (Tensor)

rsample(sample_shape=())[source]

Reparameterized samples of shape sample_shape.

Return type:

Tensor

Parameters:

sample_shape (int | Sequence[int] | Size)

log_radius_bounds()[source]

Interval [lo, hi] of log R that contains all but ~1e-12 of the mass.

Return type:

Tuple[float, float]

profile_is_monotone(d=None)[source]

Whether the radial profile h (in dimension d) is non-increasing.

The default is a numerical check on the support grid.

Return type:

bool

Parameters:

d (int | None)

class cjd_flows.radial.norms.StudentTNorm[source]

Bases: NormDistribution

Norm law of the Lp-radial multivariate-t analogue (heavy tails, monotone).

Profile h(r) ∝ (1 + (r/θ)^β / ν)^{-(ν + d)/β} with β = p (2 for p = inf). With X = (R/θ)^β / ν one gets X ~ BetaPrime(d/β, ν/β), hence the exact normalizer:

log p_R(r) = α log x - (α + β') log(1 + x) - log B(α, β') + log β - log r,
α = d/β,  β' = ν/β.

Sampling: X = G1 / G2 with G1 ~ Gamma(α), G2 ~ Gamma(β') (reparameterized). ν -> ∞ recovers the reference-type profile exp(-(r/θ)^β / β). The default scale matches the reference mean of log R.

Parameters:
  • d (int) – dimension and norm exponent.

  • p (float) – dimension and norm exponent.

  • df (float) – degrees of freedom ν (initial value).

  • theta (Optional[float]) – initial scale (default: match the reference mean of log R).

  • learn_df (bool) – learn ν.

  • learn_scale (bool) – learn θ.

__init__(d, p=2.0, df=5.0, theta=None, learn_df=True, learn_scale=True)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
log_prob_log_radius(s)[source]

Log-density of S = log R at s.

Return type:

Tensor

Parameters:

s (Tensor)

log_profile_log_radius(s, d=None)[source]

log h(e^s) – log-density of the radial distribution at norm e^s.

h(r) = p_R(r) / (d V_p r^{d-1}). d defaults to self.d.

Return type:

Tensor

Parameters:
rsample(sample_shape=())[source]

Reparameterized samples of shape sample_shape.

Return type:

Tensor

Parameters:

sample_shape (int | Sequence[int] | Size)

log_radius_bounds()[source]

Interval [lo, hi] of log R that contains all but ~1e-12 of the mass.

Return type:

Tuple[float, float]

profile_is_monotone(d=None)[source]

Whether the radial profile h (in dimension d) is non-increasing.

The default is a numerical check on the support grid.

Return type:

bool

Parameters:

d (int | None)

class cjd_flows.radial.norms.KhinchineNorm[source]

Bases: NormDistribution

Radially decreasing law via Khinchine’s representation R = C · U^{1/d}.

Every radially decreasing density is a mixture of uniform distributions on Lp balls; here the ball radius C follows an arbitrary learnable NormDistribution mixing and U ~ Unif(0, 1). The profile h(r) = V_p^{-1} ∫_r^∞ c^{-d} m_C(c) dc is monotone by construction.

On the log axis log R = log C - E/d with E ~ Exp(1), so:

p_{log R}(s) = d ∫_s^∞ exp(-d (σ - s)) q(σ) dσ,   q = density of log C.

The integral is evaluated with the exponential-linear rule (log q interpolated linearly, exponential kernel integrated exactly; all in log space) on a uniform grid of n_grid nodes over the support of log C. Since exp(-d (σ - s)) = e^{d s} e^{-d σ}, the full-panel integrals are shared by all queries (suffix logcumsumexp); only the partial panel [s, σ_j] depends on the query, so the cost is O(n_grid + batch). Differentiable w.r.t. mixing’s parameters and the query; the error is second order in the grid spacing (≈1e-5 in log p with the default grid). The CDF has the closed form F_R(r) = F_C(r) + p_{log R}(log r) / d.

Default mixing: GG(a = d + β, β, β^{1/β}), for which R follows exactly the reference law (chi(d) for p = 2).

Parameters:
  • d (int) – dimension and norm exponent.

  • p (float) – dimension and norm exponent.

  • mixing (Optional[NormDistribution]) – distribution of the ball radius C (its d is irrelevant).

  • n_grid (int) – number of quadrature nodes over the support of log C.

__init__(d, p=2.0, mixing=None, n_grid=8192)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
log_prob_log_radius(s)[source]

Log-density of S = log R at s.

Return type:

Tensor

Parameters:

s (Tensor)

cdf(r)[source]

P(R <= r).

Return type:

Tensor

Parameters:

r (Tensor)

icdf(q)[source]

Quantile function (inverse of cdf()).

Return type:

Tensor

Parameters:

q (Tensor)

rsample(sample_shape=())[source]

Reparameterized samples of shape sample_shape.

Return type:

Tensor

Parameters:

sample_shape (int | Sequence[int] | Size)

log_radius_bounds()[source]

Interval [lo, hi] of log R that contains all but ~1e-12 of the mass.

Return type:

Tuple[float, float]

profile_is_monotone(d=None)[source]

Whether the radial profile h (in dimension d) is non-increasing.

The default is a numerical check on the support grid.

Return type:

bool

Parameters:

d (int | None)

class cjd_flows.radial.norms.SplineNorm[source]

Bases: NormDistribution

Normalizing flow on the standardized log-radius.

u = (log r - μ0) / s0 (reference mean/std of log R), then a learnable affine map v = (u - m) e^{-ℓ} and a monotone rational-quadratic spline y = g(v) on [-B, B] (identity outside) map to a standard normal (base="normal") or logistic (base="logistic") variable. Density by change of variables, sampling by the inverse spline. Initialized as the identity, i.e. log R ~ N(μ0, s0²) (the log-normal approximation of the reference law).

Monotonicity: with a normal base the left tail is log-normal, hence the profile is never monotone. With a logistic base p_R(r) ∝ r^{κ-1} near 0 with κ = e^{-ℓ}/s0; the profile is then monotone iff κ ≤ d and the profile is non-increasing on the support grid (checked numerically).

Parameters:
  • d (int) – dimension and norm exponent.

  • p (float) – dimension and norm exponent.

  • num_bins (int) – number of spline bins.

  • bound (float) – half-width B of the spline domain (in standardized units).

  • base (str) – "normal" or "logistic".

  • learn_scale (bool) – learn the affine map (m, ℓ).

__init__(d, p=2.0, num_bins=8, bound=5.0, base='normal', learn_scale=True)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
log_prob_log_radius(s)[source]

Log-density of S = log R at s.

Return type:

Tensor

Parameters:

s (Tensor)

cdf(r)[source]

P(R <= r).

Return type:

Tensor

Parameters:

r (Tensor)

icdf(q)[source]

Quantile function (inverse of cdf()).

Return type:

Tensor

Parameters:

q (Tensor)

rsample(sample_shape=())[source]

Reparameterized samples of shape sample_shape.

Return type:

Tensor

Parameters:

sample_shape (int | Sequence[int] | Size)

log_radius_bounds()[source]

Interval [lo, hi] of log R that contains all but ~1e-12 of the mass.

Return type:

Tuple[float, float]

profile_is_monotone(d=None)[source]

Whether the radial profile h (in dimension d) is non-increasing.

The default is a numerical check on the support grid.

Return type:

bool

Parameters:

d (int | None)

cjd_flows.radial.norms.LogRadiusFlow

Alias: a 1-D flow on the standardized log-radius.

class cjd_flows.radial.norms.MonotoneProfileNorm[source]

Bases: NormDistribution

Radial law with a directly parametrized, non-increasing profile.

-log h(r) = φ(r) + const with the increasing function:

φ(r) = (r/θ)^β + κ Σ_k softplus(α_k) w softplus((u - c_k) / w),
u = (log r - μ0) / s0,

i.e. a generalized-normal baseline plus non-negative combinations of softplus ramps in the standardized log-radius (κ = d s0 is the natural slope of φ near the typical radius). The ramps start at α_k = -20 so the initial law is the reference one. The normalizer ∫ exp(-φ(r)) r^{d-1} dr is computed by the exponential-linear rule on a grid in log r that is adapted (without gradient) to the region holding the mass; sampling inverts the tabulated CDF (differentiable).

Parameters:
  • d (int) – dimension and norm exponent.

  • p (float) – dimension and norm exponent.

  • n_ramps (int) – number of softplus ramps K.

  • ramp_range (Tuple[float, float]) – range of the ramp centres c_k in standardized units.

  • n_grid (int) – number of quadrature nodes.

  • beta (Optional[float]) – initial baseline power and scale (default: reference).

  • theta (Optional[float]) – initial baseline power and scale (default: reference).

  • learn_scale (bool) – learn θ.

  • learn_shape (bool) – learn β.

__init__(d, p=2.0, n_ramps=16, ramp_range=(-6.0, 6.0), n_grid=4096, beta=None, theta=None, learn_scale=True, learn_shape=True)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
phi(s)[source]

φ(e^s) (increasing in s).

Return type:

Tensor

Parameters:

s (Tensor)

grid_table(n=None)[source]

Tabulated density of log R on a uniform grid over log_radius_bounds().

Return type:

GridTable

Parameters:

n (int | None)

log_normalizer()[source]

log ∫ exp(-φ(r)) r^{d-1} dr.

Return type:

Tensor

log_prob_log_radius(s)[source]

Log-density of S = log R at s.

Return type:

Tensor

Parameters:

s (Tensor)

log_profile_log_radius(s, d=None)[source]

log h(e^s) – log-density of the radial distribution at norm e^s.

h(r) = p_R(r) / (d V_p r^{d-1}). d defaults to self.d.

Return type:

Tensor

Parameters:
cdf(r)[source]

P(R <= r).

Return type:

Tensor

Parameters:

r (Tensor)

log_radius_bounds()[source]

Interval [lo, hi] of log R that contains all but ~1e-12 of the mass.

Return type:

Tuple[float, float]

profile_is_monotone(d=None)[source]

Whether the radial profile h (in dimension d) is non-increasing.

The default is a numerical check on the support grid.

Return type:

bool

Parameters:

d (int | None)

cjd_flows.radial.norms.fit_norm_to_radii(norm, radii, steps=500, lr=1e-2, optimizer='adam', batch_size=None)[source]

Maximum-likelihood refit of a norm distribution to observed radii.

Typical use: after training a flow, refit the base’s norm law to the latent norms ||f(x) - loc||_p of the training data (a cheap post-hoc 1-D correction of the base; joint training of the norm distribution is the default).

Parameters:
  • norm (NormDistribution) – the norm distribution (modified in place).

  • radii (Tensor) – 1-D tensor of observed radii.

  • steps (int) – optimization steps (Adam steps, or LBFGS iterations).

  • lr (float) – learning rate.

  • optimizer (str) – "adam" or "lbfgs" (full batch).

  • batch_size (Optional[int]) – mini-batch size for Adam (default: full batch).

Return type:

List[float]

Returns:

List of the per-step mean negative log-likelihoods.

Level sets

Density level sets and highest-density regions of radial distributions.

For a radial density p(z) = h(||z - loc||_p) with a monotone (non-increasing) profile h, every upper density level set (UDL) {z : p(z) ≥ t} is an Lp ball around loc. Hence

  • the UDL of probability mass q is the ball of radius F_R^{-1}(q),

  • the mass of the region that is more likely than z is F_R(||z||) (Uniform(0, 1) under the model; 1 - F_R(||z||) is the anomaly p-value).

For non-monotone (“shell”) profiles UDLs are unions of annuli; these are computed on a log-radius grid by udl_intervals(). Since flows in this library have a constant Jacobian determinant, these sets map back to exact density level sets in data space.

cjd_flows.radial.levelsets.udl_radius(base, q, check_monotone=True)[source]

Radius r_q with P(||Z - loc|| ≤ r_q) = q.

For a monotone profile the ball of radius r_q is the upper density level set (= highest density region) of mass q.

Return type:

Tensor

Parameters:
cjd_flows.radial.levelsets.hdr_pvalue(base, z, n_grid=65536)[source]

Mass of the region that is more likely than z: P(h(R) ≥ h(||z||)).

For a monotone profile this is exactly F_R(||z - loc||_p). For shell profiles it is computed on a log-radius grid. Under the model the result is Uniform(0, 1); large values indicate atypical points.

Parameters:
  • base (Union[RadialBase, NormDistribution]) – a RadialBase (z are points) or a NormDistribution (z are radii).

  • z (Tensor) – points (B, *event_shape) or radii.

  • n_grid (int) – grid size for non-monotone profiles.

Return type:

Tensor

cjd_flows.radial.levelsets.density_threshold_radius(base, log_density_threshold)[source]

Radius ρ with log h(ρ) = log_density_threshold (monotone profiles).

{z : log p(z) ≥ threshold} is the ball of radius ρ around loc. Returns 0 if the threshold exceeds sup h (empty set). Vectorized over thresholds (bisection in log r, no gradient).

Return type:

Tensor

Parameters:
cjd_flows.radial.levelsets.udl_log_threshold(base, q, n_grid=65536)[source]

Log-density threshold log t_q whose upper level set has mass q.

Return type:

Tensor

Parameters:
cjd_flows.radial.levelsets.udl_intervals(base, q=None, log_threshold=None, n_grid=65536)[source]

Upper density level set as a union of radial intervals (any profile).

Exactly one of q (probability mass) or log_threshold (log-density threshold) must be given. The set {r : log h(r) ≥ threshold} is computed on a uniform log-radius grid over the support (resolution (hi - lo) / n_grid in log r); fully vectorized.

Return type:

Tensor

Returns:

Tensor (M, 2) of disjoint intervals [a_m, b_m] of radii (M = 0 for an empty set). An interval reaching the lower end of the support starts at 0.

Parameters:

Geometry

Geometry of Lp balls and spheres.

For p > 0 (including p = inf) the Lp unit ball in R^d has volume

V_p = (2 Γ(1 + 1/p))^d / Γ(1 + d/p), V_inf = 2^d,

and the “sphere measure” of radius r (the derivative of the ball volume V_p r^d) is d V_p r^{d-1}. A radial density p(z) = h(||z||_p) therefore induces the norm density p_R(r) = h(r) d V_p r^{d-1}. All quantities are computed in log space with lgamma.

Reference law

Every norm family in cjd_flows.radial.norms is initialized relative to the norm law of a reference distribution p(z) ∝ exp(-||z||_p^β / β) with β = p for finite p and β = 2 for p = inf. For p = 2 this is the standard normal (R ~ chi(d)), for p = 1 the standard Laplace product distribution (R ~ Gamma(d, 1)). Its radius is R = (β G)^{1/β} with G ~ Gamma(d/β), so log R has mean (log β + ψ(d/β)) / β and standard deviation sqrt(ψ'(d/β)) / β (≈ (1/β) log d and ≈ 1/sqrt(β d) in high dimensions).

cjd_flows.radial.geometry.reference_exponent(p)[source]

Exponent β of the reference profile exp(-r^β/β) (p, or 2 for p = inf).

Return type:

float

Parameters:

p (float)

cjd_flows.radial.geometry.reference_log_radius(d, p)[source]

Mean and standard deviation of log ||Z||_p under the reference law.

Parameters:
  • d (int) – dimension.

  • p (float) – norm exponent.

Return type:

Tuple[float, float]

Returns:

(mu0, s0) as Python floats.

cjd_flows.radial.geometry.log_unit_ball_volume(d, p)[source]

log V_p – log-volume of the Lp unit ball in R^d.

Return type:

float

Parameters:
cjd_flows.radial.geometry.log_sphere_measure(d, p, r)[source]

log(d V_p r^{d-1}) – log of the Lp “surface” measure at radius r.

r^{d-1} is never formed; r is clamped to the smallest positive normal number.

Return type:

Tensor

Parameters:
cjd_flows.radial.geometry.lp_norm(z, p, event_ndim=1)[source]

Lp norm over the last event_ndim dimensions.

For p ∉ {1, 2, inf} the input is rescaled by its max-abs entry to avoid overflow of |z|^p.

Return type:

Tensor

Parameters:
cjd_flows.radial.geometry.sample_unit_sphere(n, event_shape, p, device=None, dtype=None)[source]

Samples n points on the Lp unit sphere w.r.t. the cone measure.

The cone measure is the law of Z / ||Z||_p for any Lp-radial Z (it is not the surface measure unless p ∈ {2, inf}).

  • p = 2: normalized Gaussian vectors.

  • finite p: |z_i|^p ~ Gamma(1/p) with a random sign (i.e. z_i has density ∝ exp(-|z_i|^p)), normalized by ||z||_p. Computed in log space, so arbitrary p works without under/overflow.

  • p = inf: uniform on the surface of the cube [-1, 1]^d: one face coordinate and its sign are chosen uniformly, the other coordinates are uniform on [-1, 1].

Return type:

Tensor

Returns:

Tensor of shape (n, *event_shape).

Parameters:

Splines

Monotone rational-quadratic splines (Durkan et al., 2019) for scalar inputs.

The spline maps [-B, B] onto itself and is the identity outside (linear tails with unit slope; the boundary derivatives are fixed to 1).

cjd_flows.radial.splines.identity_derivative_init(min_derivative=DEFAULT_MIN_DERIVATIVE)[source]

Unnormalized derivative value for which the spline derivative equals one.

Return type:

float

Parameters:

min_derivative (float)

cjd_flows.radial.splines.rq_spline(x, unnorm_widths, unnorm_heights, unnorm_derivatives, bound, inverse=False, min_width=DEFAULT_MIN_WIDTH, min_height=DEFAULT_MIN_HEIGHT, min_derivative=DEFAULT_MIN_DERIVATIVE)[source]

Applies a 1-D monotone RQ spline element-wise.

Parameters:
  • x (Tensor) – inputs of any shape.

  • unnorm_widths (Tensor) – (K,) bin width logits.

  • unnorm_heights (Tensor) – (K,) bin height logits.

  • unnorm_derivatives (Tensor) – (K - 1,) interior knot derivatives (pre-softplus).

  • bound (float) – half-width B of the spline interval.

  • inverse (bool) – apply the inverse map.

  • min_width (float)

  • min_height (float)

  • min_derivative (float)

Return type:

Tuple[Tensor, Tensor]

Returns:

(y, log_abs_det) where log_abs_det = log|dy/dx| of the map that was applied (forward or inverse), element-wise.