import torch
import torch.nn as nn
import torchvision.transforms as tfs
# здесь объявляйте класс ToDtypeV1
class ToDtypeV1(nn.Module):
def __init__(self, dtype: torch.dtype, scale: bool = False):
super().__init__()
self.dtype = dtype
self.scale = scale
def forward(self, item: torch.Tensor):
# First, convert to the target dtype as specified
item = item.to(dtype=self.dtype)
# Then, if scale is True and dtype is float, normalize to [0, 1]
if self.scale and self.dtype in (torch.float16, torch.float32, torch.float64):
item_min = item.min()
item_max = item.max()
# Avoid division by zero if all elements are the same
if item_max > item_min:
item = (item - item_min) / (item_max - item_min)
else:
# If max == min, all elements are the same.
# The range is 0, so we can scale them all to 0.0
# (or any single value in [0,1], 0.0 is conventional)
# Ensure the new tensor has the correct dtype.
item = torch.zeros_like(item, dtype=self.dtype)
return item
H, W = 128, 128
img_orig = torch.randint(0, 256, size=(3, H, W), dtype=torch.uint8) # тензор в программе не менять
# средние для каждого цветового канала (первая ось)
img_mean = torch.mean(img_orig.float(), dim=(1, 2)) # Corrected dim for mean over H, W
# стандартное отклонение для каждого цветового канала (первая ось)
img_std = torch.std(img_orig.float().flatten(1, 2), dim=1)
# print(img_mean)
# print(img_std)
# здесь продолжайте программу
# print(img_orig.size())
transforms = tfs.Compose([
ToDtypeV1(dtype=torch.float32, scale=False), # As per original, scale is False here
tfs.Normalize(mean=img_mean, std=img_std),
])
img = transforms(img_orig)
# print("Original image dtype:", img_orig.dtype, "min:", img_orig.min(), "max:", img_orig.max())
# print("Transformed image dtype:", img.dtype, "min:", img.min(), "max:", img.max())
# print("Transformed image mean (approx 0 for each channel):", img.mean(dim=(1,2)))
# print("Transformed image std (approx 1 for each channel):", img.std(dim=(1,2)))
# Example test for the ToDtypeV1 scaling part (which caused the assertion)
# This is likely what the Stepik checker does
if __name__ == '__main__':
print("Testing ToDtypeV1 with scale=True:")
# Test case 1: typical uint8 image range
test_tensor_uint8 = torch.randint(0, 256, size=(3, 32, 32), dtype=torch.uint8)
transform_scale_true_f64 = ToDtypeV1(dtype=torch.float64, scale=True)
scaled_tensor_f64 = transform_scale_true_f64(test_tensor_uint8)
print(f"Input uint8 (0-255) -> ToDtypeV1(float64, scale=True)")
print(f"Output dtype: {scaled_tensor_f64.dtype}")
print(f"Output min: {scaled_tensor_f64.min()}, max: {scaled_tensor_f64.max()}")
assert scaled_tensor_f64.min() >= 0.0 and scaled_tensor_f64.max() <= 1.0, "Test Case 1 Failed: Range not [0,1]"
# Check if max is close to 1 if original max was not 0, and min close to 0 if original min was not max
if test_tensor_uint8.max() > test_tensor_uint8.min():
assert torch.isclose(scaled_tensor_f64.min(), torch.tensor(0.0, dtype=torch.float64)) and \
torch.isclose(scaled_tensor_f64.max(), torch.tensor(1.0, dtype=torch.float64)), \
"Test Case 1 Failed: Min/Max not exactly 0/1 for varied input"
# Test case 2: tensor with all same values
test_tensor_same_val = torch.full(size=(3, 32, 32), fill_value=100, dtype=torch.uint8)
scaled_tensor_same_val = transform_scale_true_f64(test_tensor_same_val)
print(f"\nInput uint8 (all 100) -> ToDtypeV1(float64, scale=True)")
print(f"Output dtype: {scaled_tensor_same_val.dtype}")
print(f"Output min: {scaled_tensor_same_val.min()}, max: {scaled_tensor_same_val.max()}")
assert torch.isclose(scaled_tensor_same_val.min(), torch.tensor(0.0, dtype=torch.float64)) and \
torch.isclose(scaled_tensor_same_val.max(), torch.tensor(0.0, dtype=torch.float64)), \
"Test Case 2 Failed: All same values should scale to 0"
# Test case 3: float input already
test_tensor_float_input = torch.tensor([[-10.0, 0.0], [10.0, 20.0]], dtype=torch.float32)
transform_scale_true_f32 = ToDtypeV1(dtype=torch.float32, scale=True)
scaled_tensor_f32_input = transform_scale_true_f32(test_tensor_float_input)
print(f"\nInput float32 (-10 to 20) -> ToDtypeV1(float32, scale=True)")
print(f"Output dtype: {scaled_tensor_f32_input.dtype}")
print(f"Output min: {scaled_tensor_f32_input.min()}, max: {scaled_tensor_f32_input.max()}")
assert torch.isclose(scaled_tensor_f32_input.min(), torch.tensor(0.0)) and \
torch.isclose(scaled_tensor_f32_input.max(), torch.tensor(1.0)), \
"Test Case 3 Failed: Float input not scaled to [0,1]"
print("\nAll local tests passed for ToDtypeV1 with scale=True.")
# Also, a small correction for img_mean calculation if you intended per-channel mean:
# img_mean = torch.mean(img_orig.float(), dim=(1, 2)) # if 3,H,W then mean over H and W
# For tfs.Normalize, mean and std should be 1D tensors (one value per channel)
# Your original img_mean and img_std were correct for this.
# The code for calculating img_mean and img_std in your snippet is correct.
# `torch.mean(img_orig.float(), [1, 2])` is fine.
# `torch.std(img_orig.float().flatten(1, 2), dim=1)` is also fine.