import torch
import torch.nn.functional as F
from torch import Tensor
from typing import Tuple
import math
def frequency_aware_patch_scaling(
tensor: Tensor,
patch_size: Tuple[int, int],
eps: float = 0.05
) -> Tensor:
"""
Applies frequency-aware scaling to patches of the input tensor using Discrete Cosine Transform (DCT).
High frequencies are attenuated while mid-level frequencies are boosted.
Args:
tensor (Tensor): Input tensor of shape (batch_size, channels, height, width).
patch_size (Tuple[int, int]): Size of the patches (patch_height, patch_width).
eps (float, optional): Epsilon value to prevent division by zero. Defaults to 0.05.
Returns:
Tensor: Tensor after frequency-aware patch scaling with shape (batch_size, channels, height, width).
Raises:
ValueError: If input tensor does not have 4 dimensions.
ValueError: If patch dimensions are larger than the input tensor's spatial dimensions.
"""
if not isinstance(tensor, Tensor):
raise TypeError("Input must be a PyTorch Tensor.")
if tensor.dim() != 4:
raise ValueError(f"Expected tensor with 4 dimensions, got {tensor.dim()}.")
batch_size, channels, height, width = tensor.shape
patch_height, patch_width = patch_size
if patch_height > height or patch_width > width:
raise ValueError("Patch size must be smaller than or equal to tensor's spatial dimensions.")
try:
# Calculate the number of patches along height and width
num_patches_h = height // patch_height
num_patches_w = width // patch_width
# Trim the tensor to make it divisible by the patch size
trimmed_height = num_patches_h * patch_height
trimmed_width = num_patches_w * patch_width
tensor = tensor[:, :, :trimmed_height, :trimmed_width]
# Reshape tensor to (batch_size, channels, num_patches_h, patch_height, num_patches_w, patch_width)
tensor_patches = tensor.reshape(
batch_size,
channels,
num_patches_h,
patch_height,
num_patches_w,
patch_width
).permute(0, 1, 2, 4, 3, 5).contiguous()
# Merge batch and channels for processing
tensor_patches = tensor_patches.view(-1, 1, patch_height, patch_width)
# Apply DCT (Type-II) on the patches
patches_dct = torch.fft.dct(torch.fft.dct(tensor_patches, norm='ortho', dim=2), norm='ortho', dim=3)
# Create frequency scaling mask
freq_mask = create_frequency_mask(patch_height, patch_width)
# Apply scaling: attenuate high frequencies, boost mid frequencies
scaled_dct = patches_dct * freq_mask
# Apply inverse DCT (Type-III) to get back to spatial domain
patches_idct = torch.fft.idct(torch.fft.idct(scaled_dct, norm='ortho', dim=2), norm='ortho', dim=3)
# Reshape back to original tensor shape
patches_idct = patches_idct.view(
batch_size,
channels,
num_patches_h,
num_patches_w,
patch_height,
patch_width
).permute(0, 1, 2, 4, 3, 5).contiguous()
# Combine patches back to the original tensor shape
output = patches_idct.view(batch_size, channels, trimmed_height, trimmed_width)
return output
except Exception as e:
raise RuntimeError(f"An error occurred during frequency-aware patch scaling: {e}")
def create_frequency_mask(patch_height: int, patch_width: int) -> Tensor:
"""
Creates a frequency scaling mask that attenuates high frequencies and boosts mid-level frequencies.
Args:
patch_height (int): Height of the patch.
patch_width (int): Width of the patch.
Returns:
Tensor: Frequency scaling mask of shape (1, 1, patch_height, patch_width).
"""
y = torch.linspace(0, 1, steps=patch_height).unsqueeze(1).repeat(1, patch_width)
x = torch.linspace(0, 1, steps=patch_width).unsqueeze(0).repeat(patch_height, 1)
distance = torch.sqrt((x - 0.5) ** 2 + (y - 0.5) ** 2)
mask = 1 - (distance / distance.max()) # Invert distance: center has high values
# Attenuate high frequencies and boost mid frequencies
mask = mask ** 2 # Quadratic scaling for smoother attenuation
mask = mask.unsqueeze(0).unsqueeze(0) # Shape: (1, 1, H, W)
return mask
# ============================ Unit Tests ============================
def test_frequency_aware_patch_scaling():
"""
Unit tests for the frequency_aware_patch_scaling function.
"""
# Test case 1: Basic functionality
batch_size, channels, height, width = 2, 3, 32, 32
patch_size = (8, 8)
tensor = torch.randn(batch_size, channels, height, width)
output = frequency_aware_patch_scaling(tensor, patch_size)
assert output.shape == (batch_size, channels, height, width), "Output shape mismatch."
# Test case 2: Patch size equals tensor size
patch_size = (32, 32)
output = frequency_aware_patch_scaling(tensor, patch_size)
assert output.shape == (batch_size, channels, height, width), "Output shape mismatch."
# Test case 3: Patch size does not divide tensor dimensions exactly
tensor = torch.randn(batch_size, channels, 30, 30)
patch_size = (8, 8)
output = frequency_aware_patch_scaling(tensor, patch_size)
assert output.shape == (batch_size, channels, 24, 24), "Output shape mismatch after trimming."
# Test case 4: Invalid tensor dimensions
try:
invalid_tensor = torch.randn(channels, height, width)
frequency_aware_patch_scaling(invalid_tensor, patch_size)
except ValueError as e:
assert str(e) == "Expected tensor with 4 dimensions, got 3."
# Test case 5: Patch size larger than tensor dimensions
try:
patch_size = (64, 64)
frequency_aware_patch_scaling(tensor, patch_size)
except ValueError as e:
assert str(e) == "Patch size must be smaller than or equal to tensor's spatial dimensions."
print("All tests passed.")
if __name__ == "__main__":
test_frequency_aware_patch_scaling()