Skip to content

Unexpected Result when Binary Operation is Applied to Tensors with Different Lengths #125530

@jp2masa

Description

@jp2masa

Description

Tensor binary operations (add/subtract, multiply/divide, power, ...) yield unexpected results when applied to tensors with different lengths. The dimensions that should be broadcast are actually truncated to length 1.

Reproduction Steps

  1. Compile and run the following code:
    using System;
    using System.Numerics.Tensors;
    
    var t1 = Tensor.Create<double>([2, 3, 5, 7, 11, 13], [2, 3]);
    var t2 = Tensor.Create<double>([-2, -3], [2, 1]);
    Console.WriteLine((t1 * t2).ToString([10, 10]));
  2. The output, printed to stdout, is:
    System.Numerics.Tensors.Tensor<Double>[2, 1] {
      [-4],
      [-9]
    }
    
  3. Replacing the definition of t2 with var t2 = Tensor.Create<double>([-2, -3, -5, -7], [2, 2]); correctly throws an exception:
    System.ArgumentException: 'Lengths are not compatible with each other.'
    

Expected behavior

I expected one of the following behaviors:

  1. Broadcasting similar to NumPy:

    Code

    import numpy as np
    t1 = np.array([[2, 3, 5], [7, 11, 13]])
    t2 = np.array([[-2], [-3]])
    print(t1 * t2)

    Output

    [[ -4  -6 -10]
     [-21 -33 -39]]
    
  2. An error indicating incompatible sizes, if this is not an intended usage of the API.

Actual behavior

The dimensions of the operands that should be broadcast are truncated to length 1.

Regression?

No response

Known Workarounds

Broadcasting the tensors manually before computing the product.

Configuration

  • .NET: 10.0.3
  • .NET SDK: 10.0.200-preview.0.26103.119
  • OS: Windows 11 Home 25H2 26200.7922
  • Architecture: x64

Other information

No response

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions