Skip to content

Commit 49f4884

Browse files
lkdvosclaude
andcommitted
Emit canonical planar index tuples at macro-expansion time
`planar_contract_indices` only needs the index partitions of both operands, which `@planar` knows: `_extract_tensormap_objects` checks the partitions written in the expression against the actual tensors. Record them while preprocessing and canonicalize the index tuples of the emitted planar contractions, so that the runtime canonicalization is left with nothing to do for macro-generated code. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 8b38100 commit 49f4884

5 files changed

Lines changed: 73 additions & 1 deletion

File tree

‎src/planar/macros.jl‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ function planarparser(planarexpr, kwargs...)
2121
push!(parser.postprocessors, ex -> _free_temporaries(ex, temporaries))
2222
push!(parser.postprocessors, _insert_planar_operations)
2323

24+
partitions = Dict{Any, Union{Nothing, IndexPartition}}()
25+
push!(parser.postprocessors, ex -> canonicalizeplanarindices(ex, partitions))
26+
2427
# braiding tensors need to be instantiated before kwargs are processed
2528
push!(parser.preprocessors, _construct_braidingtensors)
2629

@@ -91,6 +94,7 @@ function planarparser(planarexpr, kwargs...)
9194
parser.contractioncostcheck = nothing
9295
push!(parser.preprocessors, ex -> _check_planarity(ex))
9396
push!(parser.preprocessors, ex -> _decompose_planar_contractions(ex, temporaries))
97+
push!(parser.preprocessors, ex -> _index_partitions!(partitions, ex))
9498

9599
return parser
96100
end

‎src/planar/planaroperations.jl‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,19 @@ function _planar_rotate(indx::IndexTuple, head::IndexTuple, tail::IndexTuple)
230230
return head′, tail′
231231
end
232232

233+
"""
234+
IndexPartition(numout, numin)
235+
236+
Stand-in for a tensor with `numout` outgoing and `numin` incoming indices, to canonicalize
237+
index tuples with [`planar_contract_indices`](@ref) at macro-expansion time.
238+
"""
239+
struct IndexPartition
240+
numout::Int
241+
numin::Int
242+
end
243+
numout(p::IndexPartition) = p.numout
244+
numin(p::IndexPartition) = p.numin
245+
233246
"""
234247
planar_contract_indices(A, pA, B, pB, pAB) -> pA′, pB′, pAB′
235248
@@ -240,7 +253,8 @@ are cyclic partitions of the indices of `A` and `B`, i.e. such that
240253
241254
For sector types with `GenericUnit()` these are the only partitions with valid intermediate
242255
spaces, so all space computations should use them. `A` and `B` can be anything supporting
243-
`codomainind` and `domainind`, in particular `AbstractTensorMap`s and `HomSpace`s.
256+
`codomainind` and `domainind`, in particular `AbstractTensorMap`s, `HomSpace`s and
257+
[`IndexPartition`](@ref)s.
244258
245259
See also [`planarcontract!`](@ref) and [`planaralloc_contract`](@ref).
246260
"""

‎src/planar/postprocessors.jl‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ end
5454
# TODO: replace _planarmethod with planarmethod in everything below
5555
const _PLANAR_OPERATIONS = (:planaradd!, :planartrace!, :planarcontract!)
5656
const _PLANAR_ALLOCATIONS = (:planaralloc_contract,)
57+
const _PLANAR_CONTRACTIONS = (:planarcontract!, :planaralloc_contract)
5758

5859
function _insert_planar_operations(ex)
5960
if isexpr(ex, :call)
@@ -99,6 +100,29 @@ function _insert_planar_operations(ex)
99100
return ex
100101
end
101102

103+
"""
104+
canonicalizeplanarindices(ex, partitions)
105+
106+
Replace the index tuples of every planar contraction in `ex` by their canonical form, as
107+
obtained from [`planar_contract_indices`](@ref) and the index partitions in `partitions`.
108+
Contractions whose operands have no known partition are left to be canonicalized at runtime.
109+
"""
110+
function canonicalizeplanarindices(ex, partitions)
111+
if isexpr(ex, :call) && length(ex.args) ≥ 7 && ex.args[1] isa GlobalRef &&
112+
ex.args[1].mod === TensorKit && ex.args[1].name ∈ _PLANAR_CONTRACTIONS
113+
A, pA, B, pB, pAB = ex.args[3], ex.args[4], ex.args[5], ex.args[6], ex.args[7]
114+
WA, WB = get(partitions, A, nothing), get(partitions, B, nothing)
115+
if !isnothing(WA) && !isnothing(WB) && pA isa Index2Tuple &&
116+
pB isa Index2Tuple && pAB isa Index2Tuple
117+
args = copy(ex.args)
118+
args[4], args[6], args[7] = planar_contract_indices(WA, pA, WB, pB, pAB)
119+
return Expr(:call, args...)
120+
end
121+
end
122+
return ex isa Expr ?
123+
Expr(ex.head, (canonicalizeplanarindices(a, partitions) for a in ex.args)...) : ex
124+
end
125+
102126
# like `TO.insertargument`, but matching `GlobalRef`s into `TensorKit`
103127
function _insertargument(ex, arg, methods)
104128
if isexpr(ex, :call) && ex.args[1] isa GlobalRef &&

‎src/planar/preprocessors.jl‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,20 @@ function _extract_tensormap_objects(ex)
7575
)
7676
return Expr(:block, pre, pre2, ex, post)
7777
end
78+
# used by `@planar`: record the index partition of every tensor in `ex`, keyed by its object.
79+
# Objects that occur with conflicting partitions are recorded as `nothing`. Note that
80+
# `_extract_tensormap_objects` checks these partitions against the actual tensors at runtime.
81+
function _index_partitions!(partitions, ex)
82+
if TO.istensor(ex)
83+
obj, leftind, rightind = TO.decomposetensor(ex)
84+
p = IndexPartition(length(leftind), length(rightind))
85+
partitions[obj] = get(partitions, obj, p) == p ? p : nothing
86+
elseif ex isa Expr
87+
foreach(a -> _index_partitions!(partitions, a), ex.args)
88+
end
89+
return ex
90+
end
91+
7892
_is_adjoint(ex) = isexpr(ex, TO.prime)
7993
_remove_adjoint(ex) = _is_adjoint(ex) ? ex.args[1] : ex
8094
_add_adjoint(ex) = Expr(TO.prime, ex)

‎test/tensors/planar.jl‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,22 @@ end
192192
@test !isempty(alloc_trailing)
193193
end
194194

195+
@testset "canonical index tuples" begin
196+
# the emitted partitions are planar, unlike the raw ones of the decomposition
197+
function planarindices(ex, out = Any[])
198+
ex isa Expr || return out
199+
if Meta.isexpr(ex, :call) && ex.args[1] isa GlobalRef &&
200+
ex.args[1].name === :planarcontract!
201+
push!(out, (ex.args[4], ex.args[6], ex.args[7]))
202+
end
203+
foreach(a -> planarindices(a, out), ex.args)
204+
return out
205+
end
206+
ex = @macroexpand @planar ρ[a; b] := t[a c d; e f] * u[e f; b c d]
207+
@test planarindices(ex) ==
208+
[(((1,), (4, 5, 3, 2)), ((1, 2, 5, 4), (3,)), ((1,), (2,)))]
209+
end
210+
195211
@testset "allocator is rewound" begin
196212
# A `BufferAllocator` hands out slices of a single buffer and reclaims them only
197213
# by rewinding its offset -- `tensorfree!` is a no-op for it. The temporaries a

0 commit comments

Comments
 (0)