Skip to content

Commit 1247e27

Browse files
lkdvosclaude
andcommitted
feat: add TimerOutputs-based timers for internal kernels
Instrument the index manipulation, tensor contraction and factorization kernels with `@timeit_debug` sections that are compiled away by default and can be enabled with `TensorKit.enable_timers!()`. Section labels carry a category prefix (`symmetry:` / `bookkeeping:` / `alloc:` / `dense:`), and `TensorKit.timer_summary()` aggregates the exclusive time of each section into per-category totals, to measure the split between fusion tree manipulations, block structure bookkeeping, allocations and the actual dense tensor kernels. The `@cached` macro additionally times cache lookups separately from miss-path construction for all memoized functions. While timers are enabled, `taskforeach` regions run serially since a `TimerOutput` may only be manipulated from a single task; the guard const-folds away when timers are disabled, leaving the production paths unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent b909280 commit 1247e27

16 files changed

Lines changed: 637 additions & 234 deletions

File tree

‎Project.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ ScopedValues = "7e506255-f358-4e82-b7e4-beb19740aa63"
1919
Strided = "5e0ebb24-38b0-5f93-81fe-25c709ecae67"
2020
TensorKitSectors = "13a9c161-d5da-41f0-bcbd-e1a08ae0647f"
2121
TensorOperations = "6aa20fa7-93e2-5fca-9bc0-fbd0db3c71a2"
22+
TimerOutputs = "a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f"
2223
TupleTools = "9d95972d-f1c8-5527-a6e0-b4b365fa01f6"
2324
VectorInterface = "409d34a3-91d5-4945-b6ec-7529ddf182d8"
2425

@@ -63,6 +64,7 @@ ScopedValues = "1.3.0"
6364
Strided = "2.6.1"
6465
TensorKitSectors = "0.3.7"
6566
TensorOperations = "5.5.2, 5.6"
67+
TimerOutputs = "1"
6668
TupleTools = "1.5"
6769
VectorInterface = "0.6"
6870
julia = "1.10"

‎benchmark/README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,12 @@ benchpkgtable TensorKit \
2929
-i benchmark/results/ \
3030
-o benchmark/results/ \
3131
```
32+
33+
## Timing internal kernels
34+
35+
To break down where time is spent *inside* the operations (symmetry work, bookkeeping,
36+
allocations, dense kernels), TensorKit ships built-in
37+
[TimerOutputs.jl](https://github.com/KristofferC/TimerOutputs.jl) instrumentation that is
38+
compiled away by default and can be enabled with `TensorKit.enable_timers!()`. See the
39+
"Profiling and timers" section of the documentation for the workflow and caveats.
40+

‎docs/make.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ pages = [
3434
"man/factorizations.md",
3535
"man/contractions.md",
3636
],
37+
"man/profiling.md",
3738
],
3839
"Library" => [
3940
"lib/sectors.md", "lib/fusiontrees.md",

‎docs/src/man/profiling.md‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# [Profiling and timers](@id s_profiling)
2+
3+
TensorKit's index manipulations, tensor contractions and factorizations are instrumented with [TimerOutputs.jl](https://github.com/KristofferC/TimerOutputs.jl) sections that are compiled away by default, so they incur no runtime cost.
4+
They can be enabled to obtain a detailed breakdown of where time is spent inside these operations, in particular the split between the different kinds of work involved in manipulating symmetric tensors:
5+
6+
| category | contents |
7+
|:---|:---|
8+
| `symmetry` | fusion tree manipulations and recoupling coefficients (braiding, transposing, F- and R-symbols) |
9+
| `bookkeeping` | block structure computations, cache lookups, contraction planning |
10+
| `alloc` | allocation of output tensors and temporary buffers |
11+
| `dense` | dense tensor kernels (BLAS/LAPACK calls, strided permutations and additions) |
12+
| `other` | remaining time within an instrumented operation (dispatch, argument checking, uncovered overhead) |
13+
14+
The canonical workflow looks as follows:
15+
16+
```julia
17+
using TensorKit
18+
19+
TensorKit.enable_timers!() # triggers recompilation of the instrumented methods
20+
21+
# warm up first, so that compilation does not pollute the timings
22+
V = SU2Space(0 => 4, 1//2 => 4, 1 => 2)
23+
t = rand(V ⊗ V ← V ⊗ V)
24+
permute(t, ((1, 3), (2, 4)))
25+
@tensor t2[a b; c d] := t[a x; c y] * t[y b; x d]
26+
svd_compact(t)
27+
28+
TensorKit.reset_timers!()
29+
# ... run the workload of interest ...
30+
TensorKit.print_timers() # full nested call tree
31+
TensorKit.timer_summary() # symmetry / bookkeeping / alloc / dense / other totals
32+
33+
TensorKit.disable_timers!()
34+
```
35+
36+
[`TensorKit.print_timers`](@ref) displays the accumulated timings as a nested call tree, with sections for the top-level operations (`"permute!"`, `"contract!"`, `"svd_compact!"`, ...) and nested sections labeled by their category prefix (`"symmetry: ..."`, `"bookkeeping: ..."`, `"alloc: ..."`, `"dense: ..."`).
37+
[`TensorKit.timer_summary`](@ref) aggregates the *exclusive* time of each section (its own time minus that of its timed children) into per-category totals, such that every nanosecond is counted exactly once and the totals sum to the total measured time.
38+
39+
A few caveats to keep in mind:
40+
41+
* Enabling or disabling the timers redefines internal functions, so instrumented methods recompile on first use afterwards.
42+
This is a debug-session switch, not a runtime option.
43+
* While timers are enabled, TensorKit-internal task parallelism is disabled, since the timer object may only be manipulated from a single task.
44+
As a consequence, multi-threaded speedups are not measurable while timing, and TensorKit functions should not be called concurrently from multiple user tasks.
45+
* Each section entry costs roughly 100–200 ns, which can distort measurements of workloads on very small tensors.
46+
* The construction of fusion tree transformers and block structures is cached (see `empty_globalcaches!`), so their cost only shows up the first time a given structure is encountered.
47+
Call `TensorKit.empty_globalcaches!()` before the measurement if you want the construction cost to be included, or after the warm-up if you want to measure the steady-state behavior with warm caches.
48+
* For GPU tensors, the timings only reflect host-side dispatch of asynchronous kernels, unless the workload is explicitly synchronized.
49+
50+
## Library documentation
51+
52+
```@docs
53+
TensorKit.GLOBAL_TIMER
54+
TensorKit.enable_timers!
55+
TensorKit.disable_timers!
56+
TensorKit.reset_timers!
57+
TensorKit.print_timers
58+
TensorKit.timer_summary
59+
TensorKit.timer
60+
TensorKit.timers_enabled
61+
```

‎src/TensorKit.jl‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ using Dictionaries: Dictionaries, Dictionary, Indices, gettoken, gettokenvalue
123123
using LRUCache
124124
using OhMyThreads
125125
using ScopedValues
126+
using TimerOutputs: TimerOutputs, TimerOutput, @timeit_debug
126127

127128
using TensorKitSectors
128129
import TensorKitSectors: dim, BraidingStyle, FusionStyle, ⊠, ⊗, ×
@@ -134,7 +135,7 @@ using Base: @boundscheck, @propagate_inbounds, @constprop,
134135
tuple_type_head, tuple_type_tail, tuple_type_cons,
135136
SizeUnknown, HasLength, HasShape, IsInfinite, EltypeUnknown, HasEltype
136137
using Base.Iterators: product, filter
137-
using Printf: @sprintf
138+
using Printf: @sprintf, @printf
138139

139140
using LinearAlgebra: LinearAlgebra, BlasFloat
140141
using LinearAlgebra: norm, dot, normalize, normalize!, tr,
@@ -153,6 +154,7 @@ using Adapt: Adapt
153154

154155
# Auxiliary files
155156
#-----------------
157+
include("auxiliary/timers.jl")
156158
include("auxiliary/auxiliary.jl")
157159
include("auxiliary/caches.jl")
158160
include("auxiliary/dicts.jl")
@@ -225,7 +227,8 @@ include("spaces/structure.jl")
225227
#-------------------------
226228
const TRANSFORMER_THREADS = Ref(1)
227229

228-
get_num_transformer_threads() = TRANSFORMER_THREADS[]
230+
# while timing, force serial execution: timer sections may only be entered from one task
231+
get_num_transformer_threads() = timers_enabled() ? 1 : TRANSFORMER_THREADS[]
229232

230233
function set_num_transformer_threads(n::Int)
231234
N = Base.Threads.nthreads()
@@ -238,7 +241,7 @@ end
238241

239242
const TREEMANIPULATION_THREADS = Ref(1)
240243

241-
get_num_manipulation_threads() = TREEMANIPULATION_THREADS[]
244+
get_num_manipulation_threads() = timers_enabled() ? 1 : TREEMANIPULATION_THREADS[]
242245

243246
function set_num_manipulation_threads(n::Int)
244247
N = Base.Threads.nthreads()

‎src/auxiliary/caches.jl‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ macro cached(ex)
6969
Meta.isexpr(fcall, :call) ||
7070
error("cached macro can only be used on function definitions")
7171
fname = fcall.args[1]
72+
# timer labels for the cache lookup and the miss-path construction
73+
lookuplabel = string("bookkeeping: cache ", fname)
74+
misslabel = string(_cached_category(fname), ": compute ", fname)
7275
fargs = fcall.args[2:end]
7376
fargnames = map(fargs) do arg
7477
if Meta.isexpr(arg, :(::))
@@ -106,7 +109,7 @@ macro cached(ex)
106109
if hasparams
107110
fnocachecall = Expr(:where, fnocachecall, params...)
108111
end
109-
fnocachebody = Expr(:call, _fname, fargnames...)
112+
fnocachebody = :(@timeit_debug GLOBAL_TIMER $misslabel $(Expr(:call, _fname, fargnames...)))
110113
if typed
111114
T = gensym(:T)
112115
fnocachebody = Expr(:block, Expr(:(=), T, typeex), Expr(:(::), fnocachebody, T))
@@ -135,8 +138,8 @@ macro cached(ex)
135138
key = Expr(:tuple, fargnames...)
136139
end
137140
getvalex = :(
138-
get!($cachevar, $key) do
139-
return $_fname($(fargnames...))
141+
@timeit_debug GLOBAL_TIMER $lookuplabel get!($cachevar, $key) do
142+
return @timeit_debug GLOBAL_TIMER $misslabel $_fname($(fargnames...))
140143
end
141144
)
142145
if typed

‎src/auxiliary/timers.jl‎

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
# define the `@timeit_debug` switch explicitly (instead of letting the first macro
2+
# expansion do it) so that ordinary code can branch on it, see `timers_enabled`
3+
timeit_debug_enabled() = false
4+
5+
"""
6+
TensorKit.GLOBAL_TIMER
7+
8+
The global `TimerOutput` object into which all timer sections of TensorKit accumulate.
9+
See [`enable_timers!`](@ref) for how to activate them, [`print_timers`](@ref) for
10+
displaying the resulting call tree and [`timer_summary`](@ref) for aggregating it into
11+
per-category totals.
12+
"""
13+
const GLOBAL_TIMER = TimerOutput("TensorKit")
14+
15+
"""
16+
TensorKit.timer() -> TimerOutputs.TimerOutput
17+
18+
Return the global timer object [`GLOBAL_TIMER`](@ref) into which all TensorKit timer
19+
sections accumulate.
20+
"""
21+
timer() = GLOBAL_TIMER
22+
23+
"""
24+
TensorKit.timers_enabled() -> Bool
25+
26+
Return whether the `@timeit_debug` timer sections of TensorKit are currently compiled in,
27+
i.e. whether [`enable_timers!`](@ref) has been called.
28+
29+
This is used internally to force serial execution of parallel regions while timing, since
30+
a `TimerOutput` may only be manipulated from a single task. When timers are disabled this
31+
check const-folds to `false`, so it has no runtime cost.
32+
"""
33+
timers_enabled() = timeit_debug_enabled()
34+
35+
"""
36+
TensorKit.enable_timers!()
37+
38+
Enable all timer sections of TensorKit (including its submodules), which accumulate
39+
timings of the internal kernels into [`GLOBAL_TIMER`](@ref). Undone by
40+
[`disable_timers!`](@ref).
41+
42+
!!! warning
43+
Enabling or disabling timers redefines internal functions and therefore triggers
44+
recompilation of the instrumented methods on first use. This is a debug-session
45+
operation, not a runtime switch.
46+
47+
!!! warning
48+
While timers are enabled, TensorKit-internal task parallelism is disabled (threaded
49+
regions run serially), so multi-threaded speedups are not measurable. Additionally,
50+
TensorKit functions should not be called concurrently from multiple user tasks while
51+
timing, as the timer object is not thread-safe.
52+
53+
Note that each timer section adds an overhead of roughly 100-200 ns per entry, which can
54+
distort measurements of very small workloads. For GPU tensors, timings only reflect
55+
host-side dispatch of asynchronous kernels unless the workload is explicitly synchronized.
56+
"""
57+
function enable_timers!()
58+
TimerOutputs.enable_debug_timings(TensorKit)
59+
return nothing
60+
end
61+
62+
"""
63+
TensorKit.disable_timers!()
64+
65+
Disable all timer sections of TensorKit again; the inverse of [`enable_timers!`](@ref).
66+
Also triggers recompilation of the instrumented methods on first use.
67+
"""
68+
function disable_timers!()
69+
TimerOutputs.disable_debug_timings(TensorKit)
70+
return nothing
71+
end
72+
73+
"""
74+
TensorKit.reset_timers!()
75+
76+
Reset the accumulated timings in [`GLOBAL_TIMER`](@ref).
77+
"""
78+
function reset_timers!()
79+
TimerOutputs.reset_timer!(GLOBAL_TIMER)
80+
return nothing
81+
end
82+
83+
"""
84+
TensorKit.print_timers(io::IO = stdout; kwargs...)
85+
86+
Print the accumulated timings in [`GLOBAL_TIMER`](@ref) as a nested table. Keyword
87+
arguments are forwarded to `TimerOutputs.print_timer`.
88+
"""
89+
print_timers(io::IO = stdout; kwargs...) = TimerOutputs.print_timer(io, GLOBAL_TIMER; kwargs...)
90+
91+
const TIMER_CATEGORIES = (:symmetry, :bookkeeping, :alloc, :dense, :other)
92+
93+
# "symmetry: recoupling" -> :symmetry; unprefixed or unknown prefix -> nothing
94+
function _timer_category(label::String)
95+
i = findfirst(':', label)
96+
i === nothing && return nothing
97+
prefix = Symbol(label[1:prevind(label, i)])
98+
return prefix in TIMER_CATEGORIES ? prefix : nothing
99+
end
100+
101+
# category of the miss-path (construction) section of an `@cached` function
102+
function _cached_category(fname::Symbol)
103+
return fname in (:fsbraid, :fstranspose, :treebraider, :treetransposer) ?
104+
"symmetry" : "bookkeeping"
105+
end
106+
107+
const TimerSummary = Dict{Symbol, @NamedTuple{time::Int64, allocated::Int64, ncalls::Int64}}
108+
109+
"""
110+
TensorKit.timer_summary([io::IO]; to = GLOBAL_TIMER)
111+
-> Dict{Symbol, @NamedTuple{time::Int64, allocated::Int64, ncalls::Int64}}
112+
113+
Aggregate the timer tree into per-category totals (time in ns, allocated bytes, number of
114+
section entries) for the categories `$(TIMER_CATEGORIES)`.
115+
116+
Each section's *exclusive* time (its own time minus that of its timed children) is
117+
attributed to the category given by its label prefix or, for unprefixed labels, to the
118+
category of the nearest categorized ancestor (`:other` at the root). Every nanosecond is
119+
thus counted exactly once and the totals sum to the total measured time.
120+
121+
When `io` is given (default `stdout`), a small table is printed; pass `nothing` to skip
122+
printing and only return the totals.
123+
"""
124+
function timer_summary(io::Union{IO, Nothing} = stdout; to::TimerOutput = GLOBAL_TIMER)
125+
totals = TimerSummary(c => (time = 0, allocated = 0, ncalls = 0) for c in TIMER_CATEGORIES)
126+
for child in to.root.children
127+
_accumulate_summary!(totals, child, :other)
128+
end
129+
io === nothing || _print_timer_summary(io, totals)
130+
return totals
131+
end
132+
133+
function _accumulate_summary!(totals::TimerSummary, s, inherited::Symbol)
134+
cat = something(_timer_category(s.name), inherited)
135+
t = TimerOutputs.time(s)
136+
b = TimerOutputs.allocated(s)
137+
for child in s.children
138+
t -= TimerOutputs.time(child)
139+
b -= TimerOutputs.allocated(child)
140+
_accumulate_summary!(totals, child, cat)
141+
end
142+
old = totals[cat]
143+
totals[cat] = (
144+
time = old.time + max(t, 0), allocated = old.allocated + max(b, 0),
145+
ncalls = old.ncalls + TimerOutputs.ncalls(s),
146+
)
147+
return nothing
148+
end
149+
150+
function _print_timer_summary(io::IO, totals::TimerSummary)
151+
total_time = sum(x -> x.time, values(totals))
152+
println(io, "TensorKit timer summary:")
153+
for cat in TIMER_CATEGORIES
154+
(; time, allocated, ncalls) = totals[cat]
155+
percentage = total_time == 0 ? 0.0 : 100 * time / total_time
156+
@printf(
157+
io, "%12s: %s (%5.1f%%) %s %d sections\n",
158+
cat, TimerOutputs.prettytime(time), percentage,
159+
TimerOutputs.prettymemory(allocated), ncalls
160+
)
161+
end
162+
return nothing
163+
end

‎src/factorizations/factorizations.jl‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ using ..TensorKit
99
using ..TensorKit: AdjointTensorMap, SectorDict, SectorVector,
1010
blocktype, foreachblock, one!,
1111
similar_diagonal, similarstoragetype
12+
using ..TensorKit: GLOBAL_TIMER
13+
using TimerOutputs: @timeit_debug
1214

1315
using LinearAlgebra: LinearAlgebra, BlasFloat, Diagonal,
1416
svdvals, svdvals!, eigen, eigen!,

0 commit comments

Comments
 (0)