Skip to content

Commit 5816040

Browse files
lkdvosclaude
andcommitted
Simplify the ncon network analysis after review
- `_ncontree_steps` merges the two occurrences of every contraction index directly from the sorted list, rather than searching for the second occurrence. - `_check_nconstyle` compares neighbours in the sorted list of labels instead of counting. - `_indexordertree_steps` asserts that the second occurrence of a contraction index exists, as before, and uses `∋(c)` rather than anonymous functions. - Disconnected parts of the network are combined from left to right. - `resolve_traces` uses comprehensions, without the helpers `_ncon_network` and `_anyvector`. As a consequence, `ncon` can no longer be differentiated with Zygote. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 600aa43 commit 5816040

3 files changed

Lines changed: 31 additions & 45 deletions

File tree

‎ext/TensorOperationsChainRulesCoreExt.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ end
197197
@non_differentiable TensorOperations._ncontree_steps(args...)
198198
@non_differentiable TensorOperations._indexordertree_steps(args...)
199199
# label manipulations that mutate arrays, which is not supported by e.g. Zygote
200-
@non_differentiable TensorOperations._ncon_network(args...)
200+
@non_differentiable TensorOperations.unique2(args...)
201201
@non_differentiable TensorOperations._ncon_labelvector(args...)
202202
@non_differentiable TensorOperations._ncon_conjlist(args...)
203203
@non_differentiable TensorOperations._ncon_symdiff(args...)

‎src/indexnotation/indexordertree.jl‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# verify that every conraction index appears exactly twice, and any other index exactly once
1+
# verify that every contraction index appears exactly twice, and any other index exactly once
22
function _verify_indexorder(network, indexorder)
33
for indices in network
44
for i in indices
@@ -22,11 +22,11 @@ function _indexordertree_steps(network, indexorder)
2222
partialtrees = collect(1:length(network))
2323
group = collect(1:length(network))
2424
for c in indexorder
25-
k1 = findfirst(indices -> c in indices, network)
25+
# trace indices have already been removed from the network
26+
k1 = findfirst(∋(c), network)
2627
isnothing(k1) && continue
27-
# trace indices have already been removed, so `c` appears in another tensor
28-
k2 = findnext(indices -> c in indices, network, k1 + 1)
29-
isnothing(k2) && continue
28+
k2 = findnext(∋(c), network, k1 + 1)
29+
@assert !isnothing(k2) # guaranteed by `_verify_indexorder`
3030
_mergetrees!(steps, partialtrees, group, k1, k2)
3131
end
3232
return _finalizetree!(steps, partialtrees, group)

‎src/indexnotation/ncontree.jl‎

Lines changed: 25 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,33 +5,29 @@ check_nconstyle(network) = _check_nconstyle(network, Val(false))
55
function _check_nconstyle(network, ::Val{check}) where {check}
66
allindices = Vector{Int}()
77
for ind in network
8-
for i in ind
9-
isa(i, Integer) || return check ? false :
10-
throw(IndexError("All indices must be integers"))
11-
push!(allindices, i)
12-
end
8+
all(i -> isa(i, Integer), ind) || return check ? false :
9+
throw(IndexError("All indices must be integers"))
10+
append!(allindices, ind)
1311
end
12+
# after sorting, equal labels are adjacent
1413
sort!(allindices)
14+
n = length(allindices)
1515
j = 1
16-
while j <= length(allindices)
16+
while j <= n
1717
i = allindices[j]
18-
# number of times that `i` appears
19-
n = 1
20-
while j + n <= length(allindices) && allindices[j + n] == i
21-
n += 1
22-
end
2318
if i > 0 # positive labels represent contractions or traces and should appear twice
24-
n == 1 && return check ? false :
19+
(j == n || allindices[j + 1] != i) && return check ? false :
2520
throw(IndexError(lazy"Index $i appears only once in the network"))
26-
n > 2 && return check ? false :
21+
(j + 2 <= n && allindices[j + 2] == i) && return check ? false :
2722
throw(IndexError(lazy"Index $i appears more than twice in the network"))
23+
j += 2
2824
elseif i < 0 # negative labels represent open indices and should appear once
29-
n > 1 && return check ? false :
25+
(j < n && allindices[j + 1] == i) && return check ? false :
3026
throw(IndexError(lazy"Index $i appears more than once in the network"))
27+
j += 1
3128
else # i == 0
3229
return check ? false : throw(IndexError("Index 0 is not allowed in the network"))
3330
end
34-
j += n
3531
end
3632
return check ? true : nothing
3733
end
@@ -56,10 +52,10 @@ function _ncontree_steps(network)
5652
steps = NTuple{2, Int}[]
5753
partialtrees = collect(1:length(network))
5854
group = collect(1:length(network))
59-
for j in sortperm(contractionindices)
60-
k = findnext(==(contractionindices[j]), contractionindices, j + 1)
61-
# each index appears twice, only consider the first occurrence
62-
isnothing(k) || _mergetrees!(steps, partialtrees, group, owners[j], owners[k])
55+
# every contraction index appears twice, so after sorting its occurrences are adjacent
56+
perm = sortperm(contractionindices)
57+
for p in 1:2:length(perm)
58+
_mergetrees!(steps, partialtrees, group, owners[perm[p]], owners[perm[p + 1]])
6359
end
6460
return _finalizetree!(steps, partialtrees, group)
6561
end
@@ -84,16 +80,15 @@ function _mergetrees!(
8480
return steps
8581
end
8682

87-
# Combine the remaining partial trees, which are disconnected and thus require outer products,
88-
# starting from the end.
83+
# Combine the remaining partial trees, which are disconnected and thus require outer products.
8984
function _finalizetree!(
9085
steps::Vector{NTuple{2, Int}}, partialtrees::Vector{Int}, group::Vector{Int}
9186
)
9287
n = length(group)
9388
remaining = unique!(group)
94-
tree = partialtrees[remaining[end]]
95-
for g in Iterators.drop(Iterators.reverse(remaining), 1)
96-
push!(steps, (partialtrees[g], tree))
89+
tree = partialtrees[remaining[1]]
90+
for k in 2:length(remaining)
91+
push!(steps, (tree, partialtrees[remaining[k]]))
9792
tree = n + length(steps)
9893
end
9994
return steps
@@ -144,22 +139,13 @@ end
144139
# Resolve the traces in the network, and canonicalize the types of the tensor list and the
145140
# network, such that the remainder of `ncon` is type stable and only compiled once.
146141
function resolve_traces(tensors, network)
147-
network′ = _ncon_network(network)
148-
all(k -> length(network[k]) == length(network′[k]), eachindex(network)) &&
149-
return _anyvector(tensors), network′
150-
tensors′ = map(tensors, network, network′) do A, IA, IC
151-
return length(IA) == length(IC) ? A : tensortrace(IC, A, _ncon_labelvector(IA))
152-
end
153-
return _anyvector(tensors′), network′
142+
network′ = Vector{Int}[unique2(IA) for IA in network]
143+
tensors′ = Any[
144+
length(IA) == length(IC) ? A : tensortrace(IC, A, _ncon_labelvector(IA))
145+
for (A, IA, IC) in zip(tensors, network, network′)
146+
]
147+
return tensors′, network′
154148
end
155149

156-
# labels after resolving the traces
157-
_ncon_network(network) =
158-
Vector{Int}[_ncon_labelvector(allunique(IA) ? IA : unique2(IA)) for IA in network]
159-
160150
# canonicalize any list of labels, e.g. a `Tuple` or a row matrix like `[1 2 -1]`
161151
_ncon_labelvector(IA) = vec(collect(Int, IA))
162-
163-
# note: avoiding `collect(Any, xs)` and mutation for compatibility with Zygote
164-
_anyvector(xs::AbstractVector) = Vector{Any}(xs)
165-
_anyvector(xs::Tuple) = Any[xs...]

0 commit comments

Comments
 (0)