Skip to content

Commit 3daa8fe

Browse files
lkdvosclaude
andauthored
Enforce strict Einstein index rules in @tensor (#289)
* stricter index verification * Test remaining index verification branches Cover the paths of `verifyindices` that were not yet exercised: - `/` and `\`: the divisor is verified as a separate scope, while the closed labels of the tensor operand do escape to the enclosing term. - `conj`, adjoint and unary minus, which pass the labels through. - `@notensor`, which is skipped entirely. This also adds the first runtime test for `@notensor`, covering the corresponding branches in `processcontractions`, `replaceindices` and `tensorify`. - the argument of an explicit `tensorscalar`, which is a separate scope but is still verified. Two branches turned out to be unreachable and are removed instead: an explicit `tensorscalar(...)` call is not an `istensorexpr`, and a sum node cannot carry scalar terms since `istensorexpr` requires all of its terms to be tensor expressions. Both cases are already handled through the scalar factor fallback of `_indexscope_product`. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent a351c31 commit 3daa8fe

6 files changed

Lines changed: 233 additions & 19 deletions

File tree

‎src/indexnotation/contractiontrees.jl‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,8 @@ function insertcontractiontrees!(
9494
end
9595
args = ex.args[2:end]
9696
network = map(getindices, args)
97-
for a in getallindices(ex)
98-
count(a in n for n in network) <= 2 ||
99-
throw(ArgumentError("index $a appears more than twice in tensor contraction: $ex"))
100-
end
97+
# the index labels have already been verified by `verifyindices`, such that every label
98+
# appears at most twice within this term
10199
tree = treebuilder(network)
102100
treeex = treesorter(args, tree, depth)
103101

‎src/indexnotation/parser.jl‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ mutable struct TensorParser
77
postprocessors::Vector{Any}
88
function TensorParser()
99
preprocessors = [
10-
normalizeindices, expandconj, nconindexcompletion, extracttensorobjects,
10+
normalizeindices, verifyindices, expandconj, nconindexcompletion,
11+
extracttensorobjects,
1112
]
1213
contractiontreebuilder = defaulttreebuilder
1314
contractiontreesorter = defaulttreesorter

‎src/indexnotation/verifiers.jl‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,119 @@ function istensorexpr(ex)
181181
return false
182182
end
183183

184+
"""
185+
verifyindices(ex) -> ex
186+
187+
Verify that all index labels in `ex` obey the strict Einstein summation convention, and throw an `ArgumentError` if not.
188+
This convention entails that within a single term, every index label should appear either once (an open index) or exactly twice (a contracted index, either between two different tensors or within a single tensor as a trace).
189+
Parentheses group the factors of a term and thus determine the contraction order, but do not introduce a new scope for the index labels.
190+
Different terms of a sum, different statements, and the argument of an explicit `tensorscalar` call do constitute separate scopes, in which labels can be reused freely.
191+
192+
This routine expects the indices to be normalized, i.e. it should be called after [`normalizeindices`](@ref).
193+
The expression is returned unchanged, such that this can be used as a preprocessor.
194+
"""
195+
function verifyindices(ex)
196+
if isexpr(ex, :macrocall) && ex.args[1] == Symbol("@notensor")
197+
return ex
198+
elseif istensor(ex) || istensorexpr(ex)
199+
_indexscope(ex)
200+
elseif isa(ex, Expr)
201+
foreach(verifyindices, ex.args)
202+
end
203+
return ex
204+
end
205+
206+
# analyze a single term and return its open indices, along with the indices that have been
207+
# contracted (closed) within that term; throws if the Einstein convention is violated
208+
function _indexscope(ex)
209+
if istensor(ex)
210+
_, leftind, rightind = decomposetensor(ex)
211+
allind = vcat(leftind, rightind)
212+
open, closed = Any[], Any[]
213+
for label in unique(allind)
214+
n = count(isequal(label), allind)
215+
if n == 1
216+
push!(open, label)
217+
elseif n == 2
218+
push!(closed, label)
219+
else
220+
throw(ArgumentError("@tensor: index $label appears $n times in tensor $ex"))
221+
end
222+
end
223+
return open, closed
224+
elseif isexpr(ex, :call)
225+
# note: an explicit `tensorscalar(...)` call is not an `istensorexpr`, so it never
226+
# reaches here; it is verified as a separate scope through the scalar factor
227+
# fallback in `_indexscope_product`
228+
if (ex.args[1] == :+ || ex.args[1] == :-) && length(ex.args) > 2
229+
return _indexscope_sum(ex)
230+
elseif ex.args[1] == :*
231+
return _indexscope_product(ex)
232+
elseif ex.args[1] == :/ && length(ex.args) == 3
233+
verifyindices(ex.args[3])
234+
return _indexscope(ex.args[2])
235+
elseif ex.args[1] == :\ && length(ex.args) == 3
236+
verifyindices(ex.args[2])
237+
return _indexscope(ex.args[3])
238+
elseif length(ex.args) == 2 # unary plus or minus, conj, adjoint, ...
239+
return _indexscope(ex.args[2])
240+
end
241+
elseif isexpr(ex, prime) && length(ex.args) == 1
242+
return _indexscope(ex.args[1])
243+
end
244+
return Any[], Any[]
245+
end
246+
247+
function _indexscope_sum(ex)
248+
# unlike a product, a sum cannot carry scalar terms, since `istensorexpr` requires all
249+
# of its terms to be tensor expressions
250+
open = nothing
251+
for term in ex.args[2:end]
252+
openterm, = _indexscope(term)
253+
if isnothing(open)
254+
open = openterm
255+
elseif Set(openterm) != Set(open)
256+
throw(
257+
ArgumentError(
258+
"@tensor: non-matching indices $(tuple(open...)) and $(tuple(openterm...)) between terms of $ex"
259+
)
260+
)
261+
end
262+
end
263+
# the contracted labels of the individual terms are not visible outside of that term
264+
return open, Any[]
265+
end
266+
267+
function _indexscope_product(ex)
268+
opens, closeds = Any[], Any[]
269+
for factor in ex.args[2:end]
270+
if !istensorexpr(factor)
271+
verifyindices(factor) # scalar factor: cannot contribute index labels
272+
continue
273+
end
274+
openfactor, closedfactor = _indexscope(factor)
275+
append!(opens, openfactor)
276+
append!(closeds, closedfactor)
277+
end
278+
# labels that are already contracted cannot be reused within this term
279+
for label in unique(closeds)
280+
n = 2 * count(isequal(label), closeds) + count(isequal(label), opens)
281+
n > 2 && throw(ArgumentError("@tensor: index $label appears $n times in $ex"))
282+
end
283+
open, closed = Any[], closeds
284+
for label in unique(opens)
285+
n = count(isequal(label), opens)
286+
if n == 1
287+
push!(open, label)
288+
elseif n == 2
289+
push!(closed, label)
290+
else
291+
throw(ArgumentError("@tensor: index $label appears $n times in $ex"))
292+
end
293+
end
294+
return open, closed
295+
end
296+
184297
"""
185298
isassignment(ex)
186299

‎test/auxiliary.jl‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,82 @@
118118
:(promote_add(promote_contract(scalartype(a), scalartype(b)), scalartype(c)))
119119
end
120120

121+
@testset "index verification" begin
122+
using TensorOperations: verifyindices, normalizeindices
123+
124+
# every label appears once or exactly twice within a single term; different terms of
125+
# a sum, different statements and explicit `tensorscalar` calls are separate scopes
126+
valid = (
127+
:(a[-1, -2] := b[-1, 1] * c[1, -2]),
128+
:(a[-1, -2] := b[-1, 1] * c[1, -2] + d[-1, 1] * e[1, -2]),
129+
:(a[-1, -2] := b[-1, 1] * (c[1, 2] + d[1, 2]) * e[2, -2]),
130+
:(a[-1, -2] := b[-1, 1] * c[1, -2] * (d[2, 2])),
131+
:(a[x, y] := b[x, y] - 2 * c[y, x]),
132+
:(a[-1] := b[-1, 1, 1]),
133+
:(a[x, y] := b[x, z] * tensorscalar(c[z, z]) * d[z, y]),
134+
:(a[x, y] := b[x′, x] * c[x′, y]),
135+
# the divisor of `/` and `\` is a separate scope, but the tensor operand is not
136+
:(a[x, y] := b[x, z] * c[z, y] / tensorscalar(d[z, z])),
137+
:(a[x, y] := tensorscalar(d[z, z]) \ (b[x, z] * c[z, y])),
138+
:(a[x, y] := b[x, z] * c[z, y] / alpha),
139+
:(a[x, y] := 2 \ (b[x, z] * c[z, y])),
140+
# conjugation, adjoint and unary minus pass the labels through unchanged
141+
:(a[x, y] := conj(b[x, z]) * c[z, y]),
142+
:(a[x, y] := (b[x, z])' * c[z, y]),
143+
:(a[x, y] := -(b[x, z] * c[z, y])),
144+
# `@notensor` is not index-verified at all
145+
:(a[-1, -2] := (@notensor f(1)) * b[-1, -2]),
146+
:(a[-1, -2] := (@notensor g[1, 1, 1]) * b[-1, -2]),
147+
quote
148+
@notensor b = c[1, 1, 1]
149+
a[-1, -2] := d[-1, 1] * e[1, -2]
150+
end,
151+
quote
152+
a[-1, -2] := b[-1, 1] * c[1, -2]
153+
d[-1, -2] := e[-1, 1] * f[1, -2]
154+
end,
155+
)
156+
for ex in valid
157+
@test verifyindices(normalizeindices(ex)) isa Expr
158+
end
159+
160+
# a label consumed by a trace or contraction cannot be reused within the same term,
161+
# and all terms of a sum should have matching open indices
162+
invalid = (
163+
:(a[-1, -2, -3; -4, -5] := b[-2, 1] * c[1, -3; 1, -5] * d[-1, 1; -4]), # issue #288
164+
:(a[-1, -2] := b[-1, 1; 1, -2] * c[1, 1]),
165+
:(a[-1, -2] := b[-1, 1] * c[1, -2] * d[1, 1, -3, -3]),
166+
:(a[-1, -2] := b[-1, 1] * c[1, -2] * (d[1, 1])),
167+
# parentheses do not introduce a new scope for the labels
168+
:(a[-1, -2] := (b[-1, 1] * c[1, -3]) * (d[-3, 1] * e[1, -2])),
169+
:(a[-1, -2] := b[-1, 1] * c[1, -3] * d[-3, 1] * e[1, -2]),
170+
:(a[-1] := b[1, 1, 1]),
171+
:(a[-1, -2] := b[-1, -2] + c[-1, 1]),
172+
:(a[x, y] := b[x′, x] * c[x′, y] * d[x', 1]), # primes are equal after normalizing
173+
# the divisor of `/` and `\` is verified in its own scope
174+
:(a[x, y] := b[x, y] / tensorscalar(c[z, z, z])),
175+
:(a[x, y] := tensorscalar(c[z, z, z]) \ b[x, y]),
176+
# ... but the labels of the tensor operand do escape to the enclosing term
177+
:(a[-1] := (b[-1, 1, 1] / 2) * c[1, 1]),
178+
:(a[-1] := (2 \ b[-1, 1, 1]) * c[1, 1]),
179+
# the argument of an explicit `tensorscalar` is still verified
180+
:(a[x, y] := b[x, z] * tensorscalar(c[z, z, z]) * d[z, y]),
181+
:(a[x, y] := b[x, y] * tensorscalar(c[z, z] + d[z, w])),
182+
:(alpha = tensorscalar(c[z, z, z])),
183+
)
184+
for ex in invalid
185+
@test_throws ArgumentError verifyindices(normalizeindices(ex))
186+
end
187+
188+
# errors are thrown at macro expansion time
189+
@test_throws ArgumentError @macroexpand(
190+
@tensor T[-1, -2, -3; -4, -5] := A[-2, 1] * B[1, -3; 1, -5] * C[-1, 1; -4]
191+
)
192+
@test_throws ArgumentError @macroexpand(
193+
@tensoropt T[-1, -2] := A[-1, 1] * B[1, -2] * C[1, 1]
194+
)
195+
end
196+
121197
@testset "parsecost" begin
122198
using TensorOperations: parsecost, Power
123199
@test parsecost(:(3 / 5)) === 3 / 5

‎test/cutensor.jl‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -280,15 +280,15 @@ if cuTENSOR.functional()
280280
@tensor C[3, 1, 4, 2] = β * C[3, 1, 4, 2] + α * A[1, 2, 3, 4]
281281
Ccopy = β * Ccopy + α * Acopy
282282
@test copy(C) ≈ Ccopy
283-
@test_throws IndexError begin
283+
@test_throws ArgumentError @macroexpand(
284284
@tensor C[3, 1, 4, 2] = 0.5 * C[3, 1, 4, 2] + 1.2 * A[1, 2, 3]
285-
end
285+
)
286286
@test_throws CUTENSORError begin
287287
@tensor C[3, 1, 4, 2] = 0.5 * C[3, 1, 4, 2] + 1.2 * A[3, 1, 2, 4]
288288
end
289-
@test_throws IndexError begin
289+
@test_throws ArgumentError @macroexpand(
290290
@tensor C[1, 1, 2, 3] = 0.5 * C[1, 1, 2, 3] + 1.2 * A[1, 2, 3, 4]
291-
end
291+
)
292292
end
293293

294294
@testset "views 3" begin
@@ -310,9 +310,7 @@ if cuTENSOR.functional()
310310
@test_throws CUTENSORError begin
311311
@tensor B[c, b] += α * A[a, b, c, a]
312312
end
313-
@test_throws IndexError begin
314-
@tensor B[c, b] += α * A[a, b, a, a]
315-
end
313+
@test_throws ArgumentError @macroexpand(@tensor B[c, b] += α * A[a, b, a, a])
316314
@test_throws CUTENSORError begin
317315
@tensor B[c, b] += α * A[a, b, a, c]
318316
end

‎test/tensor.jl‎

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -125,15 +125,15 @@ backendlist = (BaseCopy(), BaseView(), StridedNative(), StridedBLAS())
125125
@tensor backend = b C[3, 1, 4, 2] = β * C[3, 1, 4, 2] + α * A[1, 2, 3, 4]
126126
Ccopy = β * Ccopy + α * Acopy
127127
@test C ≈ Ccopy
128-
@test_throws IndexError begin
128+
@test_throws ArgumentError @macroexpand(
129129
@tensor C[3, 1, 4, 2] = 0.5 * C[3, 1, 4, 2] + 1.2 * A[1, 2, 3]
130-
end
130+
)
131131
@test_throws DimensionMismatch begin
132132
@tensor C[3, 1, 4, 2] = 0.5 * C[3, 1, 4, 2] + 1.2 * A[3, 1, 2, 4]
133133
end
134-
@test_throws IndexError begin
134+
@test_throws ArgumentError @macroexpand(
135135
@tensor C[1, 1, 2, 3] = 0.5 * C[1, 1, 2, 3] + 1.2 * A[1, 2, 3, 4]
136-
end
136+
)
137137
end
138138

139139
@testset "views 3" begin
@@ -155,9 +155,7 @@ backendlist = (BaseCopy(), BaseView(), StridedNative(), StridedBLAS())
155155
@test_throws DimensionMismatch begin
156156
@tensor B[c, b] += α * A[a, b, c, a]
157157
end
158-
@test_throws IndexError begin
159-
@tensor B[c, b] += α * A[a, b, a, a]
160-
end
158+
@test_throws ArgumentError @macroexpand(@tensor B[c, b] += α * A[a, b, a, a])
161159
@test_throws DimensionMismatch begin
162160
@tensor B[c, b] += α * A[a, b, a, c]
163161
end
@@ -593,3 +591,33 @@ end
593591
@test E ≈ c * (A * B + C * D)
594592
end
595593
end
594+
595+
# these are independent of the backend, so they are only tested once
596+
@testset "notensor" begin
597+
list = randn(Float64, (4, 4, 2))
598+
A = randn(Float64, (4, 4))
599+
B = randn(Float64, (4, 4))
600+
D = randn(Float64, (3, 3))
601+
602+
@tensor begin
603+
@notensor X = list[:, :, 1]
604+
@notensor Y = list[:, :, 2]
605+
C[a, c] := X[a, b] * Y[b, c]
606+
end
607+
@test C ≈ list[:, :, 1] * list[:, :, 2]
608+
609+
@tensor G[a, c] := (@notensor tr(D)) * A[a, b] * B[b, c]
610+
@test G ≈ tr(D) * A * B
611+
end
612+
613+
@testset "scalar division" begin
614+
A = randn(Float64, (4, 4))
615+
B = randn(Float64, (4, 4))
616+
D = randn(Float64, (3, 3))
617+
618+
# the label `b` is reused within the divisor, which is a separate scope
619+
@tensor E[a, c] := A[a, b] * B[b, c] / tensorscalar(D[b, b])
620+
@test E ≈ (A * B) / tr(D)
621+
@tensor F[a, c] := tensorscalar(D[b, b]) \ (A[a, b] * B[b, c])
622+
@test F ≈ (A * B) / tr(D)
623+
end

0 commit comments

Comments
 (0)