| 1 | from pathlib import Path |
| 2 | from typing import Any |
| 3 | |
| 4 | import torch |
| 5 | |
| 6 | |
| 7 | def rms_norm(x: torch.Tensor, weight: torch.Tensor | None = None, eps: float = 1e-6) -> torch.Tensor: |
| 8 | """Root-mean-square (RMS) normalize `x` over its last dimension. |
| 9 | Thin wrapper around `torch.nn.functional.rms_norm` that infers the normalized |
| 10 | shape and forwards `weight` and `eps`. |
| 11 | """ |
| 12 | return torch.nn.functional.rms_norm(x, (x.shape[-1],), weight=weight, eps=eps) |
| 13 | |
| 14 | |
| 15 | def check_config_value(config: dict, key: str, expected: Any) -> None: # noqa: ANN401 |
| 16 | actual = config.get(key) |
| 17 | if actual != expected: |
| 18 | raise ValueError(f"Config value {key} is {actual}, expected {expected}") |
| 19 | |
| 20 | |
| 21 | def to_velocity( |
| 22 | sample: torch.Tensor, |
| 23 | sigma: float | torch.Tensor, |
| 24 | denoised_sample: torch.Tensor, |
| 25 | calc_dtype: torch.dtype = torch.float32, |
| 26 | ) -> torch.Tensor: |
| 27 | """ |
| 28 | Convert the sample and its denoised version to velocity. |
| 29 | Returns: |
| 30 | Velocity |
| 31 | """ |
| 32 | if isinstance(sigma, torch.Tensor): |
| 33 | sigma = sigma.to(calc_dtype).item() |
| 34 | if sigma == 0: |
| 35 | raise ValueError("Sigma can't be 0.0") |
| 36 | return ((sample.to(calc_dtype) - denoised_sample.to(calc_dtype)) / sigma).to(sample.dtype) |
| 37 | |
| 38 | |
| 39 | def to_denoised( |
| 40 | sample: torch.Tensor, |
| 41 | velocity: torch.Tensor, |
| 42 | sigma: float | torch.Tensor, |
| 43 | calc_dtype: torch.dtype = torch.float32, |
| 44 | ) -> torch.Tensor: |
| 45 | """ |
| 46 | Convert the sample and its denoising velocity to denoised sample. |
| 47 | Returns: |
| 48 | Denoised sample |
| 49 | """ |
| 50 | if isinstance(sigma, torch.Tensor): |
| 51 | sigma = sigma.to(calc_dtype) |
| 52 | return (sample.to(calc_dtype) - velocity.to(calc_dtype) * sigma).to(sample.dtype) |
| 53 | |
| 54 | |
| 55 | def find_matching_file(root_path: str, pattern: str) -> Path: |
| 56 | """ |
| 57 | Recursively search for files matching a glob pattern and return the first match. |
| 58 | """ |
| 59 | matches = list(Path(root_path).rglob(pattern)) |
| 60 | if not matches: |
| 61 | raise FileNotFoundError(f"No files matching pattern '{pattern}' found under {root_path}") |
| 62 | return matches[0] |
| 63 |