| 1 | from typing import Tuple |
| 2 | |
| 3 | import torch |
| 4 | from einops import rearrange |
| 5 | |
| 6 | from ltx_core.model.upsampler.blur_downsample import BlurDownsample |
| 7 | from ltx_core.model.upsampler.pixel_shuffle import PixelShuffleND |
| 8 | |
| 9 | |
| 10 | def _rational_for_scale(scale: float) -> Tuple[int, int]: |
| 11 | mapping = {0.75: (3, 4), 1.5: (3, 2), 2.0: (2, 1), 4.0: (4, 1)} |
| 12 | if float(scale) not in mapping: |
| 13 | raise ValueError(f"Unsupported scale {scale}. Choose from {list(mapping.keys())}") |
| 14 | return mapping[float(scale)] |
| 15 | |
| 16 | |
| 17 | class SpatialRationalResampler(torch.nn.Module): |
| 18 | """ |
| 19 | Fully-learned rational spatial scaling: up by 'num' via PixelShuffle, then anti-aliased |
| 20 | downsample by 'den' using fixed blur + stride. Operates on H,W only. |
| 21 | For dims==3, work per-frame for spatial scaling (temporal axis untouched). |
| 22 | Args: |
| 23 | mid_channels (`int`): Number of intermediate channels for the convolution layer |
| 24 | scale (`float`): Spatial scaling factor. Supported values are: |
| 25 | - 0.75: Downsample by 3/4 (reduce spatial size) |
| 26 | - 1.5: Upsample by 3/2 (increase spatial size) |
| 27 | - 2.0: Upsample by 2x (double spatial size) |
| 28 | - 4.0: Upsample by 4x (quadruple spatial size) |
| 29 | Any other value will raise a ValueError. |
| 30 | """ |
| 31 | |
| 32 | def __init__(self, mid_channels: int, scale: float): |
| 33 | super().__init__() |
| 34 | self.scale = float(scale) |
| 35 | self.num, self.den = _rational_for_scale(self.scale) |
| 36 | self.conv = torch.nn.Conv2d(mid_channels, (self.num**2) * mid_channels, kernel_size=3, padding=1) |
| 37 | self.pixel_shuffle = PixelShuffleND(2, upscale_factors=(self.num, self.num)) |
| 38 | self.blur_down = BlurDownsample(dims=2, stride=self.den) |
| 39 | |
| 40 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 41 | b, _, f, _, _ = x.shape |
| 42 | x = rearrange(x, "b c f h w -> (b f) c h w") |
| 43 | x = self.conv(x) |
| 44 | x = self.pixel_shuffle(x) |
| 45 | x = self.blur_down(x) |
| 46 | x = rearrange(x, "(b f) c h w -> b c f h w", b=b, f=f) |
| 47 | return x |
| 48 |