Skip to content

Commit 87a9b6f

Browse files
committed
Use Cached keys and remove duplicated cache helpers
Use Cached.Hashed and cachekey to share sector structures across degeneracy dimensions without changing the function signature. Pass fusion-tree arguments directly to Cached, retaining the braiding result annotation needed for anyonic inference. Remove the upstream-covered Hashed tests, add TensorKit integration checks, and document native cache configuration and optional extensions.
1 parent 46980a6 commit 87a9b6f

8 files changed

Lines changed: 101 additions & 120 deletions

File tree

‎docs/src/man/fusiontrees.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,23 @@ The `braid` and `permute` routines for double fusion trees will be the main acce
262262
As a consequence, results from these routines are memoized via a `@cached` mechanism.
263263
The caching strategy is controlled by `Cached.CacheStyle`: for `FusionStyle(I) isa UniqueFusion` no caching is used (`NoCache()`), since the result is a single cheap scalar coefficient; for `MultipleFusion` or `GenericFusion` sectors, `GlobalCache()` uses Cached.jl's configured container (ClockCache by default), as computing the transformation matrix can be expensive and results are reused frequently.
264264

265+
TensorKit also uses Cached.jl for sector structures, degeneracy structures and fusion tree transformers.
266+
Sector structures share cache entries across spaces with the same sectors, even if their degeneracy dimensions differ, through `Cached.cachekey`.
267+
The Cached APIs can inspect, resize and configure these caches:
268+
269+
```julia
270+
using TensorKit, Cached
271+
Cached.cache_info(TensorKit)
272+
Cached.set_cache_size!(TensorKit.treebraider, 50_000)
273+
Cached.set_cache_preferences!(TensorKit; maxsize = 50_000, measure = "bytes")
274+
Cached.set_cache_preferences!(; container = "LRU")
275+
```
276+
277+
Preferences are saved in `LocalPreferences.toml` and apply after restarting Julia; a runtime size change applies immediately.
278+
`Cached.uncached(f, args...)` computes a result without consulting or filling the cache.
279+
Optional Cached features, such as the Tachikoma dashboard and SQLite disk caching, remain available through Cached's extensions.
280+
Disk caching requires loading SQLite and defining `Cached.DiskCacheStyle` for the desired function; it is disabled by default, and `empty_globalcaches!()` clears only in-memory caches.
281+
265282
This caching implies that potential inefficiencies in the fusion tree manipulations (which we nonetheless try to avoid) will not seriously affect performance of tensor manipulations.
266283

267284
## Inspecting fusion trees as tensors

‎src/auxiliary/caches.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# `CacheStyle` is imported (not just used) so that the `CacheStyle(::typeof(f), ...)`
33
# specializations in TensorKit, and those of users, extend `Cached.CacheStyle`.
44
import Cached: CacheStyle
5-
using Cached: Cached, @cached, NoCache, GlobalCache, LRU
5+
using Cached: Cached, @cached, NoCache, GlobalCache, Hashed, LRU
66

77
"""
88
const GLOBAL_CACHES

‎src/auxiliary/dicts.jl‎

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -242,25 +242,3 @@ function Base.mergewith(combine, d1::SortedVectorDict{K, V}, d2::SortedVectorDic
242242
unmatched = combine == min ? Returns(nothing) : identity
243243
return _sortedmerge(combine, unmatched, unmatched, d1, d2)
244244
end
245-
246-
"""
247-
Hashed(value, hashfunction = Base.hash, isequal = Base.isequal)
248-
249-
Wrapper struct to alter the `hash` and `isequal` implementations of a given value.
250-
This is useful in the contexts of dictionaries, where you either want to customize the hashfunction,
251-
or consider various values as equal with a different notion of equality.
252-
"""
253-
struct Hashed{T, H <: Function, E <: Function}
254-
val::T
255-
hashf::H
256-
eqf::E
257-
end
258-
259-
Hashed(val, hashf = Base.hash, eqf = Base.isequal) =
260-
Hashed{typeof(val), typeof(hashf), typeof(eqf)}(val, hashf, eqf)
261-
262-
Base.parent(h::Hashed) = h.val
263-
Base.hash(h::Hashed, seed::UInt) = h.hashf(parent(h), seed)
264-
# Note: requires the equality functions to be equal to avoid asymmetric results
265-
Base.isequal(h1::Hashed{<:Any, <:Any, E}, h2::Hashed{<:Any, <:Any, E}) where {E} =
266-
h1.eqf(parent(h1), parent(h2))

‎src/fusiontrees/braiding_manipulations.jl‎

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -284,42 +284,45 @@ function braid(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tuple, leve
284284
@assert numind(src) == length(p[1]) + length(p[2])
285285
@assert numout(src) == length(levels[1]) && numin(src) == length(levels[2])
286286
@assert TupleTools.isperm((p[1]..., p[2]...))
287-
return fsbraid((src, p, levels))
287+
return fsbraid(src, p, levels)
288288
end
289289

290-
const FSPBraidKey{I, N₁, N₂} = Tuple{FusionTreePair{I}, Index2Tuple{N₁, N₂}, Index2Tuple}
291-
const FSBBraidKey{I, N₁, N₂} = Tuple{FusionTreeBlock{I}, Index2Tuple{N₁, N₂}, Index2Tuple}
292-
293-
Base.@assume_effects :foldable function _fsdicttype(::Type{T}) where {I, N₁, N₂, T <: FSPBraidKey{I, N₁, N₂}}
294-
E = sectorscalartype(I)
295-
return Pair{fusiontreetype(I, N₁, N₂), E}
296-
end
297-
Base.@assume_effects :foldable function _fsdicttype(::Type{T}) where {I, N₁, N₂, T <: FSBBraidKey{I, N₁, N₂}}
298-
F₁ = fusiontreetype(I, N₁)
299-
F₂ = fusiontreetype(I, N₂)
300-
E = sectorscalartype(I)
301-
return Pair{FusionTreeBlock{I, N₁, N₂, Tuple{F₁, F₂}}, Matrix{E}}
290+
# Braiding can promote real fusion coefficients to complex values. Keep the result
291+
# type explicit so all braid paths remain inferred, including anyonic sectors.
292+
Base.@assume_effects :foldable function fsbraidtype(
293+
src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, ::Index2Tuple{N₁, N₂}
294+
) where {I, N₁, N₂}
295+
T = sectorscalartype(I)
296+
if src isa FusionTreePair
297+
return Pair{fusiontreetype(I, N₁, N₂), T}
298+
else
299+
F = Tuple{fusiontreetype(I, N₁), fusiontreetype(I, N₂)}
300+
return Pair{FusionTreeBlock{I, N₁, N₂, F}, Matrix{T}}
301+
end
302302
end
303303

304-
@cached function fsbraid(key::K)::_fsdicttype(K) where {I, N₁, N₂, K <: Union{FSPBraidKey{I, N₁, N₂}, FSBBraidKey{I, N₁, N₂}}}
305-
if K <: FSPBraidKey
306-
((f₁, f₂), (p1, p2), (l1, l2)) = key
307-
p = linearizepermutation(p1, p2, length(f₁), length(f₂))
304+
@cached function fsbraid(
305+
src::Union{FusionTreePair{I}, FusionTreeBlock{I}},
306+
p::Index2Tuple{N₁, N₂}, levels::Index2Tuple
307+
)::fsbraidtype(src, p) where {I, N₁, N₂}
308+
p1, p2 = p
309+
l1, l2 = levels
310+
if src isa FusionTreePair
311+
f₁, f₂ = src
312+
p′ = linearizepermutation(p1, p2, length(f₁), length(f₂))
308313
levels = (l1..., reverse(l2)...)
309314
(f, f0), coeff1 = repartition((f₁, f₂), N₁ + N₂)
310-
f′, coeff2 = braid(f, p, levels)
315+
f′, coeff2 = braid(f, p′, levels)
311316
(f₁′, f₂′), coeff3 = repartition((f′, f0), N₁)
312317
return (f₁′, f₂′) => coeff1 * coeff2 * coeff3
313318
else
314-
src, (p1, p2), (l1, l2) = key
315-
316-
p = linearizepermutation(p1, p2, numout(src), numin(src))
319+
p′ = linearizepermutation(p1, p2, numout(src), numin(src))
317320
levels = (l1..., reverse(l2)...)
318321

319322
dst, U = repartition(src, numind(src))
320323

321324
braid_style = BraidingStyle(I)
322-
for s in permutation2swaps(p)
325+
for s in permutation2swaps(p′)
323326
_check_levels(braid_style, levels, s)
324327
inv = levels[s] > levels[s + 1]
325328
dst, U_tmp = artin_braid(dst, s; inv)
@@ -339,7 +342,7 @@ end
339342
end
340343
end
341344

342-
CacheStyle(::typeof(fsbraid), k::Union{FSPBraidKey{I}, FSBBraidKey{I}}) where {I} =
345+
CacheStyle(::typeof(fsbraid), src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, args...) where {I} =
343346
FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache()
344347

345348
"""

‎src/fusiontrees/duality_manipulations.jl‎

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -524,25 +524,13 @@ function Base.transpose(src::Union{FusionTreePair, FusionTreeBlock}, p::Index2Tu
524524
N == length(p[1]) + length(p[2]) || throw(ArgumentError("invalid permutation p = $p of length N = $N"))
525525
p′ = linearizepermutation(p..., numout(src), numin(src))
526526
iscyclicpermutation(p′) || throw(ArgumentError("invalid cyclic or planar permutation p = $p"))
527-
return fstranspose((src, p))
527+
return fstranspose(src, p)
528528
end
529529

530-
const FSPTransposeKey{I, N₁, N₂} = Tuple{FusionTreePair{I}, Index2Tuple{N₁, N₂}}
531-
const FSBTransposeKey{I, N₁, N₂} = Tuple{FusionTreeBlock{I}, Index2Tuple{N₁, N₂}}
532-
533-
Base.@assume_effects :foldable function _fsdicttype(::Type{T}) where {I, N₁, N₂, T <: FSPTransposeKey{I, N₁, N₂}}
534-
E = fusionscalartype(I)
535-
return Pair{fusiontreetype(I, N₁, N₂), E}
536-
end
537-
Base.@assume_effects :foldable function _fsdicttype(::Type{T}) where {I, N₁, N₂, T <: FSBTransposeKey{I, N₁, N₂}}
538-
F₁ = fusiontreetype(I, N₁)
539-
F₂ = fusiontreetype(I, N₂)
540-
E = fusionscalartype(I)
541-
return Pair{FusionTreeBlock{I, N₁, N₂, Tuple{F₁, F₂}}, Matrix{E}}
542-
end
543-
544-
@cached function fstranspose(key::K)::_fsdicttype(K) where {I, N₁, N₂, K <: Union{FSPTransposeKey{I, N₁, N₂}, FSBTransposeKey{I, N₁, N₂}}}
545-
src, (p1, p2) = key
530+
@cached function fstranspose(
531+
src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, p::Index2Tuple{N₁, N₂}
532+
) where {I, N₁, N₂}
533+
p1, p2 = p
546534

547535
N = N₁ + N₂
548536
p = linearizepermutation(p1, p2, numout(src), numin(src))
@@ -567,9 +555,7 @@ end
567555
return dst => U
568556
end
569557

570-
CacheStyle(::typeof(fstranspose), k::FSPTransposeKey{I}) where {I} =
571-
FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache()
572-
CacheStyle(::typeof(fstranspose), k::FSBTransposeKey{I}) where {I} =
558+
CacheStyle(::typeof(fstranspose), src::Union{FusionTreePair{I}, FusionTreeBlock{I}}, args...) where {I} =
573559
FusionStyle(I) isa UniqueFusion ? NoCache() : GlobalCache()
574560

575561
# COMPOSITE DUALITY MANIPULATIONS PART 2: Planar traces

‎src/spaces/structure.jl‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ struct SectorStructure{I <: Sector, F <: FusionTreePair{I}}
2121
fusiontrees::Indices{F}
2222
end
2323

24-
Base.@assume_effects :foldable function sectorstructuretype(key::Hashed{S}) where {S <: HomSpace}
24+
Base.@assume_effects :foldable function sectorstructuretype(::S) where {S <: HomSpace}
2525
I = sectortype(S)
2626
F = fusiontreetype(I, numout(S), numin(S))
2727
return SectorStructure{I, F}
@@ -35,11 +35,8 @@ pairs as `Indices`. The result is cached based on the sector structure of `W` (i
3535
degeneracy dimensions).
3636
3737
See also [`degeneracystructure`](@ref), [`fusiontrees`](@ref), [`blocksectors`](@ref).
38-
""" sectorstructure(::HomSpace)
39-
sectorstructure(W::HomSpace) = sectorstructure(Hashed(W, sectorhash, sectorequal))
40-
41-
@cached function sectorstructure(key::Hashed{S})::sectorstructuretype(key) where {S <: HomSpace}
42-
W = parent(key)
38+
"""
39+
@cached function sectorstructure(W::S)::sectorstructuretype(W) where {S <: HomSpace}
4340
codom, dom = codomain(W), domain(W)
4441

4542
I = sectortype(S)
@@ -71,6 +68,8 @@ sectorstructure(W::HomSpace) = sectorstructure(Hashed(W, sectorhash, sectorequal
7168
return SectorStructure{I, F}(Indices(bs), Indices(trees))
7269
end
7370

71+
Cached.cachekey(::typeof(sectorstructure), W::HomSpace) = (Hashed(W, sectorhash, sectorequal),)
72+
7473
# DegeneracyStructure: degeneracy-dependent characterization of HomSpaces
7574
# -----------------------------------------------------------------------
7675
"""

‎test/other/caches.jl‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using Test, TestExtras
2+
using TensorKit
3+
using TensorKit: Cached, sectorstructure, degeneracystructure
4+
5+
@testset "Cached structure keys" begin
6+
V1 = SU2Space(0 => 2, 1 // 2 => 3)
7+
V2 = SU2Space(0 => 4, 1 // 2 => 1)
8+
W1, W2 = V1 ⊗ V1 ← V1, V2 ⊗ V2 ← V2
9+
empty_globalcaches!()
10+
s1 = @constinferred sectorstructure(W1)
11+
@test s1 === @constinferred sectorstructure(W2)
12+
fresh = Cached.uncached(sectorstructure, W1)
13+
@test s1.blocksectors == fresh.blocksectors
14+
@test s1.fusiontrees == fresh.fusiontrees
15+
@test parent(only(Cached.cachekey(sectorstructure, W1))) === W1
16+
@test length(only(Cached.cache_info(sectorstructure)).second) == 1
17+
@test (@constinferred degeneracystructure(W1)).totaldim !=
18+
(@constinferred degeneracystructure(W2)).totaldim
19+
@test length(only(Cached.cache_info(degeneracystructure)).second) == 2
20+
end
21+
22+
# A cache owned by another module must survive TensorKit's cache clearing.
23+
Cached.@cached unrelated_cache(x) = [x]
24+
25+
@testset "TensorKit cache management" begin
26+
retained = unrelated_cache(1)
27+
extra = Dict(:key => :value)
28+
push!(TensorKit.GLOBAL_CACHES, :extension_cache => extra)
29+
try
30+
V = SU2Space(0 => 2, 1 // 2 => 2)
31+
t = rand(V ⊗ V ← V ⊗ V)
32+
@test (@constinferred transpose(transpose(t))) ≈ t
33+
p = ((2, 1), (4, 3))
34+
@test (@constinferred permute(permute(t, p), p)) ≈ t
35+
info = sprint(TensorKit.global_cache_info)
36+
@test occursin("treebraider", info)
37+
@test occursin("extension_cache", info)
38+
@test empty_globalcaches!() === nothing
39+
@test all(isempty(cache) for (_, cache) in Cached.cache_info(TensorKit))
40+
@test isempty(extra)
41+
@test unrelated_cache(1) === retained
42+
finally
43+
pop!(TensorKit.GLOBAL_CACHES)
44+
Cached.empty_caches!(unrelated_cache)
45+
end
46+
end

‎test/other/hashed.jl‎

Lines changed: 0 additions & 48 deletions
This file was deleted.

0 commit comments

Comments
 (0)