forked from ccf-ai-infra/GPUCodeForces
50 lines
1.5 KiB
Python
50 lines
1.5 KiB
Python
import torch
|
|
import torch.nn as nn
|
|
|
|
class Model(nn.Module):
|
|
"""
|
|
Hamming Distance implementation.
|
|
Computes the Hamming 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 Hamming 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: Hamming 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 Hamming distance: count of different elements
|
|
# Step 1: Compare elements (x != y gives boolean tensor)
|
|
diff = (x != y)
|
|
|
|
# Step 2: Convert to float and sum along feature dimension
|
|
distance = torch.sum(diff.float(), dim=1)
|
|
|
|
return distance
|
|
|
|
batch_size = 256
|
|
feature_dim = 512
|
|
|
|
def get_inputs():
|
|
# Generate two sets of integer vectors (0 or 1 for simplicity)
|
|
x = torch.randint(0, 2, (batch_size, feature_dim)).float()
|
|
y = torch.randint(0, 2, (batch_size, feature_dim)).float()
|
|
return [x, y]
|
|
|
|
def get_init_inputs():
|
|
return [] # No special initialization inputs needed
|