|
| 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