Generated from the full canonical file for this source snapshot. Line numbers match the library source.
Source SHA256: 4917333d260c37350d077a8629dc66cc5dd5ccd565f44f3296a70e981f0c5e34
1"""Independent exact-input Decimal oracles for the CUDA transmission contract.23These scalar routines deliberately have no Warp dependency and no production4cutover. Inputs are quantised to binary32, reconstructed exactly by integer ratio,5and evaluated at the requested Decimal precision (100 digits by default).6"""78import math9import struct10from collections.abc import Callable, Iterable11from dataclasses import dataclass12from decimal import Decimal, localcontext131415def binary32(value: float) -> float:16"""Round a Python number to binary32; finite overflow is an explicit error."""17try:18result = struct.unpack("!f", struct.pack("!f", value))[0]19except OverflowError as exc:20raise ValueError("input exceeds finite binary32 range") from exc21if not math.isfinite(result):22raise ValueError("input must be finite binary32")23return result242526def _from_bits(bits: int) -> float:27return struct.unpack("!f", struct.pack("!I", bits))[0]282930def _bits(value: float) -> int:31return struct.unpack("!I", struct.pack("!f", value))[0]323334def exact_input(value: float, *, nonnegative: bool = False) -> Decimal:35"""Recover the exact stored binary32 value, preserving signed zero."""36stored = binary32(value)37if nonnegative and stored < 0:38raise ValueError("input must be non-negative")39numerator, denominator = stored.as_integer_ratio()40# A binary32 denominator is at most 2**149: 200 digits make this exact.41with localcontext() as context:42context.prec = 20043result = Decimal(numerator) / Decimal(denominator)44return result.copy_negate() if stored == 0 and math.copysign(1, stored) < 0 else result454647MIN_SUBNORMAL = Decimal.from_float(_from_bits(1))48MIN_NORMAL = Decimal.from_float(_from_bits(0x00800000))49MAX_FINITE = Decimal.from_float(_from_bits(0x7F7FFFFF))50with localcontext() as _context:51_context.prec = 20052U32 = Decimal(2) ** -2453U64 = Decimal(2) ** -5354OVERFLOW_MIDPOINT = MAX_FINITE + Decimal(2) ** 103555657def round_binary32(value: Decimal) -> float:58"""Round Decimal directly to nearest binary32, ties to even.5960Binary search compares exact neighbours; converting through binary64 could61incorrectly move a Decimal value onto a binary32 midpoint. Overflow follows62round-to-nearest semantics and returns a signed infinity.63"""64if not value.is_finite():65raise ValueError("reference value must be finite")66negative = value.is_signed()67magnitude = value.copy_abs()68if magnitude >= OVERFLOW_MIDPOINT:69return -math.inf if negative else math.inf70low, high = 0, 0x7F7FFFFF71while low < high:72middle = (low + high + 1) // 273if Decimal.from_float(_from_bits(middle)) <= magnitude:74low = middle75else:76high = middle - 177chosen = low78if low < 0x7F7FFFFF:79# Exact endpoints need up to 150 decimal places, independent of caller context.80with localcontext() as context:81context.prec = max(200, len(value.as_tuple().digits) + 160)82midpoint = (83Decimal.from_float(_from_bits(low)) + Decimal.from_float(_from_bits(low + 1))84) / 285if magnitude > midpoint or (magnitude == midpoint and low % 2):86chosen += 187return _from_bits(chosen | (0x80000000 if negative else 0))888990def _exponential(depth: Decimal) -> tuple[Decimal, Decimal]:91"""Return exp(-L), or zero with an explicit absolute bound for enormous L.9293For L >= 1024, exp(-L) <= exp(-1024) < 2**-1477. Even two94maximum binary32 factors and 2**31 contributions give < 2**-1190,95far below half the smallest binary32 subnormal (2**-150). This96bound covers every exponential weighted term in the declared contract.97"""98if depth >= 1024:99return Decimal(0), Decimal(2) ** -1477100return (-depth).exp(), Decimal(0)101102103@dataclass(frozen=True)104class ForwardReference:105"""Mathematical values and the exponential tail bound, before storage rounding."""106107T: Decimal108counts: Decimal109log_T: Decimal # noqa: N815 - match the documented mathematical output name.110removed: Decimal111tail_bound: Decimal112113def rounded(self) -> dict[str, float]:114return {115name: round_binary32(getattr(self, name))116for name in ("T", "counts", "log_T", "removed")117}118119120def forward_reference(depth: float, n0: float = 1.0, *, precision: int = 100) -> ForwardReference:121"""Evaluate four outputs from exact stored inputs, independently of device code."""122optical_depth, beam = exact_input(depth, nonnegative=True), exact_input(n0, nonnegative=True)123with localcontext() as context:124context.prec = precision125exponential, bound = _exponential(optical_depth)126return ForwardReference(127exponential,128(beam * exponential).copy_abs(),129optical_depth.copy_negate(),130(Decimal(1) - exponential).copy_abs(),131bound,132)133134135def inverse_reference(delta: float, *, precision: int = 100) -> Decimal:136"""Reference -ln(1-delta); the supplied decrement is the input representation."""137decrement = exact_input(delta, nonnegative=True)138if decrement >= 1:139raise ValueError("decrement must be less than one")140with localcontext() as context:141context.prec = precision142return (-(Decimal(1) - decrement).ln()).copy_abs()143144145@dataclass(frozen=True)146class VJPReference:147"""Analytic weighted derivatives and the frozen per-pixel absolute budgets."""148149grad_L: Decimal # noqa: N815 - L denotes optical depth throughout the API.150grad_n0: Decimal151budget_L: Decimal # noqa: N815 - pair the budget with grad_L.152budget_n0: Decimal153154155def vjp_reference(156depth: float,157n0: float = 1.0,158*,159seed_T: float = 0.0, # noqa: N803 - mirror the production cotangent name.160seed_counts: float = 0.0,161seed_log_T: float = 0.0, # noqa: N803 - mirror the production cotangent name.162seed_removed: float = 0.0,163precision: int = 100,164) -> VJPReference:165"""Differentiate each mathematical output independently and contract its seed."""166optical_depth, beam = exact_input(depth, nonnegative=True), exact_input(n0, nonnegative=True)167seeds = [exact_input(value) for value in (seed_T, seed_counts, seed_log_T, seed_removed)]168with localcontext() as context:169context.prec = precision170exponential, _ = _exponential(optical_depth)171derivatives = (-exponential, -beam * exponential, Decimal(-1), exponential)172terms = [seed * derivative for seed, derivative in zip(seeds, derivatives, strict=True)]173beam_term = seeds[1] * exponential174return VJPReference(175sum(terms, Decimal(0)),176beam_term,17732 * U32 * sum((abs(term) for term in terms), Decimal(0)) + 2 * MIN_SUBNORMAL,17832 * U32 * abs(beam_term) + 2 * MIN_SUBNORMAL,179)180181182def inverse_vjp_reference(183delta: float, seed: float, *, precision: int = 100184) -> tuple[Decimal, Decimal]:185"""Return the independent inverse derivative and magnitude-scaled error budget."""186inverse_reference(delta, precision=precision) # Validate the physical domain.187decrement, weight = exact_input(delta), exact_input(seed)188with localcontext() as context:189context.prec = precision190gradient = weight / (1 - decrement)191return gradient, 32 * U32 * abs(gradient) + 2 * MIN_SUBNORMAL192193194def scalar_beam_reference(195depths: Iterable[float],196seeds: Iterable[float],197*,198addition_depth: int,199precision: int = 100,200) -> tuple[Decimal, Decimal]:201"""Sum beam contributions with a bound using the actual reduction addition depth.202203The supplied depth counts additions along the longest path, including within204blocks. Kernel-launch count is not an acceptable substitute.205"""206if addition_depth < 0:207raise ValueError("addition_depth must be non-negative")208with localcontext() as context:209context.prec = precision210references = [211vjp_reference(depth, seed_counts=seed, precision=precision)212for depth, seed in zip(depths, seeds, strict=True)213]214product = addition_depth * U64215if product >= 1:216raise ValueError("addition depth exceeds the gamma-bound domain")217total = sum((record.grad_n0 for record in references), Decimal(0))218magnitude = sum((abs(record.grad_n0) for record in references), Decimal(0))219element_budget = sum((record.budget_n0 for record in references), Decimal(0))220final_rounding = U32 * abs(total) + MIN_SUBNORMAL / 2221return total, element_budget + product / (1 - product) * magnitude + final_rounding222223224def ulp_distance(actual: float, expected: float) -> int:225"""Count representable binary32 steps; opposite signed zeros have distance zero."""226227def ordered(value: float) -> int:228bits = _bits(binary32(value))229return 0x80000000 - (bits & 0x7FFFFFFF) if bits >> 31 else 0x80000000 + bits230231return abs(ordered(actual) - ordered(expected))232233234@dataclass(frozen=True)235class ValueErrorRecord:236absolute_error: Decimal237ulps: int238allowed_ulps: int239regime: str240passed: bool241242243def value_error(actual: float, expected: Decimal, *, counts: bool = False) -> ValueErrorRecord:244"""Apply frozen forward budgets, including one-ULP subnormal/zero checks."""245target = round_binary32(expected)246actual_exact = exact_input(actual)247distance = ulp_distance(actual, target)248subnormal = abs(expected) < MIN_NORMAL249allowed = 1 if subnormal else (8 if counts else 4)250with localcontext() as context:251context.prec = 200252absolute = abs(actual_exact - expected)253return ValueErrorRecord(254absolute, distance, allowed, "subnormal" if subnormal else "normal", distance <= allowed255)256257258@dataclass(frozen=True)259class AnalyticCase:260name: str261optical_depth: Decimal262definition: str263264265# region book:transmission-reference-cases266def analytic_cases() -> tuple[AnalyticCase, ...]:267"""Closed-form path cases, without claiming to validate a path integrator.268269All coefficients and lengths below are exact dyadic mathematical stress inputs.270The mm and cm expressions describe the same optical depth in different units.271"""272coefficient, distance = Decimal("0.125"), Decimal(4)273first_length, second_length = Decimal(1), Decimal(3)274intercept, slope = Decimal("0.125"), Decimal("0.0625")275return (276AnalyticCase("empty", Decimal(0), "empty path"),277AnalyticCase("zero-attenuation", Decimal(0), "mu = 0"),278AnalyticCase("homogeneous", coefficient * distance, "mu*d"),279AnalyticCase(280"split-homogeneous",281coefficient * first_length + coefficient * second_length,282"mu*d1 + mu*d2",283),284AnalyticCase("layered", Decimal("0.25") * 2 + Decimal("0.5") * 3, "mu1*d1 + mu2*d2"),285AnalyticCase("millimetres", Decimal("0.125") * 4, "0.125/mm * 4 mm"),286AnalyticCase("centimetres", Decimal("1.25") * Decimal("0.4"), "1.25/cm * 0.4 cm"),287AnalyticCase(288"added-segment",289coefficient * distance + Decimal("0.25"),290"mu*d + non-negative optical depth",291),292AnalyticCase(293"linear-coefficient",294intercept * distance + slope * distance * distance / 2,295"integral_0^d (a+b*s) ds",296),297)298299300# endregion book:transmission-reference-cases301302303@dataclass(frozen=True)304class DirectionalRecord:305step: float306derivative: float307absolute_error: float308stencil: str309310311# region book:transmission-directional-check312def directional_check(313evaluate: Callable[[float], float],314anchor: float,315analytic_derivative: float,316*,317exponents: Iterable[int] = range(2, 25),318) -> tuple[DirectionalRecord, ...]:319"""Sweep a real operator callback over admissible, distinct binary32 inputs.320321Interior anchors use centred differences; zero uses a second-order one-sided322stencil. No convergence claim is inferred from the smallest step: callers retain323all records to expose truncation, agreement and storage-rounding regimes.324"""325centre = binary32(anchor)326if centre < 0:327raise ValueError("anchor must be non-negative")328records: list[DirectionalRecord] = []329for exponent in exponents:330step = 2.0**-exponent331right = binary32(centre + step)332if right == centre:333continue334if centre == 0:335second = binary32(2 * step)336if second <= right:337continue338derivative = (-3 * evaluate(centre) + 4 * evaluate(right) - evaluate(second)) / (3392 * right340)341stencil = "one-sided-second-order"342else:343if centre - step < 0:344continue345left = binary32(centre - step)346if left == centre or centre - left != right - centre:347continue348derivative = (evaluate(right) - evaluate(left)) / (right - left)349stencil = "centred"350records.append(351DirectionalRecord(352right - centre, derivative, abs(derivative - analytic_derivative), stencil353)354)355return tuple(records)356357358# endregion book:transmission-directional-check359