To address the task, we'll create a function cross_domain_random_permutation that performs the following operations:
-
Patch Extraction: The input tensor with dimensions (batch_size, channels, height, width) is divided into non-overlapping patches of size (patch_height, patch_width). This results in num_patches per image.
-
Patch Selection: Randomly select 5% of these patches (epsilon = 0.05) for permutation.
-
Transformation and Permutation:
- Apply a transformation (e.g., RGB to YUV) to the selected patches.
- Permute these transformed patches across different channels to introduce domain adaptation.
-
Reconstruction: The permuted patches are then reassembled back into the original tensor shape (batch_size, channels, height, width).
The implementation ensures:
- PEP-8 Compliance: Adheres to Python's style guide for readability.
- Type Hints: Utilizes the
typing module for clarity.
- Efficiency: Employs optimized tensor operations suitable for large datasets.
- Error Handling: Incorporates comprehensive checks to handle unexpected conditions gracefully.
- Maintainability: The code is structured for clarity and ease of future modifications.
Below is the self-contained Python module implementing the described functionality, along with test cases to demonstrate its usage.
import torch
import torch.nn.functional as F
from typing import Tuple, Optional, Callable
import math
import random
def cross_domain_random_permutation(
tensor: torch.Tensor,
patch_size: Tuple[int, int],
transform: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
epsilon: float = 0.05,
seed: Optional[int] = None
) -> torch.Tensor:
"""
Apply Cross-Domain Random Permutation on input tensor.
Args:
tensor (torch.Tensor): Input tensor of shape (B, C, H, W).
patch_size (Tuple[int, int]): Size of each patch (patch_height, patch_width).
transform (Optional[Callable[[torch.Tensor], torch.Tensor]]):
Transformation function to apply to selected patches.
epsilon (float, optional): Fraction of patches to permute. Default is 0.05.
seed (Optional[int], optional): Random seed for reproducibility. Default is None.
Returns:
torch.Tensor: Tensor after applying cross-domain random permutation,
with shape (B, C, H, W).
Raises:
ValueError: If input tensor dimensions are invalid or patch size is incompatible.
"""
if tensor.ndim != 4:
raise ValueError(f"Input tensor must have 4 dimensions (B, C, H, W), got {tensor.ndim} dimensions.")
if not (0 < epsilon <= 1):
raise ValueError(f"Epsilon must be in the range (0, 1], got {epsilon}.")
B, C, H, W = tensor.shape
patch_h, patch_w = patch_size
if H % patch_h != 0 or W % patch_w != 0:
raise ValueError(f"Patch size {patch_size} must evenly divide tensor dimensions ({H}, {W}).")
if patch_h <= 0 or patch_w <= 0:
raise ValueError(f"Patch dimensions must be positive integers, got {patch_size}.")
if seed is not None:
torch.manual_seed(seed)
random.seed(seed)
# Calculate number of patches
num_patches_h = H // patch_h
num_patches_w = W // patch_w
num_patches = num_patches_h * num_patches_w
# Extract patches
patches = tensor.unfold(2, patch_h, patch_h).unfold(3, patch_w, patch_w)
# patches shape: (B, C, num_patches_h, num_patches_w, patch_h, patch_w)
patches = patches.contiguous().view(B, C, num_patches, patch_h, patch_w)
# patches shape: (B, C, N, patch_h, patch_w)
# Determine number of patches to permute
num_perm_patches = max(1, math.floor(epsilon * num_patches))
# Perform permutation for each image in the batch
for b in range(B):
# Select patches to permute
perm_indices = random.sample(range(num_patches), num_perm_patches)
# Apply transformation if provided
if transform is not None:
patches[b, :, perm_indices, :, :] = transform(patches[b, :, perm_indices, :, :])
# Permute patches across channels
for c in range(C):
shuffled_indices = perm_indices.copy()
random.shuffle(shuffled_indices)
patches[b, c, perm_indices, :, :] = patches[b, c, shuffled_indices, :, :]
# Reconstruct the tensor from patches
patches = patches.view(B, C, num_patches_h, num_patches_w, patch_h, patch_w)
patches = patches.permute(0, 1, 2, 4, 3, 5).contiguous()
tensor_reconstructed = patches.view(B, C, H, W)
return tensor_reconstructed
# Unit Tests
if __name__ == "__main__":
def rgb_to_yuv(patches: torch.Tensor) -> torch.Tensor:
"""
Convert RGB patches to YUV color space.
Assumes patches have 3 channels.
"""
if patches.size(1) != 3:
raise ValueError("RGB to YUV conversion requires 3 channels.")
# Define transformation matrix
matrix = torch.tensor([[0.299, 0.587, 0.114],
[-0.14713, -0.28886, 0.436],
[0.615, -0.51499, -0.10001]], dtype=patches.dtype, device=patches.device)
yuv = torch.matmul(patches.permute(0, 1, 2, 3, 4), matrix.T)
return yuv.permute(0, 1, 2, 3, 4)
# Test parameters
B, C, H, W = 2, 3, 16, 16
patch_size = (4, 4)
epsilon = 0.05
seed = 42
# Create a sample tensor
sample_tensor = torch.arange(B * C * H * W, dtype=torch.float32).reshape(B, C, H, W)
# Apply cross_domain_random_permutation without transformation
permuted_tensor = cross_domain_random_permutation(
tensor=sample_tensor,
patch_size=patch_size,
transform=None,
epsilon=epsilon,
seed=seed
)
print("Permuted Tensor without transformation:")
print(permuted_tensor)
# Apply cross_domain_random_permutation with RGB to YUV transformation
try:
permuted_tensor_yuv = cross_domain_random_permutation(
tensor=sample_tensor,
patch_size=patch_size,
transform=rgb_to_yuv,
epsilon=epsilon,
seed=seed
)
print("\nPermuted Tensor with RGB to YUV transformation:")
print(permuted_tensor_yuv)
except ValueError as e:
print(f"Error during transformation: {e}")
# Test error handling with incompatible patch size
try:
cross_domain_random_permutation(
tensor=sample_tensor,
patch_size=(5, 5), # Incompatible patch size
epsilon=epsilon
)
except ValueError as e:
print(f"\nExpected Error for incompatible patch size: {e}")
# Test error handling with invalid epsilon
try:
cross_domain_random_permutation(
tensor=sample_tensor,
patch_size=patch_size,
epsilon=1.5 # Invalid epsilon
)
except ValueError as e:
print(f"\nExpected Error for invalid epsilon: {e}")
# Test error handling with invalid tensor dimensions
try:
invalid_tensor = torch.randn(3, 4, 5) # Invalid dimensions
cross_domain_random_permutation(
tensor=invalid_tensor,
patch_size=patch_size,
epsilon=epsilon
)
except ValueError as e:
print(f"\nExpected Error for invalid tensor dimensions: {e}")
Explanation
-
Function Definition:
cross_domain_random_permutation: Accepts a tensor, patch size, an optional transformation function, epsilon, and an optional seed for reproducibility.
- Type Hints: Provided for better clarity and maintainability.
- Error Handling: Checks for tensor dimensions, patch size compatibility, and valid epsilon values.
-
Patch Extraction:
- Utilizes
unfold to divide the tensor into patches.
- Reshapes the tensor to organize patches for processing.
-
Patch Selection and Permutation:
- Calculates the number of patches to permute based on
epsilon.
- For each image in the batch:
- Randomly selects patches to permute.
- Applies the transformation if provided.
- Permutes the selected patches across channels.
-
Reconstruction:
- Reassembles the permuted patches back into the original tensor shape.
-
Unit Tests:
- Demonstrates the function's usage with and without a transformation.
- Includes tests for error handling by providing invalid inputs.
This implementation ensures that the function is robust, efficient, and adheres to best practices, making it suitable for handling large datasets and scalable applications.