GPUCodeForces/S1/wut0n_#17/manhattan_torchcode.py

46 lines
1.3 KiB
Python

import torch
import torch.nn as nn
class Model(nn.Module):
"""
Manhattan Distance implementation.
Computes the Manhattan distance (L1 distance) between two sets of vectors.
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Compute Manhattan distance between x and y.
Args:
x (torch.Tensor): First set of vectors [batch_size, feature_dim]
y (torch.Tensor): Second set of vectors [batch_size, feature_dim]
Returns:
torch.Tensor: Manhattan distances [batch_size]
"""
# Input validation
if x.shape != y.shape:
raise ValueError(f"Input tensors must have the same shape, got {x.shape} and {y.shape}")
if x.dim() != 2:
raise ValueError(f"Input tensors must be 2D, got {x.dim()}D")
# Compute Manhattan distance: Σ|x_i - y_i|
manhattan_dist = torch.sum(torch.abs(x - y), dim=1)
return manhattan_dist
batch_size = 256
feature_dim = 512
def get_inputs():
# Generate two sets of vectors
x = torch.randn(batch_size, feature_dim)
y = torch.randn(batch_size, feature_dim)
return [x, y]
def get_init_inputs():
return [] # No special initialization inputs needed