Coverage for binned_cdf/bezier_cdf.py: 93%

181 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-05 15:46 +0000

1import math 

2from typing import Literal 

3 

4import torch 

5from torch.distributions import Distribution, constraints 

6 

7_size = torch.Size() 

8 

9 

10class BezierCDF(Distribution): 

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

12 

13 The idea is that the CDF is represented as a Bezier curve, which is a weighted sum of Bernstein basis 

14 polynomials, defined by control points (betas) that are derived from the input logits. 

15 This allows for a smooth, flexible CDF that can capture complex shapes while still being differentiable. 

16 With two learned axes, this is a global parametric curve. Its vertical derivative defines a mixture of Beta 

17 densities in parameter space, with mixture weights given by the normalized vertical increments (deltas). 

18 

19 Normalized, positive increments define monotone control points on each axis, with endpoints fixed at 0 and 1. 

20 For $t \in [0, 1]$, 

21 

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

23 

24 so 

25 

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

27 

28 The two polynomials may have different degrees. Omitting `logits_x`, passing `None`, or supplying 

29 a one-element `logits_x` fixes the horizontal curve to 

30 

31 $$ B_x(t) = t. $$ 

32 

33 Learning multiple horizontal increments allows density to concentrate without increasing the vertical 

34 polynomial degree, but CDF and density evaluation then require numerical inversion. Quantiles only invert 

35 the vertical curve. 

36 

37 Inversion uses bracketed Newton steps and implicit first-order gradients, without retaining the solver graph. 

38 No application-level minimum increment is imposed; extremely concentrated curves remain limited by the input 

39 dtype's precision. Higher-order derivatives through the implicit inverse are not supported. 

40 

41 Note: 

42 Monotone control points provide the structural guarantees of a CDF: monotonicity, values in $[0, 1]$, 

43 and a non-negative PDF. In exact arithmetic, normalizing positive increments gives these guarantees 

44 for any finite logits, without imposing constraints on the parameters during optimization. 

45 

46 With fixed horizontal spacing, the density is a Beta mixture on the normalized support. Classical 

47 Bernstein approximation has uniform error $O(1/n)$ for functions with a bounded second derivative; 

48 this is not a general convergence rate for an end-to-end learned two-axis model. A degree-$n$ mixture 

49 component near the center of a fixed support of width $R$ has approximate standard deviation 

50 

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

52 

53 This explains the smoothing of narrow interior peaks with fixed spacing. It is not a universal minimum 

54 width: boundary components can be narrower, and learned horizontal spacing can further compress peaks. 

55 """ 

56 

57 has_rsample = True 

58 

59 def __init__( 

60 self, 

61 logits_y: torch.Tensor, 

62 logits_x: torch.Tensor | None = None, 

63 bound_low: float = -1e3, 

64 bound_up: float = 1e3, 

65 normalization_method: Literal["sigmoid", "softmax"] = "softmax", 

66 validate_args: bool | None = None, 

67 ) -> None: 

68 """Initializer. 

69 

70 Args: 

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

72 logits_x: Raw horizontal-increment logits, of shape (*batch_shape, degree_x). Batch shapes must 

73 broadcast with logits_y, and both tensors must have the same floating dtype and device. 

74 None uses a one-element zero tensor matching logits_y, fixing the horizontal map to the identity. 

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

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

77 normalization_method: How to normalize the probabilities. Either "sigmoid" or "softmax". With "sigmoid", 

78 each control point is independently activated, while with "softmax", the control point activations 

79 influence each other. 

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

81 """ 

82 if not math.isfinite(bound_low) or not math.isfinite(bound_up) or bound_low >= bound_up: 82 ↛ 83line 82 didn't jump to line 83 because the condition on line 82 was never true

83 raise ValueError("Bounds must be finite with bound_low < bound_up.") 

84 if logits_y.ndim < 1 or logits_y.shape[-1] < 1 or not logits_y.is_floating_point(): 84 ↛ 85line 84 didn't jump to line 85 because the condition on line 84 was never true

85 raise ValueError("logits_y must be a floating tensor with at least one increment.") 

86 if logits_x is not None and (logits_x.ndim < 1 or logits_x.shape[-1] < 1 or not logits_x.is_floating_point()): 86 ↛ 87line 86 didn't jump to line 87 because the condition on line 86 was never true

87 raise ValueError("logits_x must be None or a floating tensor with at least one increment.") 

88 if logits_x is not None and (logits_x.dtype != logits_y.dtype or logits_x.device != logits_y.device): 88 ↛ 89line 88 didn't jump to line 89 because the condition on line 88 was never true

89 raise ValueError("logits_x and logits_y must have the same floating dtype and device.") 

90 

91 logits_x = logits_y.new_zeros(1) if logits_x is None else logits_x 

92 batch_shape = torch.broadcast_shapes(logits_y.shape[:-1], logits_x.shape[:-1]) 

93 self.logits_y = logits_y.expand(*batch_shape, logits_y.shape[-1]) 

94 self.logits_x = logits_x.expand(*batch_shape, logits_x.shape[-1]) 

95 self.bound_low = bound_low 

96 self.bound_up = bound_up 

97 self.normalization_method = normalization_method 

98 

99 # Precompute binomial coefficients, and store them on the same device as logits. 

100 self._binom_coeffs_cdf_y, self._binom_coeffs_pdf_y = self._compute_binomial_coefficients(self.degree_y) 

101 self._binom_coeffs_cdf_x, self._binom_coeffs_pdf_x = self._compute_binomial_coefficients(self.degree_x) 

102 

103 # Calculate parameters (deltas and betas). 

104 self._deltas_y, self._betas_y, self._log_deltas_y = self._compute_deltas_and_betas(self.logits_y) 

105 self._deltas_x, self._betas_x, self._log_deltas_x = self._compute_deltas_and_betas(self.logits_x) 

106 

107 # Determine batch shape based on the logits. The event shape is scalar since this is a univariate distribution. 

108 super().__init__(batch_shape=batch_shape, event_shape=torch.Size([]), validate_args=validate_args) 

109 

110 def __repr__(self) -> str: 

111 """String representation of the distribution.""" 

112 return ( 

113 f"{self.__class__.__name__}(degree_y: {self.degree_y}, degree_x: {self.degree_x}, " 

114 f"batch_shape: {self.batch_shape}, bound_low: {self.bound_low}, " 

115 f"bound_up: {self.bound_up}, normalization_method: {self.normalization_method})" 

116 ) 

117 

118 def _compute_binomial_coefficients(self, degree: int) -> tuple[torch.Tensor, torch.Tensor]: 

119 """Compute the binomial coefficients for the CDF and PDF based on the degree of the Bernstein polynomial. 

120 

121 comb(n, k) = n! / (k! * (n-k)!) is the binomial coefficient, which counts the number of ways to choose k 

122 elements from a set of n elements. 

123 

124 Returns: 

125 coeffs_cdf: Binomial coefficients for the CDF, of shape (degree + 1,). 

126 coeffs_pdf: Binomial coefficients for the PDF, of shape (degree,). 

127 """ 

128 coeffs_cdf = torch.tensor( 

129 [math.comb(degree, i) for i in range(degree + 1)], device=self.logits_y.device, dtype=self.logits_y.dtype 

130 ) 

131 

132 coeffs_pdf = torch.tensor( 

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

134 ) 

135 

136 # Check if any of the binomial coefficients became infinite. 

137 if torch.isinf(coeffs_cdf).any() or torch.isinf(coeffs_pdf).any(): 

138 raise ValueError( 

139 f"Binomial coefficients became infinite for degree {degree}. " 

140 "Consider reducing the (last) dimension of the logits, leading to lower degree polynomial." 

141 ) 

142 

143 return coeffs_cdf, coeffs_pdf 

144 

145 def _compute_deltas_and_betas(self, logits: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

146 r"""Compute the deltas (Beta mixture component weights) and betas (control points) for the Bezier curve based 

147 on the given logits. 

148 

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

150 

151 Returns: 

152 deltas: Weights of the Beta components in the mixture, of shape (*batch_shape, degree). 

153 betas: Control points of the Bezier curve, of shape (*batch_shape, degree + 1). 

154 log_deltas: Log of the deltas, computed in a numerically stable way, of shape (*batch_shape, degree) 

155 """ 

156 # The deltas are the steps themselves (forward differences of betas). 

157 if self.normalization_method == "softmax": 

158 deltas = torch.softmax(logits, dim=-1) # shape: (*batch_shape, degree) 

159 log_deltas = torch.log_softmax(logits, dim=-1) 

160 

161 elif self.normalization_method == "sigmoid": 161 ↛ 166line 161 didn't jump to line 166 because the condition on line 161 was always true

162 log_deltas = torch.log_softmax(torch.nn.functional.logsigmoid(logits), dim=-1) 

163 deltas = log_deltas.exp() 

164 

165 else: 

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

167 

168 # Pad with zeros and ones to enforce the CDF boundary conditions: 

169 # betas = [0, beta_1, ..., beta_{n-1}, beta_n = 1] 

170 zeros = torch.zeros(*deltas.shape[:-1], 1, device=deltas.device, dtype=deltas.dtype) # shape: (*batch_shape, 1) 

171 inner_betas = torch.cumsum(deltas, dim=-1)[..., :-1] 

172 ones = torch.ones(*deltas.shape[:-1], 1, device=deltas.device, dtype=deltas.dtype) 

173 betas = torch.cat([zeros, inner_betas, ones], dim=-1) 

174 

175 return deltas, betas, log_deltas 

176 

177 def _map_to_t_space(self, value: torch.Tensor) -> torch.Tensor: 

178 r"""Map physical values to curve parameters by normalizing to [0, 1], clamping, and inverting $B_x(t)$.""" 

179 value = torch.clamp((value - self.bound_low) / self.support_range, 0, 1) 

180 return self._invert_bezier( 

181 value, self._betas_x, self._deltas_x, self._binom_coeffs_cdf_x, self._binom_coeffs_pdf_x 

182 ) 

183 

184 def _map_to_x_space(self, t: torch.Tensor) -> torch.Tensor: 

185 r"""Map values from the $T$ space $[0, 1]$ back to the original $X$ space using the bounds.""" 

186 t = self._eval_bezier_curve(t, self._betas_x, self._binom_coeffs_cdf_x) 

187 return t * self.support_range + self.bound_low 

188 

189 @property 

190 def support(self) -> constraints.Constraint: 

191 """Support of this distribution.""" 

192 return constraints.interval(self.bound_low, self.bound_up) 

193 

194 @property 

195 def support_range(self) -> float: 

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

197 return self.bound_up - self.bound_low 

198 

199 @property 

200 def arg_constraints(self) -> dict[str, constraints.Constraint]: 

201 """Both logit tensors must contain real values.""" 

202 return {"logits_y": constraints.real, "logits_x": constraints.real} 

203 

204 @property 

205 def degree_y(self) -> int: 

206 r"""Get the degree $n$ of the Bernstein polynomial based on the number of logits. 

207 

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

209 """ 

210 return self.logits_y.shape[-1] 

211 

212 @property 

213 def degree_x(self) -> int: 

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

215 return self.logits_x.shape[-1] 

216 

217 @property 

218 def mean(self) -> torch.Tensor: 

219 r"""Compute the mean by integrating the parametric curve. 

220 

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

222 

223 Note: 

224 Fixed horizontal spacing uses exact Beta-mixture moments; otherwise Gaussian quadrature is 

225 polynomial-exact, up to floating-point error. 

226 

227 Returns: 

228 Tensor of shape (*batch_shape,). 

229 """ 

230 e_t, _ = self._moments() 

231 return self.bound_low + self.support_range * e_t 

232 

233 @property 

234 def variance(self) -> torch.Tensor: 

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

236 

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

238 

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

240 

241 Note: 

242 Fixed horizontal spacing uses exact Beta-mixture moments; otherwise Gaussian quadrature is 

243 polynomial-exact, up to floating-point error. 

244 

245 Returns: 

246 Tensor of shape (*batch_shape,). 

247 """ 

248 e_t, e_t2 = self._moments() 

249 return self.support_range**2 * (e_t2 - e_t.square()).clamp_min(0) 

250 

251 def _quadrature(self, num_points: int) -> tuple[torch.Tensor, torch.Tensor]: 

252 r"""Generate Gauss-Legendre nodes and weights on $[0, 1]$ using the symmetric Jacobi matrix. 

253 

254 For $n=\text{num_points}$, the Golub-Welsch construction forms a symmetric tridiagonal matrix 

255 $J \in \mathbb{R}^{n \times n}$ from the recurrence coefficients of the orthonormal Legendre polynomials: 

256 

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

258 \qquad k=1,\ldots,n-1, $$ 

259 

260 with all other entries zero. Its eigenvalues $\lambda_i$ are the roots of the degree-$n$ Legendre 

261 polynomial, hence the quadrature nodes on $[-1, 1]$. For orthonormal eigenvectors $v_i$ satisfying 

262 $Jv_i=\lambda_i v_i$, the corresponding weights on that interval are $2(v_i)_1^2$, where $(v_i)_1$ 

263 is the first component of $v_i$. Shifting the nodes and halving the weights gives the rule on $[0, 1]$: 

264 

265 $$ t_i=\frac{\lambda_i+1}{2}, \qquad w_i=(v_i)_1^2, \qquad 

266 \int_0^1 f(t)\,dt \approx \sum_{i=1}^{n} w_i f(t_i). $$ 

267 

268 The rule is exact for polynomials of degree at most $2n-1$, up to floating-point error. 

269 The weights integrate with respect to $dt$; callers supply any additional density factor. 

270 

271 Note: 

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

273 

274 Args: 

275 num_points: Number $n$ of quadrature nodes; must be at least one. Increasing this count raises 

276 the maximum polynomial degree integrated exactly and refines the approximation for smooth, 

277 non-polynomial integrands. 

278 

279 Returns: 

280 nodes: Quadrature locations in $[0, 1]$, ordered increasingly, with shape 

281 (num_points,) + (1,) * len(self.batch_shape). The trailing singleton dimensions allow 

282 the shared quadrature nodes to broadcast across the distribution's batch dimensions. 

283 weights: Positive integration weights corresponding to nodes, with the same shape. They sum 

284 to one along the quadrature dimension, up to floating-point error. 

285 """ 

286 idcs = torch.arange(1, num_points, dtype=self.logits_y.dtype, device=self.logits_y.device) 

287 off_diagonal = idcs / (4 * idcs.square() - 1).sqrt() 

288 

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

290 

291 shape = (num_points,) + (1,) * len(self.batch_shape) 

292 nodes = ((nodes + 1) / 2).reshape(shape) 

293 first_comp_of_vectors = vectors[0] # 1st component of each eigenvector which represents constants in the L-poly 

294 weights = first_comp_of_vectors.square().reshape(shape) 

295 

296 return nodes, weights 

297 

298 def _moments(self) -> tuple[torch.Tensor, torch.Tensor]: 

299 r"""Compute the first two raw moments analytically for a fixed axis, otherwise by Gaussian quadrature. 

300 

301 For support bounds $L$ and $U$, let $Z = (X - L) / (U - L) = B_x(T)$. The curve parameter $T$ 

302 has CDF $B_y(t)$ and density $B_y'(t)$ on $[0, 1]$. Changing variables from $X$ to $T$ cancels 

303 the horizontal Jacobian: 

304 

305 $$ p_X(x(t)) x'(t) = B_y'(t), \qquad 

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

307 

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

309 

310 $$ e_t = \sum_{j=1}^{n_y} \Delta_{j-1} \frac{j}{n_y+1}, \qquad 

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

312 

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

314 

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

316 

317 where $n_y = \text{degree_y}$ and $\Delta_j$ are the normalized vertical increments. For Gauss-Legendre 

318 nodes $t_i$ and weights $w_i$, the code forms horizontal values $h_i$ and integration masses $a_i$: 

319 

320 $$ h_i = B_x(t_i), \qquad a_i = w_i B_y'(t_i), \qquad 

321 e_t = \sum_{i = 1}^{m} a_i h_i, \qquad e_{t2} = \sum_{i = 1}^{m} a_i h_i^2. $$ 

322 

323 The masses sum to one up to floating-point error. Horizontal values and masses have shape 

324 (m, *batch_shape); summing along dimension zero removes only the quadrature dimension. 

325 

326 With $n_x = \text{degree_x}$, the integrand for moment $k$ has degree at most $k n_x + n_y - 1$. 

327 An $m$-point Gauss-Legendre rule integrates polynomials through degree $2 m - 1$ exactly, so both 

328 moments are covered by the node count used here: 

329 

330 $$ m = \left\lceil \frac{2 n_x + n_y}{2} \right\rceil 

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

332 

333 Note: 

334 Both moments are polynomial-exact up to floating-point error and retain gradients through both axes. 

335 The fixed axis retains explicit zero gradients. Tensors use the logits' dtype and device; 

336 only learned horizontal axes are subject to the requirements of _quadrature. 

337 No numerical inversion or support rescaling is performed here; mean and variance apply the bounds. 

338 

339 Returns: 

340 e_t: First raw moment $E[Z]$, with shape (*batch_shape,). 

341 e_t2: Second raw moment $E[Z^2]$, with shape (*batch_shape,); this is not the variance. 

342 Despite their names, these are moments of $Z$, not of $T$, unless $B_x(t) = t$. 

343 """ 

344 if self.degree_x == 1: 

345 idcs = torch.arange(1, self.degree_y + 1, dtype=self.logits_y.dtype, device=self.logits_y.device) 

346 component_1st_mom = idcs / (self.degree_y + 1) # shape: (degree_y,) 

347 component_2nd_mom = component_1st_mom * (idcs + 1) / (self.degree_y + 2) # shape: (degree_y,) 

348 

349 # Combine the component raw moments using the Beta-mixture weights. 

350 zero_x = self.logits_x[..., 0] * 0 # keep autograd connection 

351 e_t = (self._deltas_y * component_1st_mom).sum(dim=-1) + zero_x # shape: (*batch_shape,) 

352 e_t2 = (self._deltas_y * component_2nd_mom).sum(dim=-1) + zero_x # shape: (*batch_shape,) 

353 

354 return e_t, e_t2 

355 

356 # Compute the Gauss-Legendre nodes t_i and weights w_i for integration over t in [0, 1]. 

357 # Choose num_points m so 2*m - 1 >= 2*degree_x + degree_y - 1, covering both raw-moment integrands. 

358 nodes, weights = self._quadrature(num_points=(2 * self.degree_x + self.degree_y + 1) // 2) 

359 

360 # Compute the normalized x-axis coordinates z_i = B_x(t_i). 

361 normalized_x_coords = self._eval_bezier_curve(nodes, self._betas_x, self._binom_coeffs_cdf_x) 

362 

363 # Quadrature masses w_i * B_y'(t_i); the horizontal Jacobian cancels when integrating in t. 

364 masses = weights * self.degree_y * self._eval_bezier_curve(nodes, self._deltas_y, self._binom_coeffs_pdf_y) 

365 

366 # Integrate z and z^2 over the quadrature dimension, keeping the batch dimensions. 

367 e_t = (masses * normalized_x_coords).sum(dim=0) 

368 e_t2 = (masses * normalized_x_coords.square()).sum(dim=0) 

369 

370 return e_t, e_t2 

371 

372 def _eval_bezier_curve( 

373 self, 

374 t: torch.Tensor, 

375 weights: torch.Tensor, 

376 binom_coeffs: torch.Tensor, 

377 ) -> torch.Tensor: 

378 r"""Evaluates a Bezier curve (a Bernstein polynomial) in the $T \in [0, 1]$ space. 

379 

380 This method computes the weighted sum of Bernstein basis polynomials. Let $d$ be the degree of the polynomial 

381 being evaluated ($n$ for an axis curve or $n-1$ for its derivative basis). Each basis polynomial is defined as: 

382 

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

384 

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

386 

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

388 

389 where $w_i$ are the weights (betas for an axis curve or deltas for its derivative basis). 

390 When using deltas, callers multiply the result by the axis degree to obtain the derivative. 

391 

392 Args: 

393 t: Normalized input values in [0, 1]. 

394 Expected shape: (*sample_shape, *batch_shape). 

395 weights: The coefficients for the basis polynomials. 

396 Expected shape: (*batch_shape, degree + 1). 

397 binom_coeffs: Precomputed binomial coefficients corresponding to the polynomial's degree. 

398 Expected shape: (degree + 1,). 

399 

400 Returns: 

401 The evaluated polynomial values. 

402 Output shape: (*sample_shape, *batch_shape) 

403 """ 

404 # Get n which can be != self.degree as we use this method for both CDF and PDF which have different degrees. 

405 nun_coeffs = binom_coeffs.shape[0] 

406 

407 # Create a tensor of indices matching the number of basis polynomials. 

408 i = torch.arange(nun_coeffs, device=t.device, dtype=t.dtype) 

409 

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

411 t_expanded = t.unsqueeze(-1) 

412 

413 # Bernstein basis B_{i,d}(t) = binom(d, i) * t**i * (1-t)**(d-i), with d = nun_coeffs - 1. 

414 # Broadcasting gives shape (*t.shape, nun_coeffs), with one entry per basis polynomial. 

415 basis = binom_coeffs * (t_expanded**i) * ((1 - t_expanded) ** (nun_coeffs - 1 - i)) 

416 

417 # Multiply by weights and sum across the final dimension, resulting in shape (*sample_shape, *batch_shape). 

418 return torch.sum(weights * basis, dim=-1) 

419 

420 def _eval_log_derivative( 

421 self, t: torch.Tensor, log_deltas: torch.Tensor, binom_coeffs: torch.Tensor 

422 ) -> torch.Tensor: 

423 r"""Evaluate the log derivative of either normalized axis entirely in log-space. 

424 

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

426 

427 $$ \log B'(t) = \log n + \operatorname{logsumexp}_i\!\left( 

428 \log \Delta_i + \log \binom{n-1}{i} + i\log t + (n-1-i)\log(1-t)\right). $$ 

429 

430 This avoids the numerically problematic log(polynomial + eps) path. Exact endpoints are handled separately, 

431 where only the first or last Bernstein basis term survives. 

432 Degree-one axes return the constant log derivative directly, preserving broadcasting and zero input gradients. 

433 

434 Args: 

435 t: Curve parameters in [0, 1], of shape (*sample_shape, *batch_shape). 

436 log_deltas: Normalized log increments for the chosen axis, of shape (*batch_shape, n). 

437 binom_coeffs: Degree-(n-1) Bernstein coefficients, of shape (n,). 

438 

439 Returns: 

440 Log derivatives with the broadcast sample/batch shape, before support-range scaling. 

441 """ 

442 degree = log_deltas.shape[-1] 

443 if degree == 1: 

444 # Degree-one axes have a constant derivative. This is not necessarily the past-path for the constantly 

445 # spaced x-axis. 

446 return t * 0 + log_deltas[..., 0] 

447 

448 # Indices for the Bernstein basis: i = 0, ..., n-1. Shape: (n,). 

449 idcs = torch.arange(degree, device=t.device, dtype=t.dtype) 

450 

451 # Clamp away from exact 0/1 to avoid log(0), then append a basis dimension: (*t.shape, 1). 

452 t_safe = t.clamp(min=torch.finfo(t.dtype).tiny, max=1 - torch.finfo(t.dtype).eps).unsqueeze(-1) 

453 

454 # Log of each Bernstein basis term: log(binom) + i*log(t) + (n-1-i)*log(1-t). 

455 # log_basis shape: (*t.shape, n); singleton batch dimensions expand when adding log_deltas. 

456 log_basis = binom_coeffs.log() + idcs * t_safe.log() + (degree - 1 - idcs) * torch.log1p(-t_safe) 

457 

458 # Broadcast log_deltas (*batch_shape, n) across samples, then sum weighted terms via logsumexp. 

459 # The degree factor accounts for differentiation; result shape: (*sample_shape, *batch_shape). 

460 log_derivative = math.log(degree) + torch.logsumexp(log_deltas + log_basis, dim=-1) 

461 

462 # Restore analytic endpoint derivatives instead of returning the clamped interior approximations. 

463 log_derivative = torch.where(t == 0, math.log(degree) + log_deltas[..., 0], log_derivative) 

464 log_derivative = torch.where(t == 1, math.log(degree) + log_deltas[..., -1], log_derivative) 

465 return log_derivative 

466 

467 def _invert_bezier( 

468 self, 

469 value: torch.Tensor, 

470 betas: torch.Tensor, 

471 deltas: torch.Tensor, 

472 coeffs_cdf: torch.Tensor, 

473 coeffs_pdf: torch.Tensor, 

474 num_iter: int = 64, 

475 use_newton: bool = True, 

476 newton_damping: float = 1.0, 

477 convergence_eps_factor: float = 2.0, 

478 ) -> torch.Tensor: 

479 r"""Invert a normalized monotone Bezier axis using a bracketed solver and implicit gradients. 

480 

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

482 

483 $$ B(t) = \sum_{i=0}^{n} \beta_i B_{i,n}(t) = q, \qquad 

484 q = \operatorname{clamp}(\text{value}, 0, 1). $$ 

485 

486 Here $B_{i,n}$ is the Bernstein basis, and the supplied control points must increase from 0 to 1. 

487 Their positive increments determine the derivative: 

488 

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

490 \Delta_i = \beta_{i+1} - \beta_i. $$ 

491 

492 Each sample/batch element starts at $t=q$ with its own bracket $[0, 1]$. The current curve value 

493 tightens one bracket endpoint. A damped Newton proposal is accepted only strictly inside the updated 

494 bracket; otherwise its midpoint is used. Setting use_newton=False always selects the midpoint. 

495 

496 $$ c_k = \frac{B(t_k)-q}{\max(B'(t_k), \text{tiny})}, \qquad 

497 t_{\mathrm{Newton}} = t_k - \alpha c_k. $$ 

498 

499 An element stops updating when either the undamped correction $|c_k|$ or its bracket width is at 

500 most convergence_eps_factor times machine epsilon. Both criteria measure error in parameter space, 

501 rather than relying on a small curve-value residual in a flat region. The loop ends when all elements 

502 converge or num_iter is reached; exhausting the iteration budget returns the current estimate. 

503 

504 Iterations run without gradient tracking. At the resulting estimate, a forward-zero residual 

505 correction attaches the implicit first-order derivatives for interior targets: 

506 

507 $$ \frac{\partial t}{\partial q} = \frac{1}{B'(t)}, \qquad 

508 \frac{\partial t}{\partial\theta} = -\frac{\partial_\theta B(t;\theta)}{B'(t)}. $$ 

509 

510 Here $\theta$ denotes the chosen axis's parameters. Detaching the denominator avoids differentiating 

511 this correction as another solver iteration. Gradient accuracy depends on the numerical root; 

512 higher-order inverse derivatives are not supported. Derivative denominators are clamped to the dtype's 

513 smallest positive normal value (tiny) to avoid division by zero, modifying the formulas below that floor. 

514 

515 Args: 

516 value: Target values on the normalized axis, clamped to [0, 1]. Shape: 

517 (*sample_shape, *value_batch_shape), with trailing batch dimensions broadcastable to batch_shape. 

518 betas: Increasing control points with first/last values 0/1. Shape: (*batch_shape, n + 1). 

519 deltas: Positive forward differences of betas, summing to one. Shape: (*batch_shape, n). 

520 coeffs_cdf: Binomial coefficients for the degree-n curve. Shape: (n + 1,). 

521 coeffs_pdf: Binomial coefficients for the degree-(n-1) derivative basis. Shape: (n,). 

522 Despite their names, both coefficient tensors apply to either axis. 

523 num_iter: Maximum number of solver iterations; must be at least one. 

524 use_newton: Whether to try damped Newton steps with bisection fallback. False uses pure bisection, 

525 but still evaluates the derivative for the convergence check. 

526 newton_damping: Newton step multiplier $\alpha$ in (0, 1]; ignored when use_newton=False. 

527 convergence_eps_factor: Positive multiplier of the input dtype's machine epsilon for the tolerance. 

528 

529 Returns: 

530 Estimated curve parameters in [0, 1], with shape (*sample_shape, *broadcast_batch_shape). 

531 The exact shape is the broadcast of value.shape and betas.shape[:-1]. Clamped target values 0 and 1 

532 return exact endpoints; a degree-one normalized axis returns the clamped targets directly. 

533 

534 Note: 

535 Callers supply consistent axis tensors with a shared floating dtype/device and valid solver settings. 

536 This helper does not rescale physical coordinates or validate these preconditions. 

537 """ 

538 # Remove the control-point dimension before broadcasting targets across the axis batch dimensions. 

539 # q and all per-element solver tensors have shape (*sample_shape, *broadcast_batch_shape). 

540 q, _ = torch.broadcast_tensors(value.clamp(0, 1), betas[..., 0]) 

541 

542 # With control points [0, 1], the degree-one axis and its inverse are both the identity. 

543 degree = deltas.shape[-1] 

544 if degree == 1: 

545 return q 

546 

547 tiny = torch.finfo(q.dtype).tiny 

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

549 

550 # Find the numerical root without retaining an autograd graph for the iterations. 

551 with torch.no_grad(): 

552 mid = q.clone() 

553 low, high = torch.zeros_like(mid), torch.ones_like(mid) 

554 

555 for _ in range(num_iter): 

556 current = self._eval_bezier_curve(mid, betas, coeffs_cdf) 

557 derivative = degree * self._eval_bezier_curve(mid, deltas, coeffs_pdf) 

558 correction = (current - q) / derivative.clamp_min(tiny) 

559 

560 # The Boolean mask has the same sample/batch shape; only the all() check reduces it to a scalar. 

561 converged = (correction.abs() <= tolerance) | (high - low <= tolerance) 

562 if converged.all(): 

563 break 

564 

565 # Monotonicity selects which bracket endpoint to move; bisection supplies the fallback step. 

566 low = torch.where(current < q, mid, low) 

567 high = torch.where(current >= q, mid, high) 

568 candidate = (low + high) / 2 

569 

570 if use_newton: 

571 # Reject overshooting Newton steps instead of letting them leave the root's bracket. 

572 newton = mid - newton_damping * correction 

573 candidate = torch.where((newton > low) & (newton < high), newton, candidate) 

574 

575 # Keep converged estimates fixed while other sample/batch elements continue iterating. 

576 mid = torch.where(converged, mid, candidate) 

577 

578 if torch.is_grad_enabled(): 

579 # residual - residual.detach() is forward-zero but preserves gradients to q and the axis parameters. 

580 # Dividing by the detached slope attaches the implicit inverse derivative at the fixed estimate. 

581 residual = q - self._eval_bezier_curve(mid, betas, coeffs_cdf) 

582 derivative = degree * self._eval_bezier_curve(mid, deltas, coeffs_pdf) 

583 mid = mid + (residual - residual.detach()) / derivative.detach().clamp_min(tiny) 

584 

585 # Return exact endpoints rather than tolerance-dependent interior approximations. 

586 mid = torch.where(q == 0, torch.zeros_like(mid), mid) 

587 return torch.where(q == 1, torch.ones_like(mid), mid) 

588 

589 def cdf(self, value: torch.Tensor) -> torch.Tensor: 

590 """Compute cumulative distribution function at given values. 

591 

592 Args: 

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

594 

595 Returns: 

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

597 Output shape: same as `value` argument. 

598 """ 

599 x = value.to(device=self.logits_y.device, dtype=self.logits_y.dtype) 

600 

601 # Map X in [bound_low, bound_up] to T in [0, 1]. 

602 t = self._map_to_t_space(x) 

603 

604 # Construct and evaluate the Bezier curve in T space. 

605 return self._eval_bezier_curve(t, weights=self._betas_y, binom_coeffs=self._binom_coeffs_cdf_y) 

606 

607 def prob(self, value: torch.Tensor) -> torch.Tensor: 

608 """Compute probability density at given values. 

609 

610 Args: 

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

612 

613 Returns: 

614 PDF values corresponding to the input values. 

615 Output shape: same as `value` argument. 

616 """ 

617 return self.log_prob(value).exp() 

618 

619 def log_prob(self, value: torch.Tensor) -> torch.Tensor: 

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

621 

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

623 

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

625 

626 Args: 

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

628 

629 Returns: 

630 Log-PDF values corresponding to the input values. 

631 Output shape: same as `value` argument. 

632 """ 

633 x = value.to(device=self.logits_y.device, dtype=self.logits_y.dtype) 

634 

635 # Map X in [bound_low, bound_up] to T in [0, 1]. 

636 t = self._map_to_t_space(x) 

637 

638 # Start with log B_y'(t): probability change per unit t, not yet the physical log-density. 

639 log_pdf = self._eval_log_derivative(t, self._log_deltas_y, self._binom_coeffs_pdf_y) 

640 

641 # Divide by horizontal stretching B_x'(t), hence subtract its log, to get density per normalized x. 

642 log_pdf = log_pdf - self._eval_log_derivative(t, self._log_deltas_x, self._binom_coeffs_pdf_x) 

643 

644 # Divide by the support width U-L (subtract its log) to get density per physical x. 

645 log_pdf = log_pdf - math.log(self.support_range) 

646 

647 # Mask values outside the support. 

648 mask = (value >= self.bound_low) & (value <= self.bound_up) 

649 return torch.where(mask, log_pdf, torch.full_like(log_pdf, -math.inf)) 

650 

651 def entropy(self, num_quadrature_points: int = 251) -> torch.Tensor: 

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

653 

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

655 

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

657 

658 Args: 

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

660 

661 Returns: 

662 Tensor of shape (*batch_shape,). 

663 """ 

664 if num_quadrature_points < 1: 664 ↛ 665line 664 didn't jump to line 665 because the condition on line 664 was never true

665 raise ValueError("num_quadrature_points must be positive.") 

666 

667 nodes, weights = self._quadrature(num_quadrature_points) 

668 

669 # B_y'(t) is the density in parameter space; evaluate its log at the quadrature nodes. 

670 log_derivative_y = self._eval_log_derivative(nodes, self._log_deltas_y, self._binom_coeffs_pdf_y) 

671 

672 # 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). 

673 log_pdf = log_derivative_y - math.log(self.support_range) 

674 log_pdf = log_pdf - self._eval_log_derivative(nodes, self._log_deltas_x, self._binom_coeffs_pdf_x) 

675 

676 # H(X) = -∫_0^1 B_y'(t) * log p_X(x(t)) dt, with exp(log_derivative_y) = B_y'(t). 

677 return -(weights * log_derivative_y.exp() * log_pdf).sum(dim=0) 

678 

679 def icdf( 

680 self, 

681 value: torch.Tensor, 

682 num_iter: int = 64, 

683 use_newton: bool = True, 

684 newton_damping: float = 1.0, 

685 convergence_eps_factor: float = 2.0, 

686 ) -> torch.Tensor: 

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

688 

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

690 

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

692 

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

694 

695 where $q$ is the target quantile in [0, 1], 

696 and $\alpha \in (0, 1]$ is a damping factor that shrinks each Newton step to improve robustness. 

697 A bracket within [0, 1] is maintained alongside: whenever $B_y(t_k) < q$ the lower bound tightens, 

698 otherwise the upper bound tightens. If the Newton step would leave the bracket, a bisection 

699 step is used instead, guaranteeing monotonic bracket contraction and preventing oscillation. 

700 The loop exits when the parameter-space Newton correction or bracket width is below tolerance. 

701 

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

703 

704 Args: 

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

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

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

708 newton_damping: Damping factor in (0, 1] applied to the Newton step. A value of 1.0 gives the 

709 full Newton step (quadratic convergence), while smaller values improve robustness 

710 at the cost of slower convergence. 

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

712 

713 Returns: 

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

715 Output shape: same as `value` argument. 

716 """ 

717 if num_iter < 1 or not 0 < newton_damping <= 1 or convergence_eps_factor <= 0: 717 ↛ 718line 717 didn't jump to line 718 because the condition on line 717 was never true

718 raise ValueError("Require num_iter >= 1, 0 < newton_damping <= 1, and convergence_eps_factor > 0.") 

719 

720 q = value.to(device=self.logits_y.device, dtype=self.logits_y.dtype) 

721 t = self._invert_bezier( 

722 q, 

723 self._betas_y, 

724 self._deltas_y, 

725 self._binom_coeffs_cdf_y, 

726 self._binom_coeffs_pdf_y, 

727 num_iter, 

728 use_newton, 

729 newton_damping, 

730 convergence_eps_factor, 

731 ) 

732 

733 return self._map_to_x_space(t) 

734 

735 def rsample(self, sample_shape: torch.Size | list[int] | tuple[int, ...] = _size) -> torch.Tensor: 

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

737 

738 Args: 

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

740 

741 Returns: 

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

743 """ 

744 # Determine the final shape of the output tensor. 

745 shape = self._extended_shape(sample_shape) 

746 

747 # Sample uniform noise, u ~ U(0, 1). 

748 u = torch.rand(shape, dtype=self.logits_y.dtype, device=self.logits_y.device) 

749 

750 return self.icdf(u)