Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514-thinking-16k· AnthropicHugging Face LMArena Human Preference 140K

how to compute l-inf distance between two tensors with pytorch

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-7-sonnet-20250219’s answer.
  1. User

    how to compute l-inf distance between two tensors with pytorch

  2. Claude Assistant

    The L-infinity (L∞) distance between two tensors is the maximum absolute difference between their corresponding elements. Here are several ways to compute it in PyTorch:

    Method 1: Using torch.dist()

    import torch
    
    # Create two example tensors
    tensor1 = torch.tensor([1.0, 2.0, 3.0])
    tensor2 = torch.tensor([1.5, 2.3, 2.8])
    
    # Compute L-inf distance
    l_inf_distance = torch.dist(tensor1, tensor2, p=float('inf'))
    print(l_inf_distance)  # tensor(0.3000)
    

    Method 2: Using torch.norm() on the difference

    # Compute the difference and then take the inf-norm
    diff = tensor1 - tensor2
    l_inf_distance = torch.norm(diff, p=float('inf'))
    print(l_inf_distance)  # tensor(0.3000)
    

    Method 3: Manual computation

    # Compute absolute differences and take the maximum
    l_inf_distance = torch.max(torch.abs(tensor1 - tensor2))
    print(l_inf_distance)  # tensor(0.3000)
    

    Working with multi-dimensional tensors

    All these methods work with tensors of any shape:

    # 2D tensors example
    tensor1 = torch.randn(3, 4)
    tensor2 = torch.randn(3, 4)
    
    # Any of these methods will work
    l_inf_distance = torch.dist(tensor1, tensor2, p=float('inf'))
    # or
    l_inf_distance = torch.norm(tensor1 - tensor2, p=float('inf'))
    # or
    l_inf_distance = torch.max(torch.abs(tensor1 - tensor2))
    

    The most concise and clear approach is typically using torch.dist() with p=float('inf'), as it directly expresses the intent of computing the L-infinity distance between two tensors.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.