bsc-quantic / Tenet.jl

Composable Tensor Network library in Julia
https://bsc-quantic.github.io/Tenet.jl/
Apache License 2.0
17 stars 1 forks source link

`DimensionMismatch` error not raised for inconsistent dimensions in `TensorNetwork` #69

Closed jofrevalles closed 12 months ago

jofrevalles commented 1 year ago

Summary

In the current implementation of the TensorNetwork function, inconsistent dimensions of the same tensor index are not correctly checked and handled. This issue manifests when two tensors with the same index label, but have different dimensions in the same TensorNetwork.

Example

julia> using Tenet

julia> A = Tensor(rand(3, 3), (:i, :j))
3×3 Tensor{Float64, 2, Matrix{Float64}}:
 0.397522  0.872019   0.541417
 0.463644  0.0310421  0.479054
 0.429812  0.923011   0.628436

julia> B = Tensor(rand(2, 2), (:j, :k))
2×2 Tensor{Float64, 2, Matrix{Float64}}:
 0.383957  0.154286
 0.454446  0.608856

julia> tn = TensorNetwork([A, B]) # No error is raised here
TensorNetwork{Arbitrary, NamedTuple{(), Tuple{}}}(#tensors=2, #labels=3)

In the above example, despite :j index having dimensions of 3 in Tensor A and 2 in Tensor B, no DimensionMismatch error is raised, which is counter-intuitive and can potentially lead to incorrect results.

Interestingly, the DimensionMismatch error is correctly thrown when using the push! function:

julia> push!(tn, Tensor(rand(3, 3), (:k, :l))) # Raises DimensionMismatch error
ERROR: DimensionMismatch: size(tensor,k)=3 but should be equal to size(tn,k)=2
Stacktrace:
 [1] push!(tn::TensorNetwork{Arbitrary, NamedTuple{(), Tuple{}}}, tensor::Tensor{Float64, 2, Matrix{Float64}})
   @ Tenet ~/git/Tenet.jl/src/TensorNetwork.jl:167
 [2] top-level scope
   @ REPL[22]:1

This suggests that the error handling mechanism might be correctly implemented in push! but is not properly functioning in the TensorNetwork constructor function.

mofeing commented 1 year ago

Before the refactor, the constructor was calling push! so it was correct. But I decided to recode it to avoid some overhead of overcalling push!.

I might bypassed some checks that were essential. Can you add a test for this case?