Skip to content

Commit 85dc10d

Browse files
lkdvosclaude
andcommitted
Add a TBLIS.jl package extension
Adds `TBLISBackend`, which routes `tensoradd!`, `tensortrace!` and `tensorcontract!` through the TBLIS library via TBLIS.jl. TBLIS contracts strided tensors in place, so it avoids the permuted intermediates that the BLAS-based backend has to materialize. The backend is opt-in: loading TBLIS.jl does not register a `select_backend` method. Arguments TBLIS cannot express, that is mixed or unsupported element types, non-strided arrays and conjugated outputs, throw an `ArgumentError` rather than being handed to another backend, so that a contraction which never reaches TBLIS cannot pass for one that did. Conjugation is carried as an ordinary runtime flag on the `TBLISTensor` descriptor rather than in the type of a `StridedView`, which keeps the entry points type stable without branching over `conj` variants. A conjugation already present on the input, as for an `Adjoint`, combines with the requested one. Two library quirks are worked around: * `tblis_tensor_mult` ignores the per-tensor conjugation flags, unlike `tblis_tensor_add`. When both factors are conjugated this is resolved by conjugating the output in place, and otherwise by materializing the conjugated factor into a temporary from the allocator. * TBLIS.jl only exposes its tensor constructor for `StridedArray` and offers no way to set the conjugation flag, so the descriptor is initialized through the low-level bindings and every referenced buffer is rooted with `GC.@preserve`. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 58c6e03 commit 85dc10d

6 files changed

Lines changed: 595 additions & 2 deletions

File tree

‎Project.toml‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,14 @@ cuTENSOR = "011b41b2-24ef-40a8-b3eb-fa098493e9e1"
2525
Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9"
2626
JLArrays = "27aeb0d3-9eb9-45fb-866b-73c2ecf80fcb"
2727
Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6"
28+
TBLIS = "48530278-0828-4a49-9772-0f3830dfa1e9"
2829

2930
[extensions]
3031
TensorOperationsAMDGPUExt = "AMDGPU"
3132
TensorOperationsBumperExt = "Bumper"
3233
TensorOperationsChainRulesCoreExt = "ChainRulesCore"
3334
TensorOperationsMooncakeExt = "Mooncake"
35+
TensorOperationsTBLISExt = "TBLIS"
3436
TensorOperationsCUDACoreExt = "CUDACore"
3537
TensorOperationsEnzymeExt = "Enzyme"
3638
TensorOperationscuTENSORExt = "cuTENSOR"
@@ -59,6 +61,7 @@ PtrArrays = "1.2"
5961
Random = "1"
6062
Strided = "2.6"
6163
StridedViews = "0.5"
64+
TBLIS = "0.3"
6265
Test = "1"
6366
TupleTools = "1.6"
6467
VectorInterface = "0.4.1, 0.5, 0.6"
@@ -81,8 +84,9 @@ JLArrays = "27aeb0d3-9eb9-45fb-866b-73c2ecf80fcb"
8184
Logging = "56ddb016-857b-54e1-b83d-db4d58db5568"
8285
Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6"
8386
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
87+
TBLIS = "48530278-0828-4a49-9772-0f3830dfa1e9"
8488
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
8589
cuTENSOR = "011b41b2-24ef-40a8-b3eb-fa098493e9e1"
8690

8791
[targets]
88-
test = ["Test", "Random", "DynamicPolynomials", "ChainRulesTestUtils", "ChainRulesCore", "cuRAND", "CUDACore", "cuTENSOR", "Aqua", "Logging", "Bumper", "Mooncake", "Enzyme", "EnzymeTestUtils", "Adapt", "JLArrays", "AMDGPU"]
92+
test = ["Test", "Random", "DynamicPolynomials", "ChainRulesTestUtils", "ChainRulesCore", "cuRAND", "CUDACore", "cuTENSOR", "Aqua", "Logging", "Bumper", "Mooncake", "Enzyme", "EnzymeTestUtils", "Adapt", "JLArrays", "AMDGPU", "TBLIS"]

‎docs/src/man/backends.md‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ TensorOperations.BaseCopy
6464
TensorOperations.BaseView
6565
TensorOperations.StridedNative
6666
TensorOperations.StridedBLAS
67+
TensorOperations.TBLISBackend
6768
TensorOperations.cuTENSORBackend
6869
```
6970

@@ -74,6 +75,26 @@ On the other hand, the `BaseCopy` and `BaseView` backends are used for arrays th
7475
These are designed to be as general as possible, and as a result are not as performant as specific implementations.
7576
Nevertheless, they can be useful for debugging purposes or for working with custom tensor types that have limited support for methods outside of `Base`.
7677

78+
The `TBLISBackend` routes the primitive operations through the [TBLIS](https://github.com/devinamatthews/tblis) library.
79+
TBLIS contracts strided tensors in place instead of reshaping them into matrices, and can therefore avoid the intermediate permuted copies that `StridedBLAS` sometimes has to allocate.
80+
It is opt-in, in the sense that loading `TBLIS.jl` does not change the default backend selection, and it is only available through a package extension for [`TBLIS.jl`](https://github.com/QuantumKitHub/TBLIS.jl):
81+
82+
```julia
83+
using TensorOperations, TBLIS
84+
TBLIS.set_num_threads(8)
85+
@tensor backend = TensorOperations.TBLISBackend() D[a, b, c, d] := A[a, e, c, f] * B[g, d, e] * conj(C[g, f, b])
86+
```
87+
88+
TBLIS requires all tensors in a single operation to share one element type out of `Float32`, `Float64`, `ComplexF32` and `ComplexF64`.
89+
Arguments that do not satisfy this, as well as non-strided arrays, are rejected with an `ArgumentError` instead of being passed on to another backend, so that a contraction which cannot actually reach TBLIS is not silently run somewhere else.
90+
91+
Note that contracting in place trades throughput for memory rather than being a free win.
92+
With BLAS, TBLIS and `Strided.jl` all given the same number of threads, this backend is roughly on par with `StridedBLAS` for permuted real contractions and slower for other shapes, while allocating no permuted temporaries at all.
93+
94+
!!! warning
95+
As of `tblis_jll` v1.3, TBLIS has no competitive support for complex element types.
96+
Its complex contraction kernels run an order of magnitude slower than the corresponding BLAS calls, so `StridedBLAS` is the better choice for complex-valued contractions.
97+
7798
Finally, we also provide a `cuTENSORBackend` for use with the `cuTENSOR.jl` library, which is a NVidia GPU-accelerated tensor contraction library.
7899
This backend is only available through a package extension for `cuTENSOR`.
79100

@@ -89,7 +110,7 @@ Users can also define their own backends, to facilitate experimentation with new
89110
This can be done by defining a new type that is a subtype of `AbstractBackend`, and dispatching on this type in the implementation of the primitive tensor operations.
90111
In particular, the only required implemented methods are [`tensoradd!`](@ref), [`tensortrace!`](@ref), [`tensorcontract!`](@ref).
91112

92-
For example, [`TensorOperationsTBLIS`](https://github.com/lkdvos/TensorOperationsTBLIS.jl) is a wrapper that provides a backend for tensor contractions using the [TBLIS](https://github.com/devinamatthews/tblis) library.
113+
For example, the `TBLISBackend` above is implemented in exactly this way, as a package extension that only adds methods for these three functions.
93114

94115
## Allocators
95116

‎ext/TensorOperationsTBLISExt.jl‎

Lines changed: 288 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,288 @@
1+
module TensorOperationsTBLISExt
2+
3+
using TensorOperations
4+
using TensorOperations: TensorOperations as TO
5+
using TensorOperations: TBLISBackend, DefaultAllocator, Index2Tuple
6+
using TensorOperations: StridedView, isstrided
7+
using TensorOperations: argcheck_tensoradd, dimcheck_tensoradd,
8+
argcheck_tensortrace, dimcheck_tensortrace,
9+
argcheck_tensorcontract, dimcheck_tensorcontract
10+
using TensorOperations: add_labels, trace_labels, contract_labels
11+
using TensorOperations: tensoralloc_add, tensorfree!
12+
13+
using TBLIS
14+
using TBLIS: len_type, stride_type, tblis_tensor
15+
16+
const SV = StridedView
17+
18+
# TBLIS only knows about these four element types, and requires all tensors taking part in a
19+
# single operation to share it.
20+
const TBLISFloat = Union{Float32, Float64, ComplexF32, ComplexF64}
21+
22+
#-------------------------------------------------------------------------------------------
23+
# Wrapping Julia arrays as TBLIS tensors
24+
#-------------------------------------------------------------------------------------------
25+
# TBLIS.jl's own `tblis_tensor` constructor is restricted to `StridedArray`, which excludes
26+
# the `StridedView`s that the tensor operations work with, and it has no way to express the
27+
# conjugation flag. We therefore initialize the descriptor through the low-level bindings and
28+
# patch in the flag afterwards.
29+
for (T, init) in (
30+
(:Float32, :tblis_init_tensor_scaled_s),
31+
(:Float64, :tblis_init_tensor_scaled_d),
32+
(:ComplexF32, :tblis_init_tensor_scaled_c),
33+
(:ComplexF64, :tblis_init_tensor_scaled_z),
34+
)
35+
@eval function init_tensor!(
36+
p::Ptr{tblis_tensor}, A::StridedView{$T, N}, α::$T,
37+
len::Vector{len_type}, stride::Vector{stride_type}
38+
) where {N}
39+
return TBLIS.$init(p, α, Cuint(N), pointer(len), pointer(A), pointer(stride))
40+
end
41+
end
42+
43+
"""
44+
TBLISTensor(A::StridedView, α, isconj)
45+
46+
Owning counterpart of `TBLIS.tblis_tensor`, which itself only stores raw pointers into the
47+
array it views and into the buffers holding its lengths and strides.
48+
Rooting a `TBLISTensor` with `GC.@preserve` also roots all of those, as they are reachable
49+
from it; pass its `ref` field wherever the library expects a `Ptr{tblis_tensor}`.
50+
51+
Conjugation is carried in the descriptor rather than in the type of the viewed array, so
52+
`isconj` is an ordinary runtime flag and callers never have to branch on it to stay type
53+
stable.
54+
"""
55+
struct TBLISTensor{T, N, A <: StridedView{T, N}}
56+
array::A
57+
len::Vector{len_type}
58+
stride::Vector{stride_type}
59+
ref::Base.RefValue{tblis_tensor}
60+
end
61+
62+
function TBLISTensor(
63+
A::StridedView{T, N}, α::T, isconj::Bool
64+
) where {T <: TBLISFloat, N}
65+
len = collect(len_type, size(A))
66+
stride = collect(stride_type, strides(A))
67+
ref = Ref{tblis_tensor}()
68+
GC.@preserve A len stride ref begin
69+
p = Base.unsafe_convert(Ptr{tblis_tensor}, ref)
70+
init_tensor!(p, A, α, len, stride)
71+
isconj && setproperty!(p, :conj, Cint(1))
72+
end
73+
return TBLISTensor{T, N, typeof(A)}(A, len, stride, ref)
74+
end
75+
76+
# A `StridedView` may already carry a conjugation in its `op` field, for instance when it
77+
# views an `Adjoint`. What TBLIS needs is the total conjugation applied to the raw data, so
78+
# that flag and the one requested by the caller combine. For real element types `conj` is the
79+
# identity and flagging it would only confuse the library.
80+
hasconj(A::StridedView{T}) where {T} = T <: Complex && (A.op === conj || A.op === adjoint)
81+
resolve_conj(A::StridedView{T}, conjA::Bool) where {T} =
82+
T <: Complex && (conjA ⊻ hasconj(A))
83+
84+
# TBLIS takes the index labels as one `char` per dimension; `add_labels` and friends hand us
85+
# `Char` tuples that are guaranteed to be ASCII.
86+
labels(ein::Tuple{Vararg{Char}}) = String(UInt8[c for c in ein])
87+
88+
#-------------------------------------------------------------------------------------------
89+
# Argument checking
90+
#-------------------------------------------------------------------------------------------
91+
# Rather than quietly handing unsupported arguments to another backend, which would make a
92+
# `backend = TBLISBackend()` that never reaches TBLIS look like it did, reject them.
93+
@noinline function throw_eltype(f, tensors)
94+
types = join(eltype.(tensors), ", ")
95+
return throw(
96+
ArgumentError(
97+
"TBLISBackend requires all tensors of $f to share a single element type out of \
98+
Float32, Float64, ComplexF32 and ComplexF64, got $types"
99+
)
100+
)
101+
end
102+
103+
@noinline function throw_strided(f, tensors)
104+
types = join(typeof.(tensors), ", ")
105+
return throw(
106+
ArgumentError("TBLISBackend requires strided arrays for $f, got $types")
107+
)
108+
end
109+
110+
@noinline throw_conj_output(f) = throw(
111+
ArgumentError("TBLISBackend cannot write into a conjugated view in $f")
112+
)
113+
114+
function check_arguments(f, C::AbstractArray, As::AbstractArray...)
115+
tensors = (C, As...)
116+
T = eltype(C)
117+
(T <: TBLISFloat && all(A -> eltype(A) === T, As)) || throw_eltype(f, tensors)
118+
all(isstrided, tensors) || throw_strided(f, tensors)
119+
hasconj(SV(C)) && throw_conj_output(f)
120+
return nothing
121+
end
122+
123+
#-------------------------------------------------------------------------------------------
124+
# Entry points
125+
#-------------------------------------------------------------------------------------------
126+
function TO.tensoradd!(
127+
C::AbstractArray,
128+
A::AbstractArray, pA::Index2Tuple, conjA::Bool,
129+
α::Number, β::Number,
130+
backend::TBLISBackend, allocator = DefaultAllocator()
131+
)
132+
check_arguments(TO.tensoradd!, C, A)
133+
tblis_add!(SV(C), SV(A), conjA, pA, α, β)
134+
return C
135+
end
136+
137+
function TO.tensortrace!(
138+
C::AbstractArray,
139+
A::AbstractArray, p::Index2Tuple, q::Index2Tuple, conjA::Bool,
140+
α::Number, β::Number,
141+
backend::TBLISBackend, allocator = DefaultAllocator()
142+
)
143+
check_arguments(TO.tensortrace!, C, A)
144+
tblis_trace!(SV(C), SV(A), conjA, p, q, α, β)
145+
return C
146+
end
147+
148+
function TO.tensorcontract!(
149+
C::AbstractArray,
150+
A::AbstractArray, pA::Index2Tuple, conjA::Bool,
151+
B::AbstractArray, pB::Index2Tuple, conjB::Bool,
152+
pAB::Index2Tuple,
153+
α::Number, β::Number,
154+
backend::TBLISBackend, allocator = DefaultAllocator()
155+
)
156+
check_arguments(TO.tensorcontract!, C, A, B)
157+
tblis_contract!(SV(C), SV(A), pA, conjA, SV(B), pB, conjB, pAB, α, β, allocator)
158+
return C
159+
end
160+
161+
#-------------------------------------------------------------------------------------------
162+
# StridedView implementation
163+
#-------------------------------------------------------------------------------------------
164+
# `tblis_tensor_add` computes `C[einC] = β * C[einC] + α * op(A)[einA]` and does honour the
165+
# per-tensor conjugation flag. Labels repeated within `einA` but absent from `einC` are
166+
# traced over, so both `tensoradd!` and `tensortrace!` map onto it directly.
167+
function tblis_add!(
168+
C::StridedView{T}, A::StridedView{T}, conjA::Bool, pA::Index2Tuple,
169+
α::Number, β::Number
170+
) where {T <: TBLISFloat}
171+
argcheck_tensoradd(C, A, pA)
172+
dimcheck_tensoradd(C, A, pA)
173+
Base.mightalias(C, A) &&
174+
throw(ArgumentError("output tensor must not be aliased with input tensor"))
175+
176+
einA, einC = add_labels(pA)
177+
return unsafe_add!(
178+
C, A, resolve_conj(A, conjA), einA, einC, convert(T, α), convert(T, β)
179+
)
180+
end
181+
182+
function tblis_trace!(
183+
C::StridedView{T}, A::StridedView{T}, conjA::Bool,
184+
p::Index2Tuple, q::Index2Tuple, α::Number, β::Number
185+
) where {T <: TBLISFloat}
186+
argcheck_tensortrace(C, A, p, q)
187+
dimcheck_tensortrace(C, A, p, q)
188+
Base.mightalias(C, A) &&
189+
throw(ArgumentError("output tensor must not be aliased with input tensor"))
190+
191+
einA, einC = trace_labels(p, q)
192+
return unsafe_add!(
193+
C, A, resolve_conj(A, conjA), einA, einC, convert(T, α), convert(T, β)
194+
)
195+
end
196+
197+
# `isconjA` is the total conjugation to apply to the raw data of `A`, as resolved by
198+
# `resolve_conj`.
199+
function unsafe_add!(
200+
C::StridedView{T}, A::StridedView{T}, isconjA::Bool, einA, einC, α::T, β::T
201+
) where {T <: TBLISFloat}
202+
tA = TBLISTensor(A, α, isconjA)
203+
tC = TBLISTensor(C, β, false)
204+
GC.@preserve tA tC begin
205+
TBLIS.tblis_tensor_add(
206+
C_NULL, C_NULL, tA.ref, labels(einA), tC.ref, labels(einC)
207+
)
208+
end
209+
return C
210+
end
211+
212+
function tblis_contract!(
213+
C::StridedView{T},
214+
A::StridedView{T}, pA::Index2Tuple, conjA::Bool,
215+
B::StridedView{T}, pB::Index2Tuple, conjB::Bool,
216+
pAB::Index2Tuple,
217+
α::Number, β::Number, allocator
218+
) where {T <: TBLISFloat}
219+
argcheck_tensorcontract(C, A, pA, B, pB, pAB)
220+
dimcheck_tensorcontract(C, A, pA, B, pB, pAB)
221+
(Base.mightalias(C, A) || Base.mightalias(C, B)) &&
222+
throw(ArgumentError("output tensor must not be aliased with input tensor"))
223+
224+
einA, einB, einC = contract_labels(pA, pB, pAB)
225+
α′ = convert(T, α)
226+
β′ = convert(T, β)
227+
isconjA = resolve_conj(A, conjA)
228+
isconjB = resolve_conj(B, conjB)
229+
230+
# `tblis_tensor_mult` silently ignores the conjugation flags of its arguments (verified
231+
# against tblis 1.3), so conjugation has to be resolved before calling into it.
232+
if isconjA && isconjB
233+
# conj(A) * conj(B) == conj(A * B), so conjugating the output in place lets both
234+
# factors through unconjugated, at the cost of two passes over C. That is much
235+
# cheaper than materializing a conjugated copy of both A and B.
236+
iszero(β′) || conj!(C)
237+
unsafe_mult!(C, A, B, einA, einB, einC, conj(α′), conj(β′))
238+
conj!(C)
239+
elseif isconjA
240+
A′ = materialize_conj(A, α′, allocator)
241+
try
242+
unsafe_mult!(C, SV(A′), B, einA, einB, einC, one(T), β′)
243+
finally
244+
tensorfree!(A′, allocator)
245+
end
246+
elseif isconjB
247+
B′ = materialize_conj(B, one(T), allocator)
248+
try
249+
unsafe_mult!(C, A, SV(B′), einA, einB, einC, α′, β′)
250+
finally
251+
tensorfree!(B′, allocator)
252+
end
253+
else
254+
unsafe_mult!(C, A, B, einA, einB, einC, α′, β′)
255+
end
256+
return C
257+
end
258+
259+
function unsafe_mult!(
260+
C::StridedView{T}, A::StridedView{T}, B::StridedView{T},
261+
einA, einB, einC, α::T, β::T
262+
) where {T <: TBLISFloat}
263+
# TBLIS scales the product by the scalars of both factors, so α rides along on A alone.
264+
# The conjugation flags are all `false` because `tblis_tensor_mult` ignores them and the
265+
# caller has resolved the conjugations already.
266+
tA = TBLISTensor(A, α, false)
267+
tB = TBLISTensor(B, one(T), false)
268+
tC = TBLISTensor(C, β, false)
269+
GC.@preserve tA tB tC begin
270+
TBLIS.tblis_tensor_mult(
271+
C_NULL, C_NULL, tA.ref, labels(einA), tB.ref, labels(einB),
272+
tC.ref, labels(einC)
273+
)
274+
end
275+
return C
276+
end
277+
278+
# Write `α * conj(raw A)` into a fresh temporary that keeps the index order of `A`, so that
279+
# the labels computed for `A` remain valid for it and it can be fed to `mult` unconjugated.
280+
function materialize_conj(A::StridedView{T, N}, α::T, allocator) where {T <: TBLISFloat, N}
281+
pA = (ntuple(identity, N), ())
282+
A′ = tensoralloc_add(T, A, pA, false, Val(true), allocator)
283+
einA, einC = add_labels(pA)
284+
unsafe_add!(SV(A′), A, true, einA, einC, α, zero(T))
285+
return A′
286+
end
287+
288+
end # module TensorOperationsTBLISExt

0 commit comments

Comments
 (0)