Download dflow/brownian_noise.py from data-archetype/dflow_2b: direct link, hf CLI and curl.
- Browser
- Download file 5.39 kB
-
https://huggingface.co/data-archetype/dflow_2b/resolve/main/dflow/brownian_noise.py
- Command line
-
hf download hf://data-archetype/dflow_2b/dflow/brownian_noise.py
-
curl -L -o brownian_noise.py https://huggingface.co/data-archetype/dflow_2b/resolve/main/dflow/brownian_noise.py
5.39 kB
| """Per-step standard normals and Brownian-tree increments for the SDE solvers. | |
| Both draw from one explicit ``torch.Generator``. A CPU generator (the | |
| recommended source) draws float32 values on the host and copies them to the | |
| state's device without a host sync, so one seed gives the same noise on every | |
| GPU model. A CUDA generator draws on the state's device; its numbers depend on | |
| the GPU model. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import torch | |
| from torch import Tensor | |
| from torchsde import BrownianTree | |
| BROWNIAN_RELATIVE_TOLERANCE = 1.0e-10 | |
| _ENTROPY_HIGH = 2**31 - 1 | |
| def _require_generator_device(generator: torch.Generator, device: torch.device) -> None: | |
| """Fail fast when a non-CPU generator is not on the state's device. | |
| Raises: | |
| ValueError: On a CUDA generator for a state on another device. | |
| """ | |
| generator_device = torch.device(generator.device) | |
| if generator_device.type == "cpu": | |
| return | |
| matches = generator_device.type == device.type and ( | |
| generator_device.index is None | |
| or device.index is None | |
| or generator_device.index == device.index | |
| ) | |
| if not matches: | |
| raise ValueError( | |
| f"The noise generator is on {generator_device} but the state is on " | |
| f"{device}; use a CPU generator or one on the state's device." | |
| ) | |
| def _to_device(host: Tensor, device: torch.device) -> Tensor: | |
| """Copy a host tensor to ``device`` through pinned memory without a sync.""" | |
| if device.type == "cpu": | |
| return host | |
| return host.pin_memory().to(device=device, non_blocking=True) | |
| def standard_normal( | |
| shape: tuple[int, ...], *, generator: torch.Generator, device: torch.device | |
| ) -> Tensor: | |
| """Draw one float32 ``N(0, 1)`` tensor of ``shape`` on ``device``. | |
| A CPU generator fills a host buffer (``Tensor.normal_``) and copies it over; | |
| a device generator calls ``torch.randn`` on the device. | |
| Raises: | |
| ValueError: If a device generator is on another device. | |
| """ | |
| _require_generator_device(generator, device) | |
| if torch.device(generator.device).type == "cpu": | |
| host = torch.empty(shape, dtype=torch.float32, device="cpu") | |
| host.normal_(generator=generator) | |
| return _to_device(host, device) | |
| return torch.randn(shape, device=device, dtype=torch.float32, generator=generator) | |
| class BrownianIntervalNormal: | |
| """Normalized Brownian increments on a fixed time domain, one tree per sample. | |
| ``sample(start, end)`` returns ``(W(end) - W(start)) / sqrt(|end - start|)`` | |
| in normalized domain units, so increments over adjacent intervals are | |
| consistent whatever the schedule. Trees live on the generator's device | |
| (the host for a CPU generator). | |
| """ | |
| def __init__( | |
| self, *, state: Tensor, start: float, end: float, generator: torch.Generator | |
| ) -> None: | |
| """Draw one tree entropy per batch item from ``generator``. | |
| Raises: | |
| ValueError: For a non-finite or empty domain, or a generator on | |
| another device than the state. | |
| """ | |
| if not (math.isfinite(start) and math.isfinite(end)) or start >= end: | |
| raise ValueError( | |
| f"The Brownian domain must be finite with start < end; got " | |
| f"[{start}, {end}]." | |
| ) | |
| _require_generator_device(generator, state.device) | |
| tree_device = torch.device(generator.device) | |
| if tree_device.type != "cpu": | |
| tree_device = state.device | |
| entropies = torch.randint( | |
| low=0, | |
| high=_ENTROPY_HIGH, | |
| size=(int(state.shape[0]),), | |
| device=torch.device(generator.device), | |
| dtype=torch.int64, | |
| generator=generator, | |
| ) | |
| origin = torch.zeros( | |
| tuple(state.shape[1:]), device=tree_device, dtype=torch.float32 | |
| ) | |
| self._trees = tuple( | |
| BrownianTree( | |
| t0=0.0, | |
| w0=origin, | |
| t1=1.0, | |
| entropy=int(entropy), | |
| tol=BROWNIAN_RELATIVE_TOLERANCE, | |
| ) | |
| for entropy in entropies.cpu().tolist() | |
| ) | |
| self._start = start | |
| self._span = end - start | |
| self._end = end | |
| def sample(self, *, state: Tensor, start: float, end: float) -> Tensor: | |
| """Return the normalized increment from ``start`` to ``end`` like ``state``. | |
| Raises: | |
| ValueError: For equal endpoints or a query outside the domain. | |
| """ | |
| low, high = min(start, end), max(start, end) | |
| if low == high or low < self._start or high > self._end: | |
| raise ValueError( | |
| f"Brownian query [{start}, {end}] is empty or outside " | |
| f"[{self._start}, {self._end}]." | |
| ) | |
| normalized_low = (low - self._start) / self._span | |
| normalized_high = (high - self._start) / self._span | |
| sign = 1.0 if end > start else -1.0 | |
| scale = sign / math.sqrt(normalized_high - normalized_low) | |
| increments = torch.stack( | |
| tuple(tree(normalized_low, normalized_high) for tree in self._trees), dim=0 | |
| ) | |
| scaled = increments * scale | |
| if scaled.device.type == "cpu": | |
| return _to_device(scaled, state.device).to(dtype=state.dtype) | |
| return scaled.to(device=state.device, dtype=state.dtype) | |