File size: 15,087 Bytes
06f9561 | 1 2 3 4 5 6 7 8 9 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 | """Deterministic distributed random sampling for flow-matching training.
The normal PyTorch CUDA RNG is process-local. Seeding every distributed rank
with the same value therefore gives equal random draws whenever ranks execute
the same sequence of random operations. This module avoids that coupling and
also makes the intended global-batch coverage explicit:
* Gaussian action noise uses a rank-specific stream.
* Sigma uses one jittered stratum per sample in the *global* batch, followed by
a deterministic global permutation.
* RTC delay is either the deployment delay or a globally balanced draw from an
explicit categorical distribution.
Sampling is keyed by ``(seed, draw_index, component[, rank])`` instead of by an
opaque long-lived generator state. Saving ``state_dict()`` after a batch and
loading it on resume reproduces the next batch exactly. Register an instance
with ``Accelerator.register_for_checkpointing`` so Accelerate saves that small
state next to the model and optimizer state.
"""
from __future__ import annotations
from dataclasses import dataclass
import math
from typing import Any, Literal, Mapping, Sequence
import torch
_STATE_VERSION = 1
_MASK64 = (1 << 64) - 1
_MAX_TORCH_SEED = (1 << 63) - 1
# Component identifiers are deliberately fixed constants. Changing one
# component's implementation must not shift the streams used by the others.
_SIGMA_JITTER_COMPONENT = 0x5349474D415F4A49
_SIGMA_PERM_COMPONENT = 0x5349474D415F504D
_DELAY_OFFSET_COMPONENT = 0x44454C41595F4F46
_DELAY_PERM_COMPONENT = 0x44454C41595F504D
_NOISE_COMPONENT = 0x4E4F4953455F524B
def _splitmix64(value: int) -> int:
"""Return a stable 64-bit mix without relying on Python's salted hash."""
value = (value + 0x9E3779B97F4A7C15) & _MASK64
value = ((value ^ (value >> 30)) * 0xBF58476D1CE4E5B9) & _MASK64
value = ((value ^ (value >> 27)) * 0x94D049BB133111EB) & _MASK64
return (value ^ (value >> 31)) & _MASK64
def _component_seed(
base_seed: int,
draw_index: int,
component: int,
*,
rank: int | None = None,
) -> int:
"""Derive a torch-compatible seed for one component and one draw."""
value = _splitmix64(int(base_seed) & _MASK64)
value ^= _splitmix64(int(draw_index) & _MASK64)
value ^= _splitmix64(int(component) & _MASK64)
if rank is not None:
value ^= _splitmix64(int(rank) & _MASK64)
return _splitmix64(value) & _MAX_TORCH_SEED
@dataclass(frozen=True)
class DelaySamplingConfig:
"""RTC delay policy.
``fixed`` trains every example with the delay used at deployment.
``balanced`` uses systematic categorical sampling over the global batch.
For a requested probability ``p``, the number of examples is always close
to ``p * global_batch_size`` instead of being allowed to clump as it would
under independent ``randint`` draws.
"""
mode: Literal["fixed", "balanced"]
deployment_delay: int | None = None
values: tuple[int, ...] = ()
probabilities: tuple[float, ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "values", tuple(int(value) for value in self.values))
object.__setattr__(
self,
"probabilities",
tuple(float(probability) for probability in self.probabilities),
)
if self.mode == "fixed":
if self.deployment_delay is None or int(self.deployment_delay) < 0:
raise ValueError("fixed RTC delay requires a non-negative deployment_delay")
if self.values or self.probabilities:
raise ValueError("fixed RTC delay must not also define values/probabilities")
return
if self.mode != "balanced":
raise ValueError(f"unknown RTC delay sampling mode: {self.mode!r}")
if self.deployment_delay is not None:
raise ValueError("balanced RTC delay must not define deployment_delay")
if not self.values:
raise ValueError("balanced RTC delay requires at least one delay value")
if any(value < 0 for value in self.values):
raise ValueError("RTC delay values must be non-negative")
if len(set(self.values)) != len(self.values):
raise ValueError("RTC delay values must be unique")
if self.probabilities and len(self.probabilities) != len(self.values):
raise ValueError("RTC delay values and probabilities must have equal length")
probabilities = self.normalized_probabilities()
if any(not math.isfinite(probability) or probability < 0 for probability in probabilities):
raise ValueError("RTC delay probabilities must be finite and non-negative")
if sum(probabilities) <= 0:
raise ValueError("at least one RTC delay probability must be positive")
@classmethod
def fixed(cls, deployment_delay: int) -> "DelaySamplingConfig":
return cls(mode="fixed", deployment_delay=int(deployment_delay))
@classmethod
def balanced(
cls,
values: Sequence[int],
probabilities: Sequence[float] | None = None,
) -> "DelaySamplingConfig":
return cls(
mode="balanced",
values=tuple(int(value) for value in values),
probabilities=tuple(float(value) for value in probabilities or ()),
)
@classmethod
def uniform(cls, max_delay: int) -> "DelaySamplingConfig":
"""Balance all valid training delays ``0 .. max_delay - 1``."""
if int(max_delay) <= 0:
raise ValueError("max_delay must be positive")
return cls.balanced(tuple(range(int(max_delay))))
def normalized_probabilities(self) -> tuple[float, ...]:
if self.mode != "balanced":
return ()
raw = self.probabilities or tuple(1.0 for _ in self.values)
total = float(sum(raw))
if not math.isfinite(total) or total <= 0:
raise ValueError("RTC delay probability sum must be finite and positive")
return tuple(float(value) / total for value in raw)
def signature(self) -> dict[str, Any]:
return {
"mode": self.mode,
"deployment_delay": self.deployment_delay,
"values": self.values,
"probabilities": self.probabilities,
}
@dataclass(frozen=True)
class FlowRandomBatch:
"""Random quantities consumed by one local flow-matching microbatch."""
sigmas: torch.Tensor
noise: torch.Tensor
delay: torch.Tensor | None
draw_index: int
class DistributedFlowRandomSampler:
"""Generate reproducible, non-duplicated distributed flow randomness.
Every rank must use the same ``seed``, ``world_size``, sigma bounds, delay
policy, and local batch size at a given draw. ``rank`` is the global rank,
not the node-local CUDA index.
"""
def __init__(
self,
*,
seed: int,
rank: int,
world_size: int,
sigma_min: float = 0.05,
sigma_max: float = 1.0,
delay: DelaySamplingConfig | None = None,
draw_index: int = 0,
) -> None:
if int(seed) < 0:
raise ValueError("seed must be non-negative")
if int(world_size) <= 0:
raise ValueError("world_size must be positive")
if int(rank) < 0 or int(rank) >= int(world_size):
raise ValueError("rank must satisfy 0 <= rank < world_size")
if not math.isfinite(float(sigma_min)) or not math.isfinite(float(sigma_max)):
raise ValueError("sigma bounds must be finite")
if float(sigma_min) < 0 or float(sigma_max) <= float(sigma_min):
raise ValueError("sigma bounds must satisfy 0 <= sigma_min < sigma_max")
if int(draw_index) < 0:
raise ValueError("draw_index must be non-negative")
self.seed = int(seed)
self.rank = int(rank)
self.world_size = int(world_size)
self.sigma_min = float(sigma_min)
self.sigma_max = float(sigma_max)
self.delay_config = delay
self._draw_index = int(draw_index)
@property
def draw_index(self) -> int:
"""Number of already generated microbatches."""
return self._draw_index
def state_dict(self) -> dict[str, Any]:
"""Small checkpoint state accepted by Accelerate's checkpoint hooks."""
return {
"version": _STATE_VERSION,
"draw_index": self._draw_index,
"config": self._config_signature(),
}
def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
version = int(state_dict.get("version", -1))
if version != _STATE_VERSION:
raise ValueError(
f"unsupported distributed flow sampler state version {version}; "
f"expected {_STATE_VERSION}"
)
saved_config = state_dict.get("config")
current_config = self._config_signature()
if saved_config != current_config:
raise ValueError(
"distributed flow sampler configuration changed across resume: "
f"saved={saved_config!r}, current={current_config!r}"
)
draw_index = int(state_dict["draw_index"])
if draw_index < 0:
raise ValueError("checkpointed draw_index must be non-negative")
self._draw_index = draw_index
def sample_like(self, actions: torch.Tensor) -> FlowRandomBatch:
"""Sample sigma/noise/delay matching an action tensor."""
if not actions.is_floating_point():
raise ValueError("actions must have a floating-point dtype")
return self.sample(
actions.shape,
device=actions.device,
noise_dtype=actions.dtype,
)
def sample(
self,
action_shape: Sequence[int],
*,
device: torch.device | str,
noise_dtype: torch.dtype = torch.float32,
) -> FlowRandomBatch:
"""Sample one local microbatch and advance ``draw_index`` by one."""
shape = tuple(int(size) for size in action_shape)
if not shape or shape[0] <= 0 or any(size <= 0 for size in shape):
raise ValueError("action_shape must contain only positive dimensions")
if not noise_dtype.is_floating_point:
raise ValueError("noise_dtype must be floating point")
local_batch_size = shape[0]
target_device = torch.device(device)
draw_index = self._draw_index
sigmas = self._sample_sigmas(local_batch_size, draw_index).to(
device=target_device,
dtype=torch.float32,
)
delay = self._sample_delay(local_batch_size, draw_index)
if delay is not None:
delay = delay.to(device=target_device, dtype=torch.long)
noise = self._sample_noise(shape, target_device, noise_dtype, draw_index)
# Advance only after all component draws succeeded.
self._draw_index += 1
return FlowRandomBatch(
sigmas=sigmas,
noise=noise,
delay=delay,
draw_index=draw_index,
)
def _config_signature(self) -> dict[str, Any]:
return {
"seed": self.seed,
# Rank is intentionally omitted. Accelerate may restore one shared
# custom state file on all ranks; the live rank still selects its
# own global-batch slice and rank-specific noise stream.
"world_size": self.world_size,
"sigma_min": self.sigma_min,
"sigma_max": self.sigma_max,
"delay": self.delay_config.signature() if self.delay_config is not None else None,
}
@staticmethod
def _cpu_generator(seed: int) -> torch.Generator:
generator = torch.Generator(device="cpu")
generator.manual_seed(int(seed))
return generator
def _local_slice(self, local_batch_size: int) -> slice:
start = self.rank * local_batch_size
return slice(start, start + local_batch_size)
def _sample_sigmas(self, local_batch_size: int, draw_index: int) -> torch.Tensor:
global_batch_size = self.world_size * local_batch_size
jitter_generator = self._cpu_generator(
_component_seed(self.seed, draw_index, _SIGMA_JITTER_COMPONENT)
)
permutation_generator = self._cpu_generator(
_component_seed(self.seed, draw_index, _SIGMA_PERM_COMPONENT)
)
jitter = torch.rand(
global_batch_size,
generator=jitter_generator,
dtype=torch.float64,
)
unit_sigmas = (
torch.arange(global_batch_size, dtype=torch.float64) + jitter
) / float(global_batch_size)
sigmas = self.sigma_min + (self.sigma_max - self.sigma_min) * unit_sigmas
permutation = torch.randperm(global_batch_size, generator=permutation_generator)
return sigmas[permutation][self._local_slice(local_batch_size)]
def _sample_delay(self, local_batch_size: int, draw_index: int) -> torch.Tensor | None:
config = self.delay_config
if config is None:
return None
if config.mode == "fixed":
return torch.full(
(local_batch_size,),
int(config.deployment_delay),
dtype=torch.long,
)
global_batch_size = self.world_size * local_batch_size
offset_generator = self._cpu_generator(
_component_seed(self.seed, draw_index, _DELAY_OFFSET_COMPONENT)
)
permutation_generator = self._cpu_generator(
_component_seed(self.seed, draw_index, _DELAY_PERM_COMPONENT)
)
# A single randomized systematic offset makes every categorical count
# floor/ceil(probability * global_batch_size), eliminating IID clumps.
offset = torch.rand((), generator=offset_generator, dtype=torch.float64)
quantiles = (
torch.arange(global_batch_size, dtype=torch.float64) + offset
) / float(global_batch_size)
probabilities = torch.tensor(
config.normalized_probabilities(),
dtype=torch.float64,
)
cumulative = torch.cumsum(probabilities, dim=0)
cumulative[-1] = 1.0
category_ids = torch.searchsorted(cumulative, quantiles, right=False)
values = torch.tensor(config.values, dtype=torch.long)[category_ids]
permutation = torch.randperm(global_batch_size, generator=permutation_generator)
return values[permutation][self._local_slice(local_batch_size)]
def _sample_noise(
self,
shape: tuple[int, ...],
device: torch.device,
dtype: torch.dtype,
draw_index: int,
) -> torch.Tensor:
generator = torch.Generator(device=device)
generator.manual_seed(
_component_seed(
self.seed,
draw_index,
_NOISE_COMPONENT,
rank=self.rank,
)
)
return torch.randn(shape, device=device, dtype=dtype, generator=generator)
|