Skip to content

API Reference

binned_cdf.bezier_cdf

BezierCDF

Bases: Distribution

A continuous probability distribution represented by a global parametric Bezier curve.

The idea is that the CDF is represented as a Bezier curve, which is a weighted sum of Bernstein basis polynomials, defined by control points (betas) that are derived from the input logits. This allows for a smooth, flexible CDF that can capture complex shapes while still being differentiable. With two learned axes, this is a global parametric curve. Its vertical derivative defines a mixture of Beta densities in parameter space, with mixture weights given by the normalized vertical increments (deltas).

Normalized, positive increments define monotone control points on each axis, with endpoints fixed at 0 and 1. For \(t \in [0, 1]\),

\[ x(t) = L + (U-L) B_x(t), \qquad F(x(t)) = B_y(t) \]

so

\[ p(x(t)) = \frac{B_y'(t)}{(U-L) B_x'(t)}. \]

The two polynomials may have different degrees. Omitting logits_x, passing None, or supplying a one-element logits_x fixes the horizontal curve to

\[ B_x(t) = t. \]

Learning multiple horizontal increments allows density to concentrate without increasing the vertical polynomial degree, but CDF and density evaluation then require numerical inversion. Quantiles only invert the vertical curve.

Inversion uses bracketed Newton steps and implicit first-order gradients, without retaining the solver graph. No application-level minimum increment is imposed; extremely concentrated curves remain limited by the input dtype's precision. Higher-order derivatives through the implicit inverse are not supported.

Note

Monotone control points provide the structural guarantees of a CDF: monotonicity, values in \([0, 1]\), and a non-negative PDF. In exact arithmetic, normalizing positive increments gives these guarantees for any finite logits, without imposing constraints on the parameters during optimization.

With fixed horizontal spacing, the density is a Beta mixture on the normalized support. Classical Bernstein approximation has uniform error \(O(1/n)\) for functions with a bounded second derivative; this is not a general convergence rate for an end-to-end learned two-axis model. A degree-\(n\) mixture component near the center of a fixed support of width \(R\) has approximate standard deviation

\[ std \approx \frac{R}{2\sqrt{n}}. \]

This explains the smoothing of narrow interior peaks with fixed spacing. It is not a universal minimum width: boundary components can be narrower, and learned horizontal spacing can further compress peaks.

Source code in binned_cdf/bezier_cdf.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
class BezierCDF(Distribution):
    r"""A continuous probability distribution represented by a global parametric Bezier curve.

    The idea is that the CDF is represented as a Bezier curve, which is a weighted sum of Bernstein basis
    polynomials, defined by control points (betas) that are derived from the input logits.
    This allows for a smooth, flexible CDF that can capture complex shapes while still being differentiable.
    With two learned axes, this is a global parametric curve. Its vertical derivative defines a mixture of Beta
    densities in parameter space, with mixture weights given by the normalized vertical increments (deltas).

    Normalized, positive increments define monotone control points on each axis, with endpoints fixed at 0 and 1.
    For $t \in [0, 1]$,

    $$ x(t) = L + (U-L) B_x(t), \qquad F(x(t)) = B_y(t) $$

    so

    $$ p(x(t)) = \frac{B_y'(t)}{(U-L) B_x'(t)}. $$

    The two polynomials may have different degrees. Omitting `logits_x`, passing `None`, or supplying
    a one-element `logits_x` fixes the horizontal curve to

    $$ B_x(t) = t. $$

    Learning multiple horizontal increments allows density to concentrate without increasing the vertical
    polynomial degree, but CDF and density evaluation then require numerical inversion. Quantiles only invert
    the vertical curve.

    Inversion uses bracketed Newton steps and implicit first-order gradients, without retaining the solver graph.
    No application-level minimum increment is imposed; extremely concentrated curves remain limited by the input
    dtype's precision. Higher-order derivatives through the implicit inverse are not supported.

    Note:
        Monotone control points provide the structural guarantees of a CDF: monotonicity, values in $[0, 1]$,
        and a non-negative PDF. In exact arithmetic, normalizing positive increments gives these guarantees
        for any finite logits, without imposing constraints on the parameters during optimization.

        With fixed horizontal spacing, the density is a Beta mixture on the normalized support. Classical
        Bernstein approximation has uniform error $O(1/n)$ for functions with a bounded second derivative;
        this is not a general convergence rate for an end-to-end learned two-axis model. A degree-$n$ mixture
        component near the center of a fixed support of width $R$ has approximate standard deviation

        $$ std \approx \frac{R}{2\sqrt{n}}. $$

        This explains the smoothing of narrow interior peaks with fixed spacing. It is not a universal minimum
        width: boundary components can be narrower, and learned horizontal spacing can further compress peaks.
    """

    has_rsample = True

    def __init__(
        self,
        logits_y: torch.Tensor,
        logits_x: torch.Tensor | None = None,
        bound_low: float = -1e3,
        bound_up: float = 1e3,
        normalization_method: Literal["sigmoid", "softmax"] = "softmax",
        validate_args: bool | None = None,
    ) -> None:
        """Initializer.

        Args:
            logits_y: Raw vertical-increment logits, of shape (*batch_shape, degree_y).
            logits_x: Raw horizontal-increment logits, of shape (*batch_shape, degree_x). Batch shapes must
                broadcast with logits_y, and both tensors must have the same floating dtype and device.
                None uses a one-element zero tensor matching logits_y, fixing the horizontal map to the identity.
            bound_low: Lower bound of the distribution support, needs to be finite.
            bound_up: Upper bound of the distribution support, needs to be finite.
            normalization_method: How to normalize the probabilities. Either "sigmoid" or "softmax". With "sigmoid",
                each control point is independently activated, while with "softmax", the control point activations
                influence each other.
            validate_args: Whether to validate arguments. Carried over to keep the interface with the base class.
        """
        if not math.isfinite(bound_low) or not math.isfinite(bound_up) or bound_low >= bound_up:
            raise ValueError("Bounds must be finite with bound_low < bound_up.")
        if logits_y.ndim < 1 or logits_y.shape[-1] < 1 or not logits_y.is_floating_point():
            raise ValueError("logits_y must be a floating tensor with at least one increment.")
        if logits_x is not None and (logits_x.ndim < 1 or logits_x.shape[-1] < 1 or not logits_x.is_floating_point()):
            raise ValueError("logits_x must be None or a floating tensor with at least one increment.")
        if logits_x is not None and (logits_x.dtype != logits_y.dtype or logits_x.device != logits_y.device):
            raise ValueError("logits_x and logits_y must have the same floating dtype and device.")

        logits_x = logits_y.new_zeros(1) if logits_x is None else logits_x
        batch_shape = torch.broadcast_shapes(logits_y.shape[:-1], logits_x.shape[:-1])
        self.logits_y = logits_y.expand(*batch_shape, logits_y.shape[-1])
        self.logits_x = logits_x.expand(*batch_shape, logits_x.shape[-1])
        self.bound_low = bound_low
        self.bound_up = bound_up
        self.normalization_method = normalization_method

        # Precompute binomial coefficients, and store them on the same device as logits.
        self._binom_coeffs_cdf_y, self._binom_coeffs_pdf_y = self._compute_binomial_coefficients(self.degree_y)
        self._binom_coeffs_cdf_x, self._binom_coeffs_pdf_x = self._compute_binomial_coefficients(self.degree_x)

        # Calculate parameters (deltas and betas).
        self._deltas_y, self._betas_y, self._log_deltas_y = self._compute_deltas_and_betas(self.logits_y)
        self._deltas_x, self._betas_x, self._log_deltas_x = self._compute_deltas_and_betas(self.logits_x)

        # Determine batch shape based on the logits. The event shape is scalar since this is a univariate distribution.
        super().__init__(batch_shape=batch_shape, event_shape=torch.Size([]), validate_args=validate_args)

    def __repr__(self) -> str:
        """String representation of the distribution."""
        return (
            f"{self.__class__.__name__}(degree_y: {self.degree_y}, degree_x: {self.degree_x}, "
            f"batch_shape: {self.batch_shape}, bound_low: {self.bound_low}, "
            f"bound_up: {self.bound_up}, normalization_method: {self.normalization_method})"
        )

    def _compute_binomial_coefficients(self, degree: int) -> tuple[torch.Tensor, torch.Tensor]:
        """Compute the binomial coefficients for the CDF and PDF based on the degree of the Bernstein polynomial.

        comb(n, k) = n! / (k! * (n-k)!) is the binomial coefficient, which counts the number of ways to choose k
        elements from a set of n elements.

        Returns:
            coeffs_cdf: Binomial coefficients for the CDF, of shape (degree + 1,).
            coeffs_pdf: Binomial coefficients for the PDF, of shape (degree,).
        """
        coeffs_cdf = torch.tensor(
            [math.comb(degree, i) for i in range(degree + 1)], device=self.logits_y.device, dtype=self.logits_y.dtype
        )

        coeffs_pdf = torch.tensor(
            [math.comb(degree - 1, i) for i in range(degree)], device=self.logits_y.device, dtype=self.logits_y.dtype
        )

        # Check if any of the binomial coefficients became infinite.
        if torch.isinf(coeffs_cdf).any() or torch.isinf(coeffs_pdf).any():
            raise ValueError(
                f"Binomial coefficients became infinite for degree {degree}. "
                "Consider reducing the (last) dimension of the logits, leading to lower degree polynomial."
            )

        return coeffs_cdf, coeffs_pdf

    def _compute_deltas_and_betas(self, logits: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        r"""Compute the deltas (Beta mixture component weights) and betas (control points) for the Bezier curve based
        on the given logits.

        The deltas are the forward differences of the betas, i.e., $ \Delta_i = \beta_{i + 1} - \beta_i $.

        Returns:
            deltas: Weights of the Beta components in the mixture, of shape (*batch_shape, degree).
            betas: Control points of the Bezier curve, of shape (*batch_shape, degree + 1).
            log_deltas: Log of the deltas, computed in a numerically stable way, of shape (*batch_shape, degree)
        """
        # The deltas are the steps themselves (forward differences of betas).
        if self.normalization_method == "softmax":
            deltas = torch.softmax(logits, dim=-1)  # shape: (*batch_shape, degree)
            log_deltas = torch.log_softmax(logits, dim=-1)

        elif self.normalization_method == "sigmoid":
            log_deltas = torch.log_softmax(torch.nn.functional.logsigmoid(logits), dim=-1)
            deltas = log_deltas.exp()

        else:
            raise ValueError(f"Unknown normalization method: {self.normalization_method}")

        # Pad with zeros and ones to enforce the CDF boundary conditions:
        # betas = [0, beta_1, ..., beta_{n-1}, beta_n = 1]
        zeros = torch.zeros(*deltas.shape[:-1], 1, device=deltas.device, dtype=deltas.dtype)  # shape: (*batch_shape, 1)
        inner_betas = torch.cumsum(deltas, dim=-1)[..., :-1]
        ones = torch.ones(*deltas.shape[:-1], 1, device=deltas.device, dtype=deltas.dtype)
        betas = torch.cat([zeros, inner_betas, ones], dim=-1)

        return deltas, betas, log_deltas

    def _map_to_t_space(self, value: torch.Tensor) -> torch.Tensor:
        r"""Map physical values to curve parameters by normalizing to [0, 1], clamping, and inverting $B_x(t)$."""
        value = torch.clamp((value - self.bound_low) / self.support_range, 0, 1)
        return self._invert_bezier(
            value, self._betas_x, self._deltas_x, self._binom_coeffs_cdf_x, self._binom_coeffs_pdf_x
        )

    def _map_to_x_space(self, t: torch.Tensor) -> torch.Tensor:
        r"""Map values from the $T$ space $[0, 1]$ back to the original $X$ space using the bounds."""
        t = self._eval_bezier_curve(t, self._betas_x, self._binom_coeffs_cdf_x)
        return t * self.support_range + self.bound_low

    @property
    def support(self) -> constraints.Constraint:
        """Support of this distribution."""
        return constraints.interval(self.bound_low, self.bound_up)

    @property
    def support_range(self) -> float:
        """Range of the support, i.e., upper bound - lower bound."""
        return self.bound_up - self.bound_low

    @property
    def arg_constraints(self) -> dict[str, constraints.Constraint]:
        """Both logit tensors must contain real values."""
        return {"logits_y": constraints.real, "logits_x": constraints.real}

    @property
    def degree_y(self) -> int:
        r"""Get the degree $n$ of the Bernstein polynomial based on the number of logits.

        For a Bernstein polynomial of degree $n$, there are $n + 1$ control points (betas) and $n$ weights (deltas).
        """
        return self.logits_y.shape[-1]

    @property
    def degree_x(self) -> int:
        """Degree of the horizontal polynomial; one for the fixed affine map."""
        return self.logits_x.shape[-1]

    @property
    def mean(self) -> torch.Tensor:
        r"""Compute the mean by integrating the parametric curve.

        $$ E[X] = L + (U-L) \int_0^1 B_x(t) B_y'(t) \, dt $$

        Note:
            Fixed horizontal spacing uses exact Beta-mixture moments; otherwise Gaussian quadrature is
            polynomial-exact, up to floating-point error.

        Returns:
            Tensor of shape (*batch_shape,).
        """
        e_t, _ = self._moments()
        return self.bound_low + self.support_range * e_t

    @property
    def variance(self) -> torch.Tensor:
        r"""Compute variance from the normalized horizontal coordinate's first two raw moments.

        For $Z=(X-L)/(U-L)$, $E[Z^k]=\int_0^1 B_x(t)^k B_y'(t)\,dt$, and

        $$ Var[X] = (U-L)^2 (E[Z^2] - E[Z]^2) $$

        Note:
            Fixed horizontal spacing uses exact Beta-mixture moments; otherwise Gaussian quadrature is
            polynomial-exact, up to floating-point error.

        Returns:
            Tensor of shape (*batch_shape,).
        """
        e_t, e_t2 = self._moments()
        return self.support_range**2 * (e_t2 - e_t.square()).clamp_min(0)

    def _quadrature(self, num_points: int) -> tuple[torch.Tensor, torch.Tensor]:
        r"""Generate Gauss-Legendre nodes and weights on $[0, 1]$ using the symmetric Jacobi matrix.

        For $n=\text{num_points}$, the Golub-Welsch construction forms a symmetric tridiagonal matrix
        $J \in \mathbb{R}^{n \times n}$ from the recurrence coefficients of the orthonormal Legendre polynomials:

        $$ J_{k,k}=0, \qquad J_{k,k+1}=J_{k+1,k}=\frac{k}{\sqrt{4k^2-1}},
        \qquad k=1,\ldots,n-1, $$

        with all other entries zero. Its eigenvalues $\lambda_i$ are the roots of the degree-$n$ Legendre
        polynomial, hence the quadrature nodes on $[-1, 1]$. For orthonormal eigenvectors $v_i$ satisfying
        $Jv_i=\lambda_i v_i$, the corresponding weights on that interval are $2(v_i)_1^2$, where $(v_i)_1$
        is the first component of $v_i$. Shifting the nodes and halving the weights gives the rule on $[0, 1]$:

        $$ t_i=\frac{\lambda_i+1}{2}, \qquad w_i=(v_i)_1^2, \qquad
        \int_0^1 f(t)\,dt \approx \sum_{i=1}^{n} w_i f(t_i). $$

        The rule is exact for polynomials of degree at most $2n-1$, up to floating-point error.
        The weights integrate with respect to $dt$; callers supply any additional density factor.

        Note:
            Both tensors use the logits' dtype and device, which must be supported by torch.linalg.eigh.

        Args:
            num_points: Number $n$ of quadrature nodes; must be at least one. Increasing this count raises
                the maximum polynomial degree integrated exactly and refines the approximation for smooth,
                non-polynomial integrands.

        Returns:
            nodes: Quadrature locations in $[0, 1]$, ordered increasingly, with shape
                (num_points,) + (1,) * len(self.batch_shape). The trailing singleton dimensions allow
                the shared quadrature nodes to broadcast across the distribution's batch dimensions.
            weights: Positive integration weights corresponding to nodes, with the same shape. They sum
                to one along the quadrature dimension, up to floating-point error.
        """
        idcs = torch.arange(1, num_points, dtype=self.logits_y.dtype, device=self.logits_y.device)
        off_diagonal = idcs / (4 * idcs.square() - 1).sqrt()

        nodes, vectors = torch.linalg.eigh(torch.diag(off_diagonal, 1) + torch.diag(off_diagonal, -1))

        shape = (num_points,) + (1,) * len(self.batch_shape)
        nodes = ((nodes + 1) / 2).reshape(shape)
        first_comp_of_vectors = vectors[0]  # 1st component of each eigenvector which represents constants in the L-poly
        weights = first_comp_of_vectors.square().reshape(shape)

        return nodes, weights

    def _moments(self) -> tuple[torch.Tensor, torch.Tensor]:
        r"""Compute the first two raw moments analytically for a fixed axis, otherwise by Gaussian quadrature.

        For support bounds $L$ and $U$, let $Z = (X - L) / (U - L) = B_x(T)$. The curve parameter $T$
        has CDF $B_y(t)$ and density $B_y'(t)$ on $[0, 1]$. Changing variables from $X$ to $T$ cancels
        the horizontal Jacobian:

        $$ p_X(x(t)) x'(t) = B_y'(t), \qquad
        E[Z^k] = \int_0^1 B_x(t)^k B_y'(t) \, dt, \qquad k \in \{1, 2\}. $$

        For degree_x = 1, $Z=T$ and the exact Beta-mixture moments avoid quadrature:

        $$ e_t = \sum_{j=1}^{n_y} \Delta_{j-1} \frac{j}{n_y+1}, \qquad
        e_{t2} = \sum_{j=1}^{n_y} \Delta_{j-1} \frac{j(j+1)}{(n_y+1)(n_y+2)}. $$

        The vertical derivative is evaluated from its degree-$(n_y - 1)$ Bernstein basis:

        $$ B_y'(t) = n_y \sum_{j = 0}^{n_y - 1} \Delta_j B_{j, n_y - 1}(t), $$

        where $n_y = \text{degree_y}$ and $\Delta_j$ are the normalized vertical increments. For Gauss-Legendre
        nodes $t_i$ and weights $w_i$, the code forms horizontal values $h_i$ and integration masses $a_i$:

        $$ h_i = B_x(t_i), \qquad a_i = w_i B_y'(t_i), \qquad
        e_t = \sum_{i = 1}^{m} a_i h_i, \qquad e_{t2} = \sum_{i = 1}^{m} a_i h_i^2. $$

        The masses sum to one up to floating-point error. Horizontal values and masses have shape
        (m, *batch_shape); summing along dimension zero removes only the quadrature dimension.

        With $n_x = \text{degree_x}$, the integrand for moment $k$ has degree at most $k n_x + n_y - 1$.
        An $m$-point Gauss-Legendre rule integrates polynomials through degree $2 m - 1$ exactly, so both
        moments are covered by the node count used here:

        $$ m = \left\lceil \frac{2 n_x + n_y}{2} \right\rceil
        = \left\lfloor \frac{2 n_x + n_y + 1}{2} \right\rfloor. $$

        Note:
            Both moments are polynomial-exact up to floating-point error and retain gradients through both axes.
            The fixed axis retains explicit zero gradients. Tensors use the logits' dtype and device;
            only learned horizontal axes are subject to the requirements of _quadrature.
            No numerical inversion or support rescaling is performed here; mean and variance apply the bounds.

        Returns:
            e_t: First raw moment $E[Z]$, with shape (*batch_shape,).
            e_t2: Second raw moment $E[Z^2]$, with shape (*batch_shape,); this is not the variance.
                Despite their names, these are moments of $Z$, not of $T$, unless $B_x(t) = t$.
        """
        if self.degree_x == 1:
            idcs = torch.arange(1, self.degree_y + 1, dtype=self.logits_y.dtype, device=self.logits_y.device)
            component_1st_mom = idcs / (self.degree_y + 1)  # shape: (degree_y,)
            component_2nd_mom = component_1st_mom * (idcs + 1) / (self.degree_y + 2)  # shape: (degree_y,)

            # Combine the component raw moments using the Beta-mixture weights.
            zero_x = self.logits_x[..., 0] * 0  # keep autograd connection
            e_t = (self._deltas_y * component_1st_mom).sum(dim=-1) + zero_x  # shape: (*batch_shape,)
            e_t2 = (self._deltas_y * component_2nd_mom).sum(dim=-1) + zero_x  # shape: (*batch_shape,)

            return e_t, e_t2

        # Compute the Gauss-Legendre nodes t_i and weights w_i for integration over t in [0, 1].
        # Choose num_points m so 2*m - 1 >= 2*degree_x + degree_y - 1, covering both raw-moment integrands.
        nodes, weights = self._quadrature(num_points=(2 * self.degree_x + self.degree_y + 1) // 2)

        # Compute the normalized x-axis coordinates z_i = B_x(t_i).
        normalized_x_coords = self._eval_bezier_curve(nodes, self._betas_x, self._binom_coeffs_cdf_x)

        # Quadrature masses w_i * B_y'(t_i); the horizontal Jacobian cancels when integrating in t.
        masses = weights * self.degree_y * self._eval_bezier_curve(nodes, self._deltas_y, self._binom_coeffs_pdf_y)

        # Integrate z and z^2 over the quadrature dimension, keeping the batch dimensions.
        e_t = (masses * normalized_x_coords).sum(dim=0)
        e_t2 = (masses * normalized_x_coords.square()).sum(dim=0)

        return e_t, e_t2

    def _eval_bezier_curve(
        self,
        t: torch.Tensor,
        weights: torch.Tensor,
        binom_coeffs: torch.Tensor,
    ) -> torch.Tensor:
        r"""Evaluates a Bezier curve (a Bernstein polynomial) in the $T \in [0, 1]$ space.

        This method computes the weighted sum of Bernstein basis polynomials. Let $d$ be the degree of the polynomial
        being evaluated ($n$ for an axis curve or $n-1$ for its derivative basis). Each basis polynomial is defined as:

        $$ B_{i, d}(t) = \binom{d}{i} t^i (1-t)^{d-i} $$

        The polynomial's value $p(t)$ is computed as:

        $$ p(t) = \sum_{i=0}^{d} w_i B_{i, d}(t) $$

        where $w_i$ are the weights (betas for an axis curve or deltas for its derivative basis).
        When using deltas, callers multiply the result by the axis degree to obtain the derivative.

        Args:
            t: Normalized input values in [0, 1].
                Expected shape: (*sample_shape, *batch_shape).
            weights: The coefficients for the basis polynomials.
                Expected shape: (*batch_shape, degree + 1).
            binom_coeffs: Precomputed binomial coefficients corresponding to the polynomial's degree.
                Expected shape: (degree + 1,).

        Returns:
            The evaluated polynomial values.
            Output shape: (*sample_shape, *batch_shape)
        """
        # Get n which can be != self.degree as we use this method for both CDF and PDF which have different degrees.
        nun_coeffs = binom_coeffs.shape[0]

        # Create a tensor of indices matching the number of basis polynomials.
        i = torch.arange(nun_coeffs, device=t.device, dtype=t.dtype)

        # Add an empty dimension to t for broadcasting, resulting in shape: (*sample_shape, *batch_shape, 1).
        t_expanded = t.unsqueeze(-1)

        # Bernstein basis B_{i,d}(t) = binom(d, i) * t**i * (1-t)**(d-i), with d = nun_coeffs - 1.
        # Broadcasting gives shape (*t.shape, nun_coeffs), with one entry per basis polynomial.
        basis = binom_coeffs * (t_expanded**i) * ((1 - t_expanded) ** (nun_coeffs - 1 - i))

        # Multiply by weights and sum across the final dimension, resulting in shape (*sample_shape, *batch_shape).
        return torch.sum(weights * basis, dim=-1)

    def _eval_log_derivative(
        self, t: torch.Tensor, log_deltas: torch.Tensor, binom_coeffs: torch.Tensor
    ) -> torch.Tensor:
        r"""Evaluate the log derivative of either normalized axis entirely in log-space.

        For an axis of degree $n$, its derivative uses the degree-$(n-1)$ Bernstein basis:

        $$ \log B'(t) = \log n + \operatorname{logsumexp}_i\!\left(
        \log \Delta_i + \log \binom{n-1}{i} + i\log t + (n-1-i)\log(1-t)\right). $$

        This avoids the numerically problematic log(polynomial + eps) path. Exact endpoints are handled separately,
        where only the first or last Bernstein basis term survives.
        Degree-one axes return the constant log derivative directly, preserving broadcasting and zero input gradients.

        Args:
            t: Curve parameters in [0, 1], of shape (*sample_shape, *batch_shape).
            log_deltas: Normalized log increments for the chosen axis, of shape (*batch_shape, n).
            binom_coeffs: Degree-(n-1) Bernstein coefficients, of shape (n,).

        Returns:
            Log derivatives with the broadcast sample/batch shape, before support-range scaling.
        """
        degree = log_deltas.shape[-1]
        if degree == 1:
            # Degree-one axes have a constant derivative. This is not necessarily the past-path for the constantly
            # spaced x-axis.
            return t * 0 + log_deltas[..., 0]

        # Indices for the Bernstein basis: i = 0, ..., n-1. Shape: (n,).
        idcs = torch.arange(degree, device=t.device, dtype=t.dtype)

        # Clamp away from exact 0/1 to avoid log(0), then append a basis dimension: (*t.shape, 1).
        t_safe = t.clamp(min=torch.finfo(t.dtype).tiny, max=1 - torch.finfo(t.dtype).eps).unsqueeze(-1)

        # Log of each Bernstein basis term: log(binom) + i*log(t) + (n-1-i)*log(1-t).
        # log_basis shape: (*t.shape, n); singleton batch dimensions expand when adding log_deltas.
        log_basis = binom_coeffs.log() + idcs * t_safe.log() + (degree - 1 - idcs) * torch.log1p(-t_safe)

        # Broadcast log_deltas (*batch_shape, n) across samples, then sum weighted terms via logsumexp.
        # The degree factor accounts for differentiation; result shape: (*sample_shape, *batch_shape).
        log_derivative = math.log(degree) + torch.logsumexp(log_deltas + log_basis, dim=-1)

        # Restore analytic endpoint derivatives instead of returning the clamped interior approximations.
        log_derivative = torch.where(t == 0, math.log(degree) + log_deltas[..., 0], log_derivative)
        log_derivative = torch.where(t == 1, math.log(degree) + log_deltas[..., -1], log_derivative)
        return log_derivative

    def _invert_bezier(
        self,
        value: torch.Tensor,
        betas: torch.Tensor,
        deltas: torch.Tensor,
        coeffs_cdf: torch.Tensor,
        coeffs_pdf: torch.Tensor,
        num_iter: int = 64,
        use_newton: bool = True,
        newton_damping: float = 1.0,
        convergence_eps_factor: float = 2.0,
    ) -> torch.Tensor:
        r"""Invert a normalized monotone Bezier axis using a bracketed solver and implicit gradients.

        For the chosen horizontal or vertical axis of degree $n$, solve for the curve parameter $t$:

        $$ B(t) = \sum_{i=0}^{n} \beta_i B_{i,n}(t) = q, \qquad
        q = \operatorname{clamp}(\text{value}, 0, 1). $$

        Here $B_{i,n}$ is the Bernstein basis, and the supplied control points must increase from 0 to 1.
        Their positive increments determine the derivative:

        $$ B'(t) = n \sum_{i=0}^{n-1} \Delta_i B_{i,n-1}(t), \qquad
        \Delta_i = \beta_{i+1} - \beta_i. $$

        Each sample/batch element starts at $t=q$ with its own bracket $[0, 1]$. The current curve value
        tightens one bracket endpoint. A damped Newton proposal is accepted only strictly inside the updated
        bracket; otherwise its midpoint is used. Setting use_newton=False always selects the midpoint.

        $$ c_k = \frac{B(t_k)-q}{\max(B'(t_k), \text{tiny})}, \qquad
        t_{\mathrm{Newton}} = t_k - \alpha c_k. $$

        An element stops updating when either the undamped correction $|c_k|$ or its bracket width is at
        most convergence_eps_factor times machine epsilon. Both criteria measure error in parameter space,
        rather than relying on a small curve-value residual in a flat region. The loop ends when all elements
        converge or num_iter is reached; exhausting the iteration budget returns the current estimate.

        Iterations run without gradient tracking. At the resulting estimate, a forward-zero residual
        correction attaches the implicit first-order derivatives for interior targets:

        $$ \frac{\partial t}{\partial q} = \frac{1}{B'(t)}, \qquad
        \frac{\partial t}{\partial\theta} = -\frac{\partial_\theta B(t;\theta)}{B'(t)}. $$

        Here $\theta$ denotes the chosen axis's parameters. Detaching the denominator avoids differentiating
        this correction as another solver iteration. Gradient accuracy depends on the numerical root;
        higher-order inverse derivatives are not supported. Derivative denominators are clamped to the dtype's
        smallest positive normal value (tiny) to avoid division by zero, modifying the formulas below that floor.

        Args:
            value: Target values on the normalized axis, clamped to [0, 1]. Shape:
                (*sample_shape, *value_batch_shape), with trailing batch dimensions broadcastable to batch_shape.
            betas: Increasing control points with first/last values 0/1. Shape: (*batch_shape, n + 1).
            deltas: Positive forward differences of betas, summing to one. Shape: (*batch_shape, n).
            coeffs_cdf: Binomial coefficients for the degree-n curve. Shape: (n + 1,).
            coeffs_pdf: Binomial coefficients for the degree-(n-1) derivative basis. Shape: (n,).
                Despite their names, both coefficient tensors apply to either axis.
            num_iter: Maximum number of solver iterations; must be at least one.
            use_newton: Whether to try damped Newton steps with bisection fallback. False uses pure bisection,
                but still evaluates the derivative for the convergence check.
            newton_damping: Newton step multiplier $\alpha$ in (0, 1]; ignored when use_newton=False.
            convergence_eps_factor: Positive multiplier of the input dtype's machine epsilon for the tolerance.

        Returns:
            Estimated curve parameters in [0, 1], with shape (*sample_shape, *broadcast_batch_shape).
            The exact shape is the broadcast of value.shape and betas.shape[:-1]. Clamped target values 0 and 1
            return exact endpoints; a degree-one normalized axis returns the clamped targets directly.

        Note:
            Callers supply consistent axis tensors with a shared floating dtype/device and valid solver settings.
            This helper does not rescale physical coordinates or validate these preconditions.
        """
        # Remove the control-point dimension before broadcasting targets across the axis batch dimensions.
        # q and all per-element solver tensors have shape (*sample_shape, *broadcast_batch_shape).
        q, _ = torch.broadcast_tensors(value.clamp(0, 1), betas[..., 0])

        # With control points [0, 1], the degree-one axis and its inverse are both the identity.
        degree = deltas.shape[-1]
        if degree == 1:
            return q

        tiny = torch.finfo(q.dtype).tiny
        tolerance = convergence_eps_factor * torch.finfo(q.dtype).eps

        # Find the numerical root without retaining an autograd graph for the iterations.
        with torch.no_grad():
            mid = q.clone()
            low, high = torch.zeros_like(mid), torch.ones_like(mid)

            for _ in range(num_iter):
                current = self._eval_bezier_curve(mid, betas, coeffs_cdf)
                derivative = degree * self._eval_bezier_curve(mid, deltas, coeffs_pdf)
                correction = (current - q) / derivative.clamp_min(tiny)

                # The Boolean mask has the same sample/batch shape; only the all() check reduces it to a scalar.
                converged = (correction.abs() <= tolerance) | (high - low <= tolerance)
                if converged.all():
                    break

                # Monotonicity selects which bracket endpoint to move; bisection supplies the fallback step.
                low = torch.where(current < q, mid, low)
                high = torch.where(current >= q, mid, high)
                candidate = (low + high) / 2

                if use_newton:
                    # Reject overshooting Newton steps instead of letting them leave the root's bracket.
                    newton = mid - newton_damping * correction
                    candidate = torch.where((newton > low) & (newton < high), newton, candidate)

                # Keep converged estimates fixed while other sample/batch elements continue iterating.
                mid = torch.where(converged, mid, candidate)

        if torch.is_grad_enabled():
            # residual - residual.detach() is forward-zero but preserves gradients to q and the axis parameters.
            # Dividing by the detached slope attaches the implicit inverse derivative at the fixed estimate.
            residual = q - self._eval_bezier_curve(mid, betas, coeffs_cdf)
            derivative = degree * self._eval_bezier_curve(mid, deltas, coeffs_pdf)
            mid = mid + (residual - residual.detach()) / derivative.detach().clamp_min(tiny)

        # Return exact endpoints rather than tolerance-dependent interior approximations.
        mid = torch.where(q == 0, torch.zeros_like(mid), mid)
        return torch.where(q == 1, torch.ones_like(mid), mid)

    def cdf(self, value: torch.Tensor) -> torch.Tensor:
        """Compute cumulative distribution function at given values.

        Args:
            value: Values at which to compute the CDF. Expected shape: (*sample_shape, *batch_shape).

        Returns:
            CDF values in [0, 1] corresponding to the input values.
            Output shape: same as `value` argument.
        """
        x = value.to(device=self.logits_y.device, dtype=self.logits_y.dtype)

        # Map X in [bound_low, bound_up] to T in [0, 1].
        t = self._map_to_t_space(x)

        # Construct and evaluate the Bezier curve in T space.
        return self._eval_bezier_curve(t, weights=self._betas_y, binom_coeffs=self._binom_coeffs_cdf_y)

    def prob(self, value: torch.Tensor) -> torch.Tensor:
        """Compute probability density at given values.

        Args:
            value: Values at which to compute the PDF. Expected shape: (*sample_shape, *batch_shape).

        Returns:
            PDF values corresponding to the input values.
            Output shape: same as `value` argument.
        """
        return self.log_prob(value).exp()

    def log_prob(self, value: torch.Tensor) -> torch.Tensor:
        r"""Compute the log-probability density at given values, entirely in log-space for numerical stability.

        $$ \log p(x(t)) = \log B_y'(t) - \log B_x'(t) - \log(U-L) $$

        Both derivatives are evaluated with logsumexp. With fixed horizontal spacing, $B_x'(t)=1$.

        Args:
            value: Values at which to compute the log-PDF. Expected shape: (*sample_shape, *batch_shape).

        Returns:
            Log-PDF values corresponding to the input values.
            Output shape: same as `value` argument.
        """
        x = value.to(device=self.logits_y.device, dtype=self.logits_y.dtype)

        # Map X in [bound_low, bound_up] to T in [0, 1].
        t = self._map_to_t_space(x)

        # Start with log B_y'(t): probability change per unit t, not yet the physical log-density.
        log_pdf = self._eval_log_derivative(t, self._log_deltas_y, self._binom_coeffs_pdf_y)

        # Divide by horizontal stretching B_x'(t), hence subtract its log, to get density per normalized x.
        log_pdf = log_pdf - self._eval_log_derivative(t, self._log_deltas_x, self._binom_coeffs_pdf_x)

        # Divide by the support width U-L (subtract its log) to get density per physical x.
        log_pdf = log_pdf - math.log(self.support_range)

        # Mask values outside the support.
        mask = (value >= self.bound_low) & (value <= self.bound_up)
        return torch.where(mask, log_pdf, torch.full_like(log_pdf, -math.inf))

    def entropy(self, num_quadrature_points: int = 251) -> torch.Tensor:
        r"""Compute differential entropy via Gaussian quadrature in parameter space, without inversion.

        $$ H(X) = -\int_0^1 B_y'(t) \log p(x(t)) \, dt $$

        where $L$ and $U$ are the lower and upper bounds of the distribution support, respectively.

        Args:
            num_quadrature_points: Number of Gauss-Legendre nodes for the approximation.

        Returns:
            Tensor of shape (*batch_shape,).
        """
        if num_quadrature_points < 1:
            raise ValueError("num_quadrature_points must be positive.")

        nodes, weights = self._quadrature(num_quadrature_points)

        # B_y'(t) is the density in parameter space; evaluate its log at the quadrature nodes.
        log_derivative_y = self._eval_log_derivative(nodes, self._log_deltas_y, self._binom_coeffs_pdf_y)

        # Change variables: log p_X(x(t)) = log p_T(t) - log x'(t) = log B_y'(t) - log(U-L) - log B_x'(t).
        log_pdf = log_derivative_y - math.log(self.support_range)
        log_pdf = log_pdf - self._eval_log_derivative(nodes, self._log_deltas_x, self._binom_coeffs_pdf_x)

        # H(X) = -∫_0^1 B_y'(t) * log p_X(x(t)) dt, with exp(log_derivative_y) = B_y'(t).
        return -(weights * log_derivative_y.exp() * log_pdf).sum(dim=0)

    def icdf(
        self,
        value: torch.Tensor,
        num_iter: int = 64,
        use_newton: bool = True,
        newton_damping: float = 1.0,
        convergence_eps_factor: float = 2.0,
    ) -> torch.Tensor:
        r"""Compute the inverse CDF, i.e., the quantile function, at the given values.

        Both solvers invert $B_y(t)-q=0$ and then evaluate $x(t)$, without a nested horizontal solve:

        **Newton's method** uses the vertical derivative and iterates

        $$ t_{k+1} = t_k - \alpha \frac{B_y(t_k) - q}{B_y'(t_k)} $$

        where $q$ is the target quantile in [0, 1],
        and $\alpha \in (0, 1]$ is a damping factor that shrinks each Newton step to improve robustness.
        A bracket within [0, 1] is maintained alongside: whenever $B_y(t_k) < q$ the lower bound tightens,
        otherwise the upper bound tightens. If the Newton step would leave the bracket, a bisection
        step is used instead, guaranteeing monotonic bracket contraction and preventing oscillation.
        The loop exits when the parameter-space Newton correction or bracket width is below tolerance.

        **Bisection** halves the search interval each iteration, gaining ~1 bit of precision per step.

        Args:
            value: Values in [0, 1] at which to compute the inverse CDF. Expected shape: (*sample_shape, *batch_shape).
            num_iter: Maximum number of solver iterations. The loop exits early upon convergence.
            use_newton: If True, use Newton's method. If False, use pure bisection.
            newton_damping: Damping factor in (0, 1] applied to the Newton step. A value of 1.0 gives the
                full Newton step (quadratic convergence), while smaller values improve robustness
                at the cost of slower convergence.
            convergence_eps_factor: The factor multiplied by machine epsilon to determine the convergence criterion.

        Returns:
            Quantiles in [bound_low, bound_up] corresponding to the input CDF values.
            Output shape: same as `value` argument.
        """
        if num_iter < 1 or not 0 < newton_damping <= 1 or convergence_eps_factor <= 0:
            raise ValueError("Require num_iter >= 1, 0 < newton_damping <= 1, and convergence_eps_factor > 0.")

        q = value.to(device=self.logits_y.device, dtype=self.logits_y.dtype)
        t = self._invert_bezier(
            q,
            self._betas_y,
            self._deltas_y,
            self._binom_coeffs_cdf_y,
            self._binom_coeffs_pdf_y,
            num_iter,
            use_newton,
            newton_damping,
            convergence_eps_factor,
        )

        return self._map_to_x_space(t)

    def rsample(self, sample_shape: torch.Size | list[int] | tuple[int, ...] = _size) -> torch.Tensor:
        """Draw reparameterized samples with first-order gradients through both axes.

        Args:
            sample_shape: Desired shape of the samples to be drawn. Default is empty, which means one sample per batch element.

        Returns:
            Samples drawn from the distribution, with shape (*sample_shape, *batch_shape).
        """
        # Determine the final shape of the output tensor.
        shape = self._extended_shape(sample_shape)

        # Sample uniform noise, u ~ U(0, 1).
        u = torch.rand(shape, dtype=self.logits_y.dtype, device=self.logits_y.device)

        return self.icdf(u)
arg_constraints property

Both logit tensors must contain real values.

degree_x property

Degree of the horizontal polynomial; one for the fixed affine map.

degree_y property

Get the degree \(n\) of the Bernstein polynomial based on the number of logits.

For a Bernstein polynomial of degree \(n\), there are \(n + 1\) control points (betas) and \(n\) weights (deltas).

mean property

Compute the mean by integrating the parametric curve.

\[ E[X] = L + (U-L) \int_0^1 B_x(t) B_y'(t) \, dt \]

Note

Fixed horizontal spacing uses exact Beta-mixture moments; otherwise Gaussian quadrature is polynomial-exact, up to floating-point error.

Returns:

Type Description
Tensor

Tensor of shape (*batch_shape,).

support property

Support of this distribution.

support_range property

Range of the support, i.e., upper bound - lower bound.

variance property

Compute variance from the normalized horizontal coordinate's first two raw moments.

For \(Z=(X-L)/(U-L)\), \(E[Z^k]=\int_0^1 B_x(t)^k B_y'(t)\,dt\), and

\[ Var[X] = (U-L)^2 (E[Z^2] - E[Z]^2) \]

Note

Fixed horizontal spacing uses exact Beta-mixture moments; otherwise Gaussian quadrature is polynomial-exact, up to floating-point error.

Returns:

Type Description
Tensor

Tensor of shape (*batch_shape,).

__init__(logits_y, logits_x=None, bound_low=-1000.0, bound_up=1000.0, normalization_method='softmax', validate_args=None)

Initializer.

Parameters:

Name Type Description Default
logits_y Tensor

Raw vertical-increment logits, of shape (*batch_shape, degree_y).

required
logits_x Tensor | None

Raw horizontal-increment logits, of shape (*batch_shape, degree_x). Batch shapes must broadcast with logits_y, and both tensors must have the same floating dtype and device. None uses a one-element zero tensor matching logits_y, fixing the horizontal map to the identity.

None
bound_low float

Lower bound of the distribution support, needs to be finite.

-1000.0
bound_up float

Upper bound of the distribution support, needs to be finite.

1000.0
normalization_method Literal['sigmoid', 'softmax']

How to normalize the probabilities. Either "sigmoid" or "softmax". With "sigmoid", each control point is independently activated, while with "softmax", the control point activations influence each other.

'softmax'
validate_args bool | None

Whether to validate arguments. Carried over to keep the interface with the base class.

None
Source code in binned_cdf/bezier_cdf.py
def __init__(
    self,
    logits_y: torch.Tensor,
    logits_x: torch.Tensor | None = None,
    bound_low: float = -1e3,
    bound_up: float = 1e3,
    normalization_method: Literal["sigmoid", "softmax"] = "softmax",
    validate_args: bool | None = None,
) -> None:
    """Initializer.

    Args:
        logits_y: Raw vertical-increment logits, of shape (*batch_shape, degree_y).
        logits_x: Raw horizontal-increment logits, of shape (*batch_shape, degree_x). Batch shapes must
            broadcast with logits_y, and both tensors must have the same floating dtype and device.
            None uses a one-element zero tensor matching logits_y, fixing the horizontal map to the identity.
        bound_low: Lower bound of the distribution support, needs to be finite.
        bound_up: Upper bound of the distribution support, needs to be finite.
        normalization_method: How to normalize the probabilities. Either "sigmoid" or "softmax". With "sigmoid",
            each control point is independently activated, while with "softmax", the control point activations
            influence each other.
        validate_args: Whether to validate arguments. Carried over to keep the interface with the base class.
    """
    if not math.isfinite(bound_low) or not math.isfinite(bound_up) or bound_low >= bound_up:
        raise ValueError("Bounds must be finite with bound_low < bound_up.")
    if logits_y.ndim < 1 or logits_y.shape[-1] < 1 or not logits_y.is_floating_point():
        raise ValueError("logits_y must be a floating tensor with at least one increment.")
    if logits_x is not None and (logits_x.ndim < 1 or logits_x.shape[-1] < 1 or not logits_x.is_floating_point()):
        raise ValueError("logits_x must be None or a floating tensor with at least one increment.")
    if logits_x is not None and (logits_x.dtype != logits_y.dtype or logits_x.device != logits_y.device):
        raise ValueError("logits_x and logits_y must have the same floating dtype and device.")

    logits_x = logits_y.new_zeros(1) if logits_x is None else logits_x
    batch_shape = torch.broadcast_shapes(logits_y.shape[:-1], logits_x.shape[:-1])
    self.logits_y = logits_y.expand(*batch_shape, logits_y.shape[-1])
    self.logits_x = logits_x.expand(*batch_shape, logits_x.shape[-1])
    self.bound_low = bound_low
    self.bound_up = bound_up
    self.normalization_method = normalization_method

    # Precompute binomial coefficients, and store them on the same device as logits.
    self._binom_coeffs_cdf_y, self._binom_coeffs_pdf_y = self._compute_binomial_coefficients(self.degree_y)
    self._binom_coeffs_cdf_x, self._binom_coeffs_pdf_x = self._compute_binomial_coefficients(self.degree_x)

    # Calculate parameters (deltas and betas).
    self._deltas_y, self._betas_y, self._log_deltas_y = self._compute_deltas_and_betas(self.logits_y)
    self._deltas_x, self._betas_x, self._log_deltas_x = self._compute_deltas_and_betas(self.logits_x)

    # Determine batch shape based on the logits. The event shape is scalar since this is a univariate distribution.
    super().__init__(batch_shape=batch_shape, event_shape=torch.Size([]), validate_args=validate_args)
__repr__()

String representation of the distribution.

Source code in binned_cdf/bezier_cdf.py
def __repr__(self) -> str:
    """String representation of the distribution."""
    return (
        f"{self.__class__.__name__}(degree_y: {self.degree_y}, degree_x: {self.degree_x}, "
        f"batch_shape: {self.batch_shape}, bound_low: {self.bound_low}, "
        f"bound_up: {self.bound_up}, normalization_method: {self.normalization_method})"
    )
cdf(value)

Compute cumulative distribution function at given values.

Parameters:

Name Type Description Default
value Tensor

Values at which to compute the CDF. Expected shape: (*sample_shape, *batch_shape).

required

Returns:

Type Description
Tensor

CDF values in [0, 1] corresponding to the input values.

Tensor

Output shape: same as value argument.

Source code in binned_cdf/bezier_cdf.py
def cdf(self, value: torch.Tensor) -> torch.Tensor:
    """Compute cumulative distribution function at given values.

    Args:
        value: Values at which to compute the CDF. Expected shape: (*sample_shape, *batch_shape).

    Returns:
        CDF values in [0, 1] corresponding to the input values.
        Output shape: same as `value` argument.
    """
    x = value.to(device=self.logits_y.device, dtype=self.logits_y.dtype)

    # Map X in [bound_low, bound_up] to T in [0, 1].
    t = self._map_to_t_space(x)

    # Construct and evaluate the Bezier curve in T space.
    return self._eval_bezier_curve(t, weights=self._betas_y, binom_coeffs=self._binom_coeffs_cdf_y)
entropy(num_quadrature_points=251)

Compute differential entropy via Gaussian quadrature in parameter space, without inversion.

\[ H(X) = -\int_0^1 B_y'(t) \log p(x(t)) \, dt \]

where \(L\) and \(U\) are the lower and upper bounds of the distribution support, respectively.

Parameters:

Name Type Description Default
num_quadrature_points int

Number of Gauss-Legendre nodes for the approximation.

251

Returns:

Type Description
Tensor

Tensor of shape (*batch_shape,).

Source code in binned_cdf/bezier_cdf.py
def entropy(self, num_quadrature_points: int = 251) -> torch.Tensor:
    r"""Compute differential entropy via Gaussian quadrature in parameter space, without inversion.

    $$ H(X) = -\int_0^1 B_y'(t) \log p(x(t)) \, dt $$

    where $L$ and $U$ are the lower and upper bounds of the distribution support, respectively.

    Args:
        num_quadrature_points: Number of Gauss-Legendre nodes for the approximation.

    Returns:
        Tensor of shape (*batch_shape,).
    """
    if num_quadrature_points < 1:
        raise ValueError("num_quadrature_points must be positive.")

    nodes, weights = self._quadrature(num_quadrature_points)

    # B_y'(t) is the density in parameter space; evaluate its log at the quadrature nodes.
    log_derivative_y = self._eval_log_derivative(nodes, self._log_deltas_y, self._binom_coeffs_pdf_y)

    # Change variables: log p_X(x(t)) = log p_T(t) - log x'(t) = log B_y'(t) - log(U-L) - log B_x'(t).
    log_pdf = log_derivative_y - math.log(self.support_range)
    log_pdf = log_pdf - self._eval_log_derivative(nodes, self._log_deltas_x, self._binom_coeffs_pdf_x)

    # H(X) = -∫_0^1 B_y'(t) * log p_X(x(t)) dt, with exp(log_derivative_y) = B_y'(t).
    return -(weights * log_derivative_y.exp() * log_pdf).sum(dim=0)
icdf(value, num_iter=64, use_newton=True, newton_damping=1.0, convergence_eps_factor=2.0)

Compute the inverse CDF, i.e., the quantile function, at the given values.

Both solvers invert \(B_y(t)-q=0\) and then evaluate \(x(t)\), without a nested horizontal solve:

Newton's method uses the vertical derivative and iterates

\[ t_{k+1} = t_k - \alpha \frac{B_y(t_k) - q}{B_y'(t_k)} \]

where \(q\) is the target quantile in [0, 1], and \(\alpha \in (0, 1]\) is a damping factor that shrinks each Newton step to improve robustness. A bracket within [0, 1] is maintained alongside: whenever \(B_y(t_k) < q\) the lower bound tightens, otherwise the upper bound tightens. If the Newton step would leave the bracket, a bisection step is used instead, guaranteeing monotonic bracket contraction and preventing oscillation. The loop exits when the parameter-space Newton correction or bracket width is below tolerance.

Bisection halves the search interval each iteration, gaining ~1 bit of precision per step.

Parameters:

Name Type Description Default
value Tensor

Values in [0, 1] at which to compute the inverse CDF. Expected shape: (*sample_shape, *batch_shape).

required
num_iter int

Maximum number of solver iterations. The loop exits early upon convergence.

64
use_newton bool

If True, use Newton's method. If False, use pure bisection.

True
newton_damping float

Damping factor in (0, 1] applied to the Newton step. A value of 1.0 gives the full Newton step (quadratic convergence), while smaller values improve robustness at the cost of slower convergence.

1.0
convergence_eps_factor float

The factor multiplied by machine epsilon to determine the convergence criterion.

2.0

Returns:

Type Description
Tensor

Quantiles in [bound_low, bound_up] corresponding to the input CDF values.

Tensor

Output shape: same as value argument.

Source code in binned_cdf/bezier_cdf.py
def icdf(
    self,
    value: torch.Tensor,
    num_iter: int = 64,
    use_newton: bool = True,
    newton_damping: float = 1.0,
    convergence_eps_factor: float = 2.0,
) -> torch.Tensor:
    r"""Compute the inverse CDF, i.e., the quantile function, at the given values.

    Both solvers invert $B_y(t)-q=0$ and then evaluate $x(t)$, without a nested horizontal solve:

    **Newton's method** uses the vertical derivative and iterates

    $$ t_{k+1} = t_k - \alpha \frac{B_y(t_k) - q}{B_y'(t_k)} $$

    where $q$ is the target quantile in [0, 1],
    and $\alpha \in (0, 1]$ is a damping factor that shrinks each Newton step to improve robustness.
    A bracket within [0, 1] is maintained alongside: whenever $B_y(t_k) < q$ the lower bound tightens,
    otherwise the upper bound tightens. If the Newton step would leave the bracket, a bisection
    step is used instead, guaranteeing monotonic bracket contraction and preventing oscillation.
    The loop exits when the parameter-space Newton correction or bracket width is below tolerance.

    **Bisection** halves the search interval each iteration, gaining ~1 bit of precision per step.

    Args:
        value: Values in [0, 1] at which to compute the inverse CDF. Expected shape: (*sample_shape, *batch_shape).
        num_iter: Maximum number of solver iterations. The loop exits early upon convergence.
        use_newton: If True, use Newton's method. If False, use pure bisection.
        newton_damping: Damping factor in (0, 1] applied to the Newton step. A value of 1.0 gives the
            full Newton step (quadratic convergence), while smaller values improve robustness
            at the cost of slower convergence.
        convergence_eps_factor: The factor multiplied by machine epsilon to determine the convergence criterion.

    Returns:
        Quantiles in [bound_low, bound_up] corresponding to the input CDF values.
        Output shape: same as `value` argument.
    """
    if num_iter < 1 or not 0 < newton_damping <= 1 or convergence_eps_factor <= 0:
        raise ValueError("Require num_iter >= 1, 0 < newton_damping <= 1, and convergence_eps_factor > 0.")

    q = value.to(device=self.logits_y.device, dtype=self.logits_y.dtype)
    t = self._invert_bezier(
        q,
        self._betas_y,
        self._deltas_y,
        self._binom_coeffs_cdf_y,
        self._binom_coeffs_pdf_y,
        num_iter,
        use_newton,
        newton_damping,
        convergence_eps_factor,
    )

    return self._map_to_x_space(t)
log_prob(value)

Compute the log-probability density at given values, entirely in log-space for numerical stability.

\[ \log p(x(t)) = \log B_y'(t) - \log B_x'(t) - \log(U-L) \]

Both derivatives are evaluated with logsumexp. With fixed horizontal spacing, \(B_x'(t)=1\).

Parameters:

Name Type Description Default
value Tensor

Values at which to compute the log-PDF. Expected shape: (*sample_shape, *batch_shape).

required

Returns:

Type Description
Tensor

Log-PDF values corresponding to the input values.

Tensor

Output shape: same as value argument.

Source code in binned_cdf/bezier_cdf.py
def log_prob(self, value: torch.Tensor) -> torch.Tensor:
    r"""Compute the log-probability density at given values, entirely in log-space for numerical stability.

    $$ \log p(x(t)) = \log B_y'(t) - \log B_x'(t) - \log(U-L) $$

    Both derivatives are evaluated with logsumexp. With fixed horizontal spacing, $B_x'(t)=1$.

    Args:
        value: Values at which to compute the log-PDF. Expected shape: (*sample_shape, *batch_shape).

    Returns:
        Log-PDF values corresponding to the input values.
        Output shape: same as `value` argument.
    """
    x = value.to(device=self.logits_y.device, dtype=self.logits_y.dtype)

    # Map X in [bound_low, bound_up] to T in [0, 1].
    t = self._map_to_t_space(x)

    # Start with log B_y'(t): probability change per unit t, not yet the physical log-density.
    log_pdf = self._eval_log_derivative(t, self._log_deltas_y, self._binom_coeffs_pdf_y)

    # Divide by horizontal stretching B_x'(t), hence subtract its log, to get density per normalized x.
    log_pdf = log_pdf - self._eval_log_derivative(t, self._log_deltas_x, self._binom_coeffs_pdf_x)

    # Divide by the support width U-L (subtract its log) to get density per physical x.
    log_pdf = log_pdf - math.log(self.support_range)

    # Mask values outside the support.
    mask = (value >= self.bound_low) & (value <= self.bound_up)
    return torch.where(mask, log_pdf, torch.full_like(log_pdf, -math.inf))
prob(value)

Compute probability density at given values.

Parameters:

Name Type Description Default
value Tensor

Values at which to compute the PDF. Expected shape: (*sample_shape, *batch_shape).

required

Returns:

Type Description
Tensor

PDF values corresponding to the input values.

Tensor

Output shape: same as value argument.

Source code in binned_cdf/bezier_cdf.py
def prob(self, value: torch.Tensor) -> torch.Tensor:
    """Compute probability density at given values.

    Args:
        value: Values at which to compute the PDF. Expected shape: (*sample_shape, *batch_shape).

    Returns:
        PDF values corresponding to the input values.
        Output shape: same as `value` argument.
    """
    return self.log_prob(value).exp()
rsample(sample_shape=_size)

Draw reparameterized samples with first-order gradients through both axes.

Parameters:

Name Type Description Default
sample_shape Size | list[int] | tuple[int, ...]

Desired shape of the samples to be drawn. Default is empty, which means one sample per batch element.

_size

Returns:

Type Description
Tensor

Samples drawn from the distribution, with shape (*sample_shape, *batch_shape).

Source code in binned_cdf/bezier_cdf.py
def rsample(self, sample_shape: torch.Size | list[int] | tuple[int, ...] = _size) -> torch.Tensor:
    """Draw reparameterized samples with first-order gradients through both axes.

    Args:
        sample_shape: Desired shape of the samples to be drawn. Default is empty, which means one sample per batch element.

    Returns:
        Samples drawn from the distribution, with shape (*sample_shape, *batch_shape).
    """
    # Determine the final shape of the output tensor.
    shape = self._extended_shape(sample_shape)

    # Sample uniform noise, u ~ U(0, 1).
    u = torch.rand(shape, dtype=self.logits_y.dtype, device=self.logits_y.device)

    return self.icdf(u)

binned_cdf.piecewise_constant_binned_cdf

PiecewiseConstantBinnedCDF

Bases: Distribution

A discrete probability distribution parameterized by binned logits for the CDF.

Each bin contributes a step function to the CDF when active. The activation of each bin is determined by applying a sigmoid to the corresponding logit. The distribution is defined over the interval [bound_low, bound_up] with either linear or logarithmic bin spacing.

Note

This distribution is differentiable with respect to the logits, i.e., the arguments of __init__, but not through the inputs of the prob or cfg method.

Source code in binned_cdf/piecewise_constant_binned_cdf.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
class PiecewiseConstantBinnedCDF(Distribution):
    """A discrete probability distribution parameterized by binned logits for the CDF.

    Each bin contributes a step function to the CDF when active.
    The activation of each bin is determined by applying a sigmoid to the corresponding logit.
    The distribution is defined over the interval [bound_low, bound_up] with either linear or logarithmic bin spacing.

    Note:
        This distribution is differentiable with respect to the logits, i.e., the arguments of `__init__`, but
        not through the inputs of the `prob` or `cfg` method.
    """

    def __init__(
        self,
        logits: torch.Tensor,
        bound_low: float = -1e3,
        bound_up: float = 1e3,
        log_spacing: bool = False,
        normalization_method: Literal["sigmoid", "softmax"] = "sigmoid",
        validate_args: bool | None = None,
    ) -> None:
        """Initializer.

        Args:
            logits: Raw logits for the bin probabilities (before sigmoid), of shape (*batch_shape, num_bins)
            bound_low: Lower bound of the distribution support, needs to be finite.
            bound_up: Upper bound of the distribution support, needs to be finite.
            log_spacing: Whether logarithmic (base = 2) spacing for the bins or linear spacing should be used.
            normalization_method: How to normalize the probabilities. Either "sigmoid" or "softmax". With "sigmoid",
                each bin is independently activated, while with "softmax", the bins activations influence each other.
            validate_args: Whether to validate arguments. Carried over to keep the interface with the base class.
        """
        self.logits = logits
        self.bound_low = bound_low
        self.bound_up = bound_up
        self.normalization_method = normalization_method
        self.log_spacing = log_spacing

        # Create bin structure (same for all batch dimensions).
        self.bin_edges, self.bin_centers, self.bin_widths = self._create_bins(
            num_bins=logits.shape[-1],
            bound_low=bound_low,
            bound_up=bound_up,
            log_spacing=log_spacing,
            device=logits.device,
            dtype=logits.dtype,
        )

        # Determine batch shape based on the logits. The event shape is scalar since this is a univariate distribution.
        super().__init__(batch_shape=logits.shape[:-1], event_shape=torch.Size([]), validate_args=validate_args)

    @classmethod
    def _create_bins(
        cls,
        num_bins: int,
        bound_low: float,
        bound_up: float,
        log_spacing: bool,
        device: torch.device,
        dtype: torch.dtype,
        log_min_positive_edge: float = 1e-6,
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        """Create bin edges with symmetric log spacing around zero.

        Layout:
            - 1 edge at 0
            - num_bins//2 - 1 edges from 0 to bound_up (log spaced)
            - num_bins//2 - 1 edges from 0 to -bound_low (log spaced, mirrored)
            - 2 boundary edges at ±bounds
            - in total: num_bins + 1 edges creating num_bins bins

        Args:
            num_bins: Number of bins to create.
            bound_low: Lower bound of the distribution support.
            bound_up: Upper bound of the distribution support.
            log_spacing: Whether to use logarithmic spacing.
            device: Device for the tensors.
            dtype: Data type for the tensors.
            log_min_positive_edge: Minimum positive edge when using log spacing. The log2-value of this argument
                will be passed to torch.logspace. Too small values, approx below 1e-9, will result in poor bin spacing.

        Returns:
            Tuple of (bin_edges, bin_centers, bin_widths).
        """
        if log_spacing:
            if not math.isclose(-bound_low, bound_up):
                raise ValueError("log_spacing requires symmetric bounds: -bound_low == bound_up")
            if bound_up <= 0:
                raise ValueError("log_spacing requires bound_up > 0")
            if num_bins % 2 != 0:
                raise ValueError("log_spacing requires even number of bins")

            half_bins = num_bins // 2

            # Create positive side: 0, internal edges, bound_up.
            if half_bins == 1:
                # Special case where we only use the boundary edges.
                positive_edges = torch.tensor([bound_up])
            else:
                # Create half_bins - 1 internal edges between 0 and bound_up.
                internal_positive = torch.logspace(
                    start=math.log2(log_min_positive_edge),
                    end=math.log2(bound_up),
                    steps=half_bins,
                    base=2,
                )
                positive_edges = torch.cat([internal_positive[:-1], torch.tensor([bound_up])])

            # Mirror for the negative side (excluding 0).
            negative_edges = -positive_edges.flip(0)

            # Combine to [negative_boundary, negative_internal, 0, positive_internal, positive_boundary].
            bin_edges = torch.cat([negative_edges, torch.tensor([0.0]), positive_edges])

        else:
            # Linear spacing.
            bin_edges = torch.linspace(start=bound_low, end=bound_up, steps=num_bins + 1)

        bin_centers = (bin_edges[:-1] + bin_edges[1:]) * 0.5
        bin_widths = bin_edges[1:] - bin_edges[:-1]

        # Move to specified device and dtype.
        bin_edges = bin_edges.to(device=device, dtype=dtype)
        bin_centers = bin_centers.to(device=device, dtype=dtype)
        bin_widths = bin_widths.to(device=device, dtype=dtype)

        return bin_edges, bin_centers, bin_widths

    @property
    def num_bins(self) -> int:
        """Number of bins making up the PiecewiseConstantBinnedCDF."""
        return self.logits.shape[-1]

    @property
    def num_edges(self) -> int:
        """Number of bins edges of the PiecewiseConstantBinnedCDF."""
        return self.bin_edges.shape[0]

    @property
    def bin_probs(self) -> torch.Tensor:
        """Get normalized probabilities for each bin, of shape (*batch_shape, num_bins)."""
        if self.normalization_method == "sigmoid":
            raw_probs = torch.sigmoid(self.logits)  # shape: (*batch_shape, num_bins)
            bin_probs = raw_probs / raw_probs.sum(dim=-1, keepdim=True)
        else:
            bin_probs = torch.softmax(self.logits, dim=-1)  # shape: (*batch_shape, num_bins)
        return bin_probs

    @property
    def mean(self) -> torch.Tensor:
        """Compute mean of the distribution, i.e., the weighted average of bin centers.

        Returns:
            Tensor of shape (*batch_shape,).
        """
        weighted_centers = self.bin_probs * self.bin_centers  # shape: (*batch_shape, num_bins)
        return torch.sum(weighted_centers, dim=-1)

    @property
    def variance(self) -> torch.Tensor:
        """Compute variance of the distribution.

        Returns:
            Tensor of shape (*batch_shape,).
        """
        # E[X^2] = weighted squared bin centers.
        weighted_centers_sq = self.bin_probs * (self.bin_centers**2)  # shape: (*batch_shape, num_bins)
        second_moment = torch.sum(weighted_centers_sq, dim=-1)  # shape: (*batch_shape,)

        # Var = E[X^2] - E[X]^2.
        return second_moment - self.mean**2

    @property
    def support(self) -> constraints.Constraint:
        """Support of this distribution. The resolution also depends on the number of bins."""
        return constraints.interval(self.bound_low, self.bound_up)

    @property
    def arg_constraints(self) -> dict[str, constraints.Constraint]:
        """Constraints that should be satisfied by each argument of this distribution. None for this class."""
        return {"logits": constraints.real}

    def expand(
        self, batch_shape: torch.Size | list[int] | tuple[int, ...], _instance: Distribution | None = None
    ) -> "PiecewiseConstantBinnedCDF":
        """Expand distribution to new batch shape. This creates a new instance."""
        expanded_logits = self.logits.expand((*torch.Size(batch_shape), self.num_bins))
        return self.__class__(
            logits=expanded_logits,
            bound_low=self.bound_low,
            bound_up=self.bound_up,
            log_spacing=self.log_spacing,
            validate_args=self._validate_args,
        )

    def _prepare_input(self, value: torch.Tensor) -> tuple[torch.Tensor, int]:
        """Prepare the input tensor for `log_prob`, `prob`, `cdf` and `icdf` computations.

        This method handles device/dtype transfer, batch dimension alignment, and broadcasting.

        Args:
            value: Input tensor to prepare. Expected shape: `(*sample_shape, *batch_shape)` or broadcastable to it.
                For example, if `batch_shape` is `(B1, B2)` and `value` is `(S1, S2)`, it will be broadcast to
                `(S1, S2, B1, B2)`. If `value` is `(B1, B2)` (no sample dims), it remains `(B1, B2)`.

        Returns:
            A tuple containing:
            - Prepared `value` tensor, of shape: `(*sample_shape, *batch_shape)`.
            - `num_sample_dims`: The number of sample dimensions in the prepared `value` tensor.
        """
        value = value.to(dtype=self.logits.dtype, device=self.logits.device)

        # This ensures the batch dimension is the last dimension.
        if len(self.batch_shape) > 0:  # noqa: SIM102
            # Check if the rightmost dimensions of value match batch_shape.
            # If they don't, we assume value is missing the batch dimensions.
            if value.shape[-len(self.batch_shape) :] != self.batch_shape:
                value = value.unsqueeze(-1)

        num_sample_dims = max(0, value.ndim - len(self.batch_shape))
        target_shape = self._extended_shape(sample_shape=value.shape[:num_sample_dims])
        value = value.expand(target_shape)
        value = value.contiguous()  # for searchsorted later

        return value, num_sample_dims

    def _get_bin_indices(
        self, value: torch.Tensor, bin_edges: torch.Tensor | None = None, bin_centers: torch.Tensor | None = None
    ) -> torch.Tensor:
        """Get bin indices for the given values using binary search.

        Args:
            value: Input tensor of shape (*sample_shape, *batch_shape).
            bin_edges: Tensor of bin edges, of shape (num_bins + 1,). If provided, the bin indices are determined based
                on the edges.
            bin_centers: Tensor of bin centers, of shape (num_bins,). If provided, the bin indices are determined based
                on the centers.

        Returns:
            Tensor of bin indices for the given values, of shape (*sample_shape, *batch_shape), with values in
            [0, num_bins - 1] if the bins are defined by their edges or with values in [0, num_bins] if the bins are
            defined by their centers.
        """
        if bin_edges is not None and bin_centers is not None:
            raise ValueError("Provide either edges or centers as input, not both.")

        # Use binary search to find which bin each value belongs to. The torch.searchsorted function returns the
        # index where value would be inserted to maintain sorted order.
        if bin_edges is not None:
            # Since bins are defined as [edge[i], edge[i + 1]), we subtract 1 to get the bin index.
            bin_idcs = torch.searchsorted(bin_edges, value, right=True) - 1
        elif bin_centers is not None:
            # If value < first center, returns 0 -> gets 0.0 from cumsum_probs
            # If value >= last center, returns num_bins -> gets 1.0 from cumsum_probs
            bin_idcs = torch.searchsorted(bin_centers, value, right=True)
        else:
            raise ValueError("Either edges or centers must be provided to determine bin indices.")

        # Clamp the output of torch.searchsorted to valid range to handle edge cases:
        # - values below bound_low would give bin_idx = -1
        # - values at bound_up would give bin_idx = num_bins
        if bin_edges is not None:
            bin_idcs = torch.clamp(bin_idcs, 0, self.num_bins - 1)
        elif bin_centers is not None:
            bin_idcs = torch.clamp(bin_idcs, 0, self.num_bins)

        return bin_idcs

    def _gather_from_bins(
        self, params: torch.Tensor, bin_idcs: torch.Tensor, num_sample_dims: int, target_shape: torch.Size
    ) -> torch.Tensor:
        """Gather bin-specific parameters using aligned indices.

        Args:
            params: Tensor used as the input to gather from, of shape (*batch_shape, num_bins) or
                (*batch_shape, num_bins + 1).
            bin_idcs: Indices used to gather by, of shape (*sample_shape, *batch_shape).
            num_sample_dims: Number of leading sample dimensions in the input.
            target_shape: The shape to expand to, (*sample_shape, *batch_shape).

        Returns:
            Gathered values of shape (*sample_shape, *batch_shape).
        """
        # Add singleton dimensions for sample_shape: (1, ..., 1, *batch_shape, num_bins).
        params_view = params.view((1,) * num_sample_dims + params.shape)

        # Expand to match the full target shape of the input.
        params_expanded = params_view.expand(*target_shape, -1)

        # Gather along the last dimension. The index must be unsqueezed if indices doesn't have the bin dim yet.
        # Use gather with automatic broadcasting. unsqueeze(-1) provides the index dimension,
        # and squeeze(-1) removes it from the result.
        if bin_idcs.ndim == len(target_shape):
            bin_idcs = bin_idcs.unsqueeze(-1)
        gathered = torch.gather(params_expanded, dim=-1, index=bin_idcs).squeeze(-1)

        return gathered

    def log_prob(self, value: torch.Tensor) -> torch.Tensor:
        """Compute the log-probability density at given values.

        Args:
            value: Values at which to compute the log-PDF.
                Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

        Returns:
            Log-PDF values corresponding to the input values.
            Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
        """
        if self._validate_args:
            self._validate_sample(value)

        value_prep, num_sample_dims = self._prepare_input(value)

        bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)

        # Calculate the log-probabilities directly for stability.
        if self.normalization_method == "sigmoid":
            # Normalized logsigmoid: log(sigmoid(x) / sum(sigmoid(x)))
            log_raw = logsigmoid(self.logits)
            log_normalization = torch.logsumexp(log_raw, dim=-1, keepdim=True)
            log_bin_probs = log_raw - log_normalization
        else:
            log_bin_probs = log_softmax(self.logits, dim=-1)

        log_probs = self._gather_from_bins(log_bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        return log_probs

    def prob(self, value: torch.Tensor) -> torch.Tensor:
        """Compute probability density at given values.

        Args:
            value: Values at which to compute the PDF.
                Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

        Returns:
            PDF values corresponding to the input values.
            Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
        """
        if self._validate_args:
            self._validate_sample(value)

        value_prep, num_sample_dims = self._prepare_input(value)

        bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)

        probs = self._gather_from_bins(self.bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        return probs

    def cdf(self, value: torch.Tensor) -> torch.Tensor:
        """Compute cumulative distribution function at given values.

        Args:
            value: Values at which to compute the CDF.
                Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

        Returns:
            CDF values in [0, 1] corresponding to the input values.
            Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
        """
        if self._validate_args:
            self._validate_sample(value)

        value_prep, num_sample_dims = self._prepare_input(value)

        bin_idcs = self._get_bin_indices(value_prep, bin_centers=self.bin_centers)

        # Compute the cumulative sum of bin probabilities.
        # Prepend 0 for the case where no bins are active.
        cumsum_probs = torch.cumsum(self.bin_probs, dim=-1)  # shape: (*batch_shape, num_bins)
        zero_prefix = torch.zeros(*self.batch_shape, 1, dtype=self.logits.dtype, device=self.logits.device)
        cumsum_probs = torch.cat([zero_prefix, cumsum_probs], dim=-1)  # shape: (*batch_shape, num_bins + 1)

        cdf_values = self._gather_from_bins(cumsum_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        return cdf_values

    def icdf(self, value: torch.Tensor) -> torch.Tensor:
        """Compute the inverse CDF, i.e., the quantile function, at the given values.

        Args:
            value: Values in [0, 1] at which to compute the inverse CDF.
                Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

        Returns:
            Quantiles in [bound_low, bound_up] corresponding to the input CDF values.
            Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
        """
        if self._validate_args:
            self._validate_sample(value)

        value_prep, num_sample_dims = self._prepare_input(value)

        # Compute CDF at bin edges. Prepend zeros to the cumsum of probabilities as this is always the first edge.
        cdf_edges = torch.cat(
            [
                torch.zeros(*self.batch_shape, 1, dtype=self.logits.dtype, device=self.logits.device),
                torch.cumsum(self.bin_probs, dim=-1),  # shape: (*batch_shape, num_bins)
            ],
            dim=-1,
        )  # [0, p1, p1+p2, ..., 1.0], shape: (*batch_shape, num_bins + 1)

        # Prepend singleton dimensions for sample_shape to cdf_edges and expand to match value.
        cdf_edges_expanded = cdf_edges.view((1,) * num_sample_dims + cdf_edges.shape)
        cdf_edges_expanded = cdf_edges_expanded.expand(*value_prep.shape, -1)
        cdf_edges_expanded = cdf_edges_expanded.contiguous()

        bin_idcs = self._get_bin_indices(value_prep.unsqueeze(-1), bin_edges=cdf_edges_expanded)

        quantiles = self._gather_from_bins(self.bin_centers, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        return quantiles  # shape: (*sample_shape, *batch_shape)

    @torch.no_grad()
    def sample(self, sample_shape: torch.Size | list[int] | tuple[int, ...] = _size) -> torch.Tensor:
        """Sample from the distribution by passing uniformly random draws from [0, 1] thought the inverse CDF.

        Args:
            sample_shape: Shape of the samples to draw.

        Returns:
            Samples of shape (sample_shape + batch_shape), where batch_shape is the batch shape of the distribution.
        """
        # Determine the final shape of the output tensor.
        shape = self._extended_shape(sample_shape)

        # Sample in [0, 1] and transform through inverse CDF to get samples in [bound_low, bound_up].
        uniform_samples = torch.rand(shape, dtype=self.logits.dtype, device=self.logits.device)
        samples = self.icdf(uniform_samples)

        return samples

    def entropy(self) -> torch.Tensor:
        r"""Compute Shannon entropy of the discrete distribution.

        $$H[X] = -\sum_{i=1}^{n} p_i \log p_i$$
        where $p_i$ is the probability mass of bin $i$.

        Returns:
            Tensor of shape (*batch_shape,).
        """
        bin_probs = self.bin_probs

        # Compute entropy per bin and sum over bins. Add small epsilon for numerical stability in log.
        entropy_per_bin = bin_probs * torch.log(bin_probs + 1e-8)  # shape: (*batch_shape, num_bins)

        # Sum over bins to get total entropy.
        return -torch.sum(entropy_per_bin, dim=-1)

    def __repr__(self) -> str:
        """String representation of the distribution."""
        return (
            f"{self.__class__.__name__}(logits_shape: {self.logits.shape}, bound_low: {self.bound_low}, "
            f"bound_up: {self.bound_up}, log_spacing: {self.log_spacing}, "
            f"normalization_method: {self.normalization_method})"
        )
arg_constraints property

Constraints that should be satisfied by each argument of this distribution. None for this class.

bin_probs property

Get normalized probabilities for each bin, of shape (*batch_shape, num_bins).

mean property

Compute mean of the distribution, i.e., the weighted average of bin centers.

Returns:

Type Description
Tensor

Tensor of shape (*batch_shape,).

num_bins property

Number of bins making up the PiecewiseConstantBinnedCDF.

num_edges property

Number of bins edges of the PiecewiseConstantBinnedCDF.

support property

Support of this distribution. The resolution also depends on the number of bins.

variance property

Compute variance of the distribution.

Returns:

Type Description
Tensor

Tensor of shape (*batch_shape,).

__init__(logits, bound_low=-1000.0, bound_up=1000.0, log_spacing=False, normalization_method='sigmoid', validate_args=None)

Initializer.

Parameters:

Name Type Description Default
logits Tensor

Raw logits for the bin probabilities (before sigmoid), of shape (*batch_shape, num_bins)

required
bound_low float

Lower bound of the distribution support, needs to be finite.

-1000.0
bound_up float

Upper bound of the distribution support, needs to be finite.

1000.0
log_spacing bool

Whether logarithmic (base = 2) spacing for the bins or linear spacing should be used.

False
normalization_method Literal['sigmoid', 'softmax']

How to normalize the probabilities. Either "sigmoid" or "softmax". With "sigmoid", each bin is independently activated, while with "softmax", the bins activations influence each other.

'sigmoid'
validate_args bool | None

Whether to validate arguments. Carried over to keep the interface with the base class.

None
Source code in binned_cdf/piecewise_constant_binned_cdf.py
def __init__(
    self,
    logits: torch.Tensor,
    bound_low: float = -1e3,
    bound_up: float = 1e3,
    log_spacing: bool = False,
    normalization_method: Literal["sigmoid", "softmax"] = "sigmoid",
    validate_args: bool | None = None,
) -> None:
    """Initializer.

    Args:
        logits: Raw logits for the bin probabilities (before sigmoid), of shape (*batch_shape, num_bins)
        bound_low: Lower bound of the distribution support, needs to be finite.
        bound_up: Upper bound of the distribution support, needs to be finite.
        log_spacing: Whether logarithmic (base = 2) spacing for the bins or linear spacing should be used.
        normalization_method: How to normalize the probabilities. Either "sigmoid" or "softmax". With "sigmoid",
            each bin is independently activated, while with "softmax", the bins activations influence each other.
        validate_args: Whether to validate arguments. Carried over to keep the interface with the base class.
    """
    self.logits = logits
    self.bound_low = bound_low
    self.bound_up = bound_up
    self.normalization_method = normalization_method
    self.log_spacing = log_spacing

    # Create bin structure (same for all batch dimensions).
    self.bin_edges, self.bin_centers, self.bin_widths = self._create_bins(
        num_bins=logits.shape[-1],
        bound_low=bound_low,
        bound_up=bound_up,
        log_spacing=log_spacing,
        device=logits.device,
        dtype=logits.dtype,
    )

    # Determine batch shape based on the logits. The event shape is scalar since this is a univariate distribution.
    super().__init__(batch_shape=logits.shape[:-1], event_shape=torch.Size([]), validate_args=validate_args)
__repr__()

String representation of the distribution.

Source code in binned_cdf/piecewise_constant_binned_cdf.py
def __repr__(self) -> str:
    """String representation of the distribution."""
    return (
        f"{self.__class__.__name__}(logits_shape: {self.logits.shape}, bound_low: {self.bound_low}, "
        f"bound_up: {self.bound_up}, log_spacing: {self.log_spacing}, "
        f"normalization_method: {self.normalization_method})"
    )
cdf(value)

Compute cumulative distribution function at given values.

Parameters:

Name Type Description Default
value Tensor

Values at which to compute the CDF. Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

required

Returns:

Type Description
Tensor

CDF values in [0, 1] corresponding to the input values.

Tensor

Output shape: same as value shape after broadcasting, i.e., (*sample_shape, *batch_shape).

Source code in binned_cdf/piecewise_constant_binned_cdf.py
def cdf(self, value: torch.Tensor) -> torch.Tensor:
    """Compute cumulative distribution function at given values.

    Args:
        value: Values at which to compute the CDF.
            Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

    Returns:
        CDF values in [0, 1] corresponding to the input values.
        Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
    """
    if self._validate_args:
        self._validate_sample(value)

    value_prep, num_sample_dims = self._prepare_input(value)

    bin_idcs = self._get_bin_indices(value_prep, bin_centers=self.bin_centers)

    # Compute the cumulative sum of bin probabilities.
    # Prepend 0 for the case where no bins are active.
    cumsum_probs = torch.cumsum(self.bin_probs, dim=-1)  # shape: (*batch_shape, num_bins)
    zero_prefix = torch.zeros(*self.batch_shape, 1, dtype=self.logits.dtype, device=self.logits.device)
    cumsum_probs = torch.cat([zero_prefix, cumsum_probs], dim=-1)  # shape: (*batch_shape, num_bins + 1)

    cdf_values = self._gather_from_bins(cumsum_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    return cdf_values
entropy()

Compute Shannon entropy of the discrete distribution.

$\(H[X] = -\sum_{i=1}^{n} p_i \log p_i\)$ where \(p_i\) is the probability mass of bin \(i\).

Returns:

Type Description
Tensor

Tensor of shape (*batch_shape,).

Source code in binned_cdf/piecewise_constant_binned_cdf.py
def entropy(self) -> torch.Tensor:
    r"""Compute Shannon entropy of the discrete distribution.

    $$H[X] = -\sum_{i=1}^{n} p_i \log p_i$$
    where $p_i$ is the probability mass of bin $i$.

    Returns:
        Tensor of shape (*batch_shape,).
    """
    bin_probs = self.bin_probs

    # Compute entropy per bin and sum over bins. Add small epsilon for numerical stability in log.
    entropy_per_bin = bin_probs * torch.log(bin_probs + 1e-8)  # shape: (*batch_shape, num_bins)

    # Sum over bins to get total entropy.
    return -torch.sum(entropy_per_bin, dim=-1)
expand(batch_shape, _instance=None)

Expand distribution to new batch shape. This creates a new instance.

Source code in binned_cdf/piecewise_constant_binned_cdf.py
def expand(
    self, batch_shape: torch.Size | list[int] | tuple[int, ...], _instance: Distribution | None = None
) -> "PiecewiseConstantBinnedCDF":
    """Expand distribution to new batch shape. This creates a new instance."""
    expanded_logits = self.logits.expand((*torch.Size(batch_shape), self.num_bins))
    return self.__class__(
        logits=expanded_logits,
        bound_low=self.bound_low,
        bound_up=self.bound_up,
        log_spacing=self.log_spacing,
        validate_args=self._validate_args,
    )
icdf(value)

Compute the inverse CDF, i.e., the quantile function, at the given values.

Parameters:

Name Type Description Default
value Tensor

Values in [0, 1] at which to compute the inverse CDF. Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

required

Returns:

Type Description
Tensor

Quantiles in [bound_low, bound_up] corresponding to the input CDF values.

Tensor

Output shape: same as value shape after broadcasting, i.e., (*sample_shape, *batch_shape).

Source code in binned_cdf/piecewise_constant_binned_cdf.py
def icdf(self, value: torch.Tensor) -> torch.Tensor:
    """Compute the inverse CDF, i.e., the quantile function, at the given values.

    Args:
        value: Values in [0, 1] at which to compute the inverse CDF.
            Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

    Returns:
        Quantiles in [bound_low, bound_up] corresponding to the input CDF values.
        Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
    """
    if self._validate_args:
        self._validate_sample(value)

    value_prep, num_sample_dims = self._prepare_input(value)

    # Compute CDF at bin edges. Prepend zeros to the cumsum of probabilities as this is always the first edge.
    cdf_edges = torch.cat(
        [
            torch.zeros(*self.batch_shape, 1, dtype=self.logits.dtype, device=self.logits.device),
            torch.cumsum(self.bin_probs, dim=-1),  # shape: (*batch_shape, num_bins)
        ],
        dim=-1,
    )  # [0, p1, p1+p2, ..., 1.0], shape: (*batch_shape, num_bins + 1)

    # Prepend singleton dimensions for sample_shape to cdf_edges and expand to match value.
    cdf_edges_expanded = cdf_edges.view((1,) * num_sample_dims + cdf_edges.shape)
    cdf_edges_expanded = cdf_edges_expanded.expand(*value_prep.shape, -1)
    cdf_edges_expanded = cdf_edges_expanded.contiguous()

    bin_idcs = self._get_bin_indices(value_prep.unsqueeze(-1), bin_edges=cdf_edges_expanded)

    quantiles = self._gather_from_bins(self.bin_centers, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    return quantiles  # shape: (*sample_shape, *batch_shape)
log_prob(value)

Compute the log-probability density at given values.

Parameters:

Name Type Description Default
value Tensor

Values at which to compute the log-PDF. Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

required

Returns:

Type Description
Tensor

Log-PDF values corresponding to the input values.

Tensor

Output shape: same as value shape after broadcasting, i.e., (*sample_shape, *batch_shape).

Source code in binned_cdf/piecewise_constant_binned_cdf.py
def log_prob(self, value: torch.Tensor) -> torch.Tensor:
    """Compute the log-probability density at given values.

    Args:
        value: Values at which to compute the log-PDF.
            Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

    Returns:
        Log-PDF values corresponding to the input values.
        Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
    """
    if self._validate_args:
        self._validate_sample(value)

    value_prep, num_sample_dims = self._prepare_input(value)

    bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)

    # Calculate the log-probabilities directly for stability.
    if self.normalization_method == "sigmoid":
        # Normalized logsigmoid: log(sigmoid(x) / sum(sigmoid(x)))
        log_raw = logsigmoid(self.logits)
        log_normalization = torch.logsumexp(log_raw, dim=-1, keepdim=True)
        log_bin_probs = log_raw - log_normalization
    else:
        log_bin_probs = log_softmax(self.logits, dim=-1)

    log_probs = self._gather_from_bins(log_bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    return log_probs
prob(value)

Compute probability density at given values.

Parameters:

Name Type Description Default
value Tensor

Values at which to compute the PDF. Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

required

Returns:

Type Description
Tensor

PDF values corresponding to the input values.

Tensor

Output shape: same as value shape after broadcasting, i.e., (*sample_shape, *batch_shape).

Source code in binned_cdf/piecewise_constant_binned_cdf.py
def prob(self, value: torch.Tensor) -> torch.Tensor:
    """Compute probability density at given values.

    Args:
        value: Values at which to compute the PDF.
            Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

    Returns:
        PDF values corresponding to the input values.
        Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
    """
    if self._validate_args:
        self._validate_sample(value)

    value_prep, num_sample_dims = self._prepare_input(value)

    bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)

    probs = self._gather_from_bins(self.bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    return probs
sample(sample_shape=_size)

Sample from the distribution by passing uniformly random draws from [0, 1] thought the inverse CDF.

Parameters:

Name Type Description Default
sample_shape Size | list[int] | tuple[int, ...]

Shape of the samples to draw.

_size

Returns:

Type Description
Tensor

Samples of shape (sample_shape + batch_shape), where batch_shape is the batch shape of the distribution.

Source code in binned_cdf/piecewise_constant_binned_cdf.py
@torch.no_grad()
def sample(self, sample_shape: torch.Size | list[int] | tuple[int, ...] = _size) -> torch.Tensor:
    """Sample from the distribution by passing uniformly random draws from [0, 1] thought the inverse CDF.

    Args:
        sample_shape: Shape of the samples to draw.

    Returns:
        Samples of shape (sample_shape + batch_shape), where batch_shape is the batch shape of the distribution.
    """
    # Determine the final shape of the output tensor.
    shape = self._extended_shape(sample_shape)

    # Sample in [0, 1] and transform through inverse CDF to get samples in [bound_low, bound_up].
    uniform_samples = torch.rand(shape, dtype=self.logits.dtype, device=self.logits.device)
    samples = self.icdf(uniform_samples)

    return samples

binned_cdf.piecewise_linear_binned_cdf

PiecewiseLinearBinnedCDF

Bases: PiecewiseConstantBinnedCDF

A continuous probability distribution parameterized by binned logits for the CDF.

Unlike [PiecewiseConstantBinnedCDF][binned_cdf.piecewise_constant_cdf.PiecewiseConstantBinnedCDF], which evaluates the CDF as a step function over bin centers, this class implements a true piecewise-linear CDF, i.e., histogram PDF, interpolating smoothly between bin edges.

Source code in binned_cdf/piecewise_linear_binned_cdf.py
class PiecewiseLinearBinnedCDF(PiecewiseConstantBinnedCDF):
    """A continuous probability distribution parameterized by binned logits for the CDF.

    Unlike [PiecewiseConstantBinnedCDF][binned_cdf.piecewise_constant_cdf.PiecewiseConstantBinnedCDF], which evaluates
    the CDF as a step function over bin centers, this class implements a true piecewise-linear CDF, i.e., histogram PDF,
    interpolating smoothly between bin edges.
    """

    @property
    def variance(self) -> torch.Tensor:
        """Compute variance of the distribution.

        Note:
            Since the distribution is piecewise linear, the variance includes both the discrete variance from the
            bin probabilities and the intra-bin variance due to linear interpolation called Sheppard's correction,
            which assumes that probabilities are uniformly distributed within each bin.

        Returns:
            Tensor of shape (*batch_shape,).
        """
        discrete_var = super().variance
        intra_bin_var = torch.sum(self.bin_probs * (self.bin_widths**2) / 12.0, dim=-1)  # Sheppard's correction
        return discrete_var + intra_bin_var

    def log_prob(self, value: torch.Tensor) -> torch.Tensor:
        """Compute the log-probability density at given values.

        Args:
            value: Values at which to compute the log-PDF.
                Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

        Returns:
            Log-PDF values corresponding to the input values.
            Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
        """
        value_prep, num_sample_dims = self._prepare_input(value)

        # Compute the log of the probability mass for the bin the value falls into.
        log_mass = super().log_prob(value)  # also validates the args if self._validate_args is True

        # We need to gather the width of the bin the value falls into.
        bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)
        widths = self._gather_from_bins(self.bin_widths, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        # Log density = log(mass / width) = log_mass - log_width.
        eps = torch.finfo(widths.dtype).eps
        log_prob = log_mass - torch.log(widths + 2 * eps)

        return log_prob

    def prob(self, value: torch.Tensor) -> torch.Tensor:
        """Compute probability density at given values.

        Args:
            value: Values at which to compute the PDF.
                Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

        Returns:
            PDF values corresponding to the input values.
            Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
        """
        if self._validate_args:
            self._validate_sample(value)

        value_prep, num_sample_dims = self._prepare_input(value)

        bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)

        # Gather normalized mass and bin width.
        masses = self._gather_from_bins(self.bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)
        widths = self._gather_from_bins(self.bin_widths, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        # Density = p(bin_i) / width_i.
        eps = torch.finfo(widths.dtype).eps
        prob = masses / (widths + 2 * eps)

        return prob

    def cdf(self, value: torch.Tensor) -> torch.Tensor:
        """Compute cumulative distribution function at given values.

        Args:
            value: Values at which to compute the CDF.
                Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

        Returns:
            CDF values in [0, 1] corresponding to the input values.
            Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
        """
        if self._validate_args:
            self._validate_sample(value)

        value_prep, num_sample_dims = self._prepare_input(value)

        # Find the bin in probability space.
        bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)

        # Gather the interpolation parameters.
        left_edges = self._gather_from_bins(
            self.bin_edges[:-1], bin_idcs, num_sample_dims, target_shape=value_prep.shape
        )
        widths = self._gather_from_bins(self.bin_widths, bin_idcs, num_sample_dims, target_shape=value_prep.shape)
        masses = self._gather_from_bins(self.bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        # Get base CDF at the left edge of the bin.
        # Prepend 0 for the case where no bins are active.
        cumsum_probs = torch.cumsum(self.bin_probs, dim=-1)
        zero_prefix = torch.zeros(*self.batch_shape, 1, dtype=self.logits.dtype, device=self.logits.device)
        cumsum_probs = torch.cat([zero_prefix, cumsum_probs], dim=-1)  # shape: (*batch_shape, num_bins + 1)
        base_cdf = self._gather_from_bins(cumsum_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        # Interpolate: cdf = base_cdf + (x_input - x_left_edge) * (mass / width)
        eps = torch.finfo(widths.dtype).eps
        alpha = (value_prep - left_edges) / (widths + 2 * eps)
        alpha = torch.clamp(alpha, 0.0, 1.0)  # prevent extrapolation
        cdf_vals = base_cdf + alpha * masses

        return cdf_vals

    def icdf(self, value: torch.Tensor) -> torch.Tensor:
        """Compute the inverse CDF, i.e., the quantile function, at the given values.

        Args:
            value: Values in [0, 1] at which to compute the inverse CDF.
                Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

        Returns:
            Quantiles in [bound_low, bound_up] corresponding to the input CDF values.
            Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
        """
        if self._validate_args:
            self._validate_sample(value)

        value_prep, num_sample_dims = self._prepare_input(value)

        # Get the CDF edges (y-coordinates of the piecewise linear segments).
        zero_prefix = torch.zeros(*self.batch_shape, 1, dtype=self.logits.dtype, device=self.logits.device)
        cdf_edges = torch.cat([zero_prefix, torch.cumsum(self.bin_probs, dim=-1)], dim=-1)

        # Find the bin in probability space.
        cdf_edges_aligned = (
            cdf_edges.view((1,) * num_sample_dims + cdf_edges.shape).expand(*value_prep.shape, -1).contiguous()
        )
        bin_idcs = self._get_bin_indices(value_prep.unsqueeze(-1), bin_edges=cdf_edges_aligned)

        # Gather the probability base.
        base_cdf = self._gather_from_bins(cdf_edges, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        # Gather the interpolation parameters.
        left_edges = self._gather_from_bins(
            self.bin_edges[:-1], bin_idcs, num_sample_dims, target_shape=value_prep.shape
        )
        widths = self._gather_from_bins(self.bin_widths, bin_idcs, num_sample_dims, target_shape=value_prep.shape)
        masses = self._gather_from_bins(self.bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

        # Interpolate: x = x_left_edge + (target_cdf - base_cdf) * (width / mass)
        eps = torch.finfo(masses.dtype).eps
        slope = widths / (masses + 2 * eps)  # add eps to avoid division by zero for bins with no mass
        interp_value = left_edges + (value_prep - base_cdf) * slope

        quantiles = torch.clamp(interp_value, self.bound_low, self.bound_up)

        return quantiles

    def entropy(self) -> torch.Tensor:
        r"""Compute differential entropy of the distribution.

        Entropy H(X) = -\sum_{x \in \mathcal{X}} p(x) \log( p(x) )

        Note:
            Here, we are doing an approximation by treating each bin as a uniform distribution over its width.

        Returns:
            Tensor of shape (*batch_shape,).
        """
        bin_probs = self.bin_probs

        # Get the PDF values at bin centers.
        pdf_values = bin_probs / self.bin_widths  # shape: (*batch_shape, num_bins)

        # Entropy ≈ -∑ p_i * log(pdf_i) * bin_width_i.
        log_pdf = torch.log(pdf_values + 1e-8)  # small epsilon for stability
        entropy_per_bin = -bin_probs * log_pdf

        # Sum over bins to get total entropy.
        return torch.sum(entropy_per_bin, dim=-1)
variance property

Compute variance of the distribution.

Note

Since the distribution is piecewise linear, the variance includes both the discrete variance from the bin probabilities and the intra-bin variance due to linear interpolation called Sheppard's correction, which assumes that probabilities are uniformly distributed within each bin.

Returns:

Type Description
Tensor

Tensor of shape (*batch_shape,).

cdf(value)

Compute cumulative distribution function at given values.

Parameters:

Name Type Description Default
value Tensor

Values at which to compute the CDF. Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

required

Returns:

Type Description
Tensor

CDF values in [0, 1] corresponding to the input values.

Tensor

Output shape: same as value shape after broadcasting, i.e., (*sample_shape, *batch_shape).

Source code in binned_cdf/piecewise_linear_binned_cdf.py
def cdf(self, value: torch.Tensor) -> torch.Tensor:
    """Compute cumulative distribution function at given values.

    Args:
        value: Values at which to compute the CDF.
            Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

    Returns:
        CDF values in [0, 1] corresponding to the input values.
        Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
    """
    if self._validate_args:
        self._validate_sample(value)

    value_prep, num_sample_dims = self._prepare_input(value)

    # Find the bin in probability space.
    bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)

    # Gather the interpolation parameters.
    left_edges = self._gather_from_bins(
        self.bin_edges[:-1], bin_idcs, num_sample_dims, target_shape=value_prep.shape
    )
    widths = self._gather_from_bins(self.bin_widths, bin_idcs, num_sample_dims, target_shape=value_prep.shape)
    masses = self._gather_from_bins(self.bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    # Get base CDF at the left edge of the bin.
    # Prepend 0 for the case where no bins are active.
    cumsum_probs = torch.cumsum(self.bin_probs, dim=-1)
    zero_prefix = torch.zeros(*self.batch_shape, 1, dtype=self.logits.dtype, device=self.logits.device)
    cumsum_probs = torch.cat([zero_prefix, cumsum_probs], dim=-1)  # shape: (*batch_shape, num_bins + 1)
    base_cdf = self._gather_from_bins(cumsum_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    # Interpolate: cdf = base_cdf + (x_input - x_left_edge) * (mass / width)
    eps = torch.finfo(widths.dtype).eps
    alpha = (value_prep - left_edges) / (widths + 2 * eps)
    alpha = torch.clamp(alpha, 0.0, 1.0)  # prevent extrapolation
    cdf_vals = base_cdf + alpha * masses

    return cdf_vals
entropy()

Compute differential entropy of the distribution.

Entropy H(X) = -\sum_{x \in \mathcal{X}} p(x) \log( p(x) )

Note

Here, we are doing an approximation by treating each bin as a uniform distribution over its width.

Returns:

Type Description
Tensor

Tensor of shape (*batch_shape,).

Source code in binned_cdf/piecewise_linear_binned_cdf.py
def entropy(self) -> torch.Tensor:
    r"""Compute differential entropy of the distribution.

    Entropy H(X) = -\sum_{x \in \mathcal{X}} p(x) \log( p(x) )

    Note:
        Here, we are doing an approximation by treating each bin as a uniform distribution over its width.

    Returns:
        Tensor of shape (*batch_shape,).
    """
    bin_probs = self.bin_probs

    # Get the PDF values at bin centers.
    pdf_values = bin_probs / self.bin_widths  # shape: (*batch_shape, num_bins)

    # Entropy ≈ -∑ p_i * log(pdf_i) * bin_width_i.
    log_pdf = torch.log(pdf_values + 1e-8)  # small epsilon for stability
    entropy_per_bin = -bin_probs * log_pdf

    # Sum over bins to get total entropy.
    return torch.sum(entropy_per_bin, dim=-1)
icdf(value)

Compute the inverse CDF, i.e., the quantile function, at the given values.

Parameters:

Name Type Description Default
value Tensor

Values in [0, 1] at which to compute the inverse CDF. Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

required

Returns:

Type Description
Tensor

Quantiles in [bound_low, bound_up] corresponding to the input CDF values.

Tensor

Output shape: same as value shape after broadcasting, i.e., (*sample_shape, *batch_shape).

Source code in binned_cdf/piecewise_linear_binned_cdf.py
def icdf(self, value: torch.Tensor) -> torch.Tensor:
    """Compute the inverse CDF, i.e., the quantile function, at the given values.

    Args:
        value: Values in [0, 1] at which to compute the inverse CDF.
            Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

    Returns:
        Quantiles in [bound_low, bound_up] corresponding to the input CDF values.
        Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
    """
    if self._validate_args:
        self._validate_sample(value)

    value_prep, num_sample_dims = self._prepare_input(value)

    # Get the CDF edges (y-coordinates of the piecewise linear segments).
    zero_prefix = torch.zeros(*self.batch_shape, 1, dtype=self.logits.dtype, device=self.logits.device)
    cdf_edges = torch.cat([zero_prefix, torch.cumsum(self.bin_probs, dim=-1)], dim=-1)

    # Find the bin in probability space.
    cdf_edges_aligned = (
        cdf_edges.view((1,) * num_sample_dims + cdf_edges.shape).expand(*value_prep.shape, -1).contiguous()
    )
    bin_idcs = self._get_bin_indices(value_prep.unsqueeze(-1), bin_edges=cdf_edges_aligned)

    # Gather the probability base.
    base_cdf = self._gather_from_bins(cdf_edges, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    # Gather the interpolation parameters.
    left_edges = self._gather_from_bins(
        self.bin_edges[:-1], bin_idcs, num_sample_dims, target_shape=value_prep.shape
    )
    widths = self._gather_from_bins(self.bin_widths, bin_idcs, num_sample_dims, target_shape=value_prep.shape)
    masses = self._gather_from_bins(self.bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    # Interpolate: x = x_left_edge + (target_cdf - base_cdf) * (width / mass)
    eps = torch.finfo(masses.dtype).eps
    slope = widths / (masses + 2 * eps)  # add eps to avoid division by zero for bins with no mass
    interp_value = left_edges + (value_prep - base_cdf) * slope

    quantiles = torch.clamp(interp_value, self.bound_low, self.bound_up)

    return quantiles
log_prob(value)

Compute the log-probability density at given values.

Parameters:

Name Type Description Default
value Tensor

Values at which to compute the log-PDF. Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

required

Returns:

Type Description
Tensor

Log-PDF values corresponding to the input values.

Tensor

Output shape: same as value shape after broadcasting, i.e., (*sample_shape, *batch_shape).

Source code in binned_cdf/piecewise_linear_binned_cdf.py
def log_prob(self, value: torch.Tensor) -> torch.Tensor:
    """Compute the log-probability density at given values.

    Args:
        value: Values at which to compute the log-PDF.
            Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

    Returns:
        Log-PDF values corresponding to the input values.
        Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
    """
    value_prep, num_sample_dims = self._prepare_input(value)

    # Compute the log of the probability mass for the bin the value falls into.
    log_mass = super().log_prob(value)  # also validates the args if self._validate_args is True

    # We need to gather the width of the bin the value falls into.
    bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)
    widths = self._gather_from_bins(self.bin_widths, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    # Log density = log(mass / width) = log_mass - log_width.
    eps = torch.finfo(widths.dtype).eps
    log_prob = log_mass - torch.log(widths + 2 * eps)

    return log_prob
prob(value)

Compute probability density at given values.

Parameters:

Name Type Description Default
value Tensor

Values at which to compute the PDF. Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

required

Returns:

Type Description
Tensor

PDF values corresponding to the input values.

Tensor

Output shape: same as value shape after broadcasting, i.e., (*sample_shape, *batch_shape).

Source code in binned_cdf/piecewise_linear_binned_cdf.py
def prob(self, value: torch.Tensor) -> torch.Tensor:
    """Compute probability density at given values.

    Args:
        value: Values at which to compute the PDF.
            Expected shape: (*sample_shape, *batch_shape) or broadcastable to it.

    Returns:
        PDF values corresponding to the input values.
        Output shape: same as `value` shape after broadcasting, i.e., (*sample_shape, *batch_shape).
    """
    if self._validate_args:
        self._validate_sample(value)

    value_prep, num_sample_dims = self._prepare_input(value)

    bin_idcs = self._get_bin_indices(value_prep, bin_edges=self.bin_edges)

    # Gather normalized mass and bin width.
    masses = self._gather_from_bins(self.bin_probs, bin_idcs, num_sample_dims, target_shape=value_prep.shape)
    widths = self._gather_from_bins(self.bin_widths, bin_idcs, num_sample_dims, target_shape=value_prep.shape)

    # Density = p(bin_i) / width_i.
    eps = torch.finfo(widths.dtype).eps
    prob = masses / (widths + 2 * eps)

    return prob