Quantizes a tensor to a specified bit depth using per-channel min-max normalization.
(
params: torch.Tensor, bit_depth: int = 8
)
| 13 | |
| 14 | |
| 15 | def _quantize_tensor( |
| 16 | params: torch.Tensor, bit_depth: int = 8 |
| 17 | ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, List[int]]: |
| 18 | """Quantizes a tensor to a specified bit depth using per-channel min-max normalization.""" |
| 19 | # Calculate the minimum and maximum value for each channel |
| 20 | mins = torch.amin(params, dim=tuple(range(params.ndim - 1)), keepdim=True) |
| 21 | maxs = torch.amax(params, dim=tuple(range(params.ndim - 1)), keepdim=True) |
| 22 | scale = maxs - mins |
| 23 | scale[scale == 0] = 1.0 # Prevent division by zero |
| 24 | |
| 25 | params_norm = (params - mins) / scale |
| 26 | |
| 27 | max_val = (2**bit_depth) - 1 |
| 28 | uint_type = f"uint{bit_depth}" if bit_depth == 8 else "int32" # PyTorch does not have uint16 |
| 29 | video = (params_norm * max_val).round().to(getattr(torch, uint_type)) |
| 30 | |
| 31 | # Squeeze for easier serialization |
| 32 | mins = mins.squeeze(tuple(range(params.ndim - 1))) |
| 33 | maxs = maxs.squeeze(tuple(range(params.ndim - 1))) |
| 34 | original_shape = list(params.shape) |
| 35 | return video, mins, maxs, original_shape |
| 36 | |
| 37 | def _dequantize_tensor(video: torch.Tensor, meta: Dict[str, Any]) -> torch.Tensor: |
| 38 | """Dequantizes a video tensor using per-channel metadata.""" |