Skip to content

Commit 41a979f

Browse files
committed
KA kernel for add_transform for Abelian symmetries
1 parent 3e1b0fb commit 41a979f

2 files changed

Lines changed: 202 additions & 2 deletions

File tree

‎Project.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,6 @@ TimerOutputs = "1"
7272
TupleTools = "1.5"
7373
VectorInterface = "0.6"
7474
julia = "1.10"
75+
76+
[sources]
77+
TensorOperations = {url = "https://github.com/QuantumKitHub/TensorOperations.jl", rev = "main"}

‎ext/TensorKitGPUArraysExt.jl‎

Lines changed: 199 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@ module TensorKitGPUArraysExt
33
using GPUArrays
44
using GPUArrays: @allowscalar
55
using GPUArrays.KernelAbstractions: @kernel, @index, get_backend
6-
6+
using Adapt
77
using Strided: StridedViews
88
using MatrixAlgebraKit, Adapt
99
using TensorKit
10+
using TensorKit.TensorOperations: linearize, DefaultAllocator
1011
using TensorKit.Factorizations
1112
using TensorKit.Factorizations: AbstractAlgorithm
1213
using TensorKit: SectorDict, tensormaptype, scalar, similarstoragetype, AdjointTensorMap, scalartype, project_symmetric_and_check
13-
import TensorKit: randisometry, rand, randn, fill_braidingsubblock!
14+
import TensorKit: randisometry, rand, randn, fill_braidingsubblock!, add_transform_kernel!
1415

1516
function TensorKit.fill_braidingsubblock!(data::TD, val) where {T, TD <: Union{<:AnyGPUMatrix{T}, <:StridedViews.StridedView{T, 4, <:AnyGPUArray{T}}}}
1617
# COV_EXCL_START
@@ -121,5 +122,201 @@ function TensorKit.scalar(t::TensorMap{T, S, 0, 0, <:AnyGPUArray}) where {T, S}
121122
return isempty(inds) ? zero(scalartype(t)) : @allowscalar @inbounds t.data[only(inds)]
122123
end
123124

125+
# Device-side tree transformers
126+
# -----------------------------
127+
# We pack all the information on the CPU side into dense vectors of numbers,
128+
# plus some accounting information so we know how to unpack in the kernel.
129+
# Also, we can permute the source strides "in advance" on the CPU side.
130+
# We also precompute the strides of the subblock each kernel index will work on,
131+
# so that the GPU thread can recover the Cartesian
132+
# coordinates it will need for input/ouput, and a running `work_offsets` count
133+
# of destination elements, so that a kernel can run one thread per output
134+
# element and recover which input that element belongs with.
135+
136+
# Some possible TODO here:
137+
# - Try cuTILE as this is a classic tile programming problem
138+
# - Use shared memory to coalesce the reads
139+
# - Use a 2D grid for the Generic case
140+
141+
const TreeStructure{N} = Tuple{NTuple{N, Int}, Int}
142+
143+
"""
144+
AbelianTransformerBlock{T, N}
145+
146+
`isbits` descriptor for a subblock that is a *single* scaled permutation:
147+
an entry of an `AbelianTreeTransformer`.
148+
"""
149+
struct AbelianTransformerBlock{T, N}
150+
coeff::T
151+
sz::NTuple{N, Int}
152+
densestrides::NTuple{N, Int}
153+
st_dst::NTuple{N, Int}
154+
offs_dst::Int
155+
pst_src::NTuple{N, Int} # source strides, permuted by `p`
156+
offs_src::Int
157+
end
158+
159+
# device-side simple struct that GPU kernels can use
160+
struct DeviceAbelianTreeTransformer{VB <: AbstractVector{<:AbelianTransformerBlock}, VO <: AbstractVector{Int}}
161+
blocks::VB
162+
work_offsets::VO
163+
nwork::Int
164+
end
165+
166+
# strides of a dense array of shape `sz`
167+
_densestrides(sz::NTuple{N, Int}) where {N} = ntuple(n -> prod(sz[1:(n - 1)]; init = 1), Val(N))
168+
_permutestrides(st::NTuple{N, Int}, p) where {N} = ntuple(n -> st[p[n]], Val(N))
169+
170+
# `permute(Vsrc, p) == Vdst` is enforced when the transformer is built, so the permuted
171+
# source shape always matches `sz_dst` and the two views share Cartesian inds.
172+
function _abelian_block(
173+
coeff::T, (sz_dst, st_dst, offs_dst), (_, st_src, offs_src), p
174+
) where {T}
175+
return AbelianTransformerBlock{T, length(sz_dst)}(
176+
coeff, sz_dst, _densestrides(sz_dst), st_dst, offs_dst,
177+
_permutestrides(st_src, p), offs_src
178+
)
179+
end
180+
181+
function _work_offsets(work)
182+
offsets = cumsum(work)
183+
pushfirst!(offsets, 0)
184+
total = pop!(offsets)
185+
return offsets, total
186+
end
187+
188+
function DeviceAbelianTreeTransformer(
189+
transformer::TensorKit.AbelianTreeTransformer{T, N}, p
190+
) where {T, N}
191+
blocks = AbelianTransformerBlock{T, N}[_abelian_block(entry..., p) for entry in transformer.data]
192+
work_offsets, nwork = _work_offsets(prod(blk.sz) for blk in blocks)
193+
return DeviceAbelianTreeTransformer(blocks, work_offsets, nwork)
194+
end
195+
196+
"""
197+
StorageAdaptor(proto)
198+
199+
`Adapt` adaptor moving arrays onto the same device and array type as `proto`, preserving
200+
their element type. `adapt(CuVector{Float64}, ::Vector{Int})` would force-convert the Int
201+
to Float64, while `similar(proto, Int, n)` doesn't.
202+
"""
203+
struct StorageAdaptor{A <: AbstractArray}
204+
proto::A
205+
end
206+
function Adapt.adapt_storage(a::StorageAdaptor, x::AbstractArray)
207+
dst = similar(a.proto, eltype(x), size(x))
208+
isempty(x) && return dst
209+
return copyto!(dst, x)
210+
end
211+
212+
function Adapt.adapt_structure(to, t::DeviceAbelianTreeTransformer)
213+
return DeviceAbelianTreeTransformer(
214+
Adapt.adapt(to, t.blocks), Adapt.adapt(to, t.work_offsets), t.nwork
215+
)
216+
end
217+
218+
# Copying a transformer to GPU is more expensive than running it, and transformers are
219+
# themselves cached (and thus long-lived) by `treebraider`/`treetransposer`, so we cache the
220+
# device copy for as long as the CPU original is "alive". The key is:
221+
# - `transformer.data`
222+
# - the storage type
223+
# - `p`, which is baked into the permuted source strides.
224+
# Using `objectid` avoids walking every recoupling matrix on every lookup.
225+
# TODO: should this live in the main package?
226+
const DEVICE_TRANSFORMER_CACHE = Dict{UInt, Tuple{WeakRef, Dict{Any, Any}}}()
227+
const DEVICE_TRANSFORMER_LOCK = ReentrantLock()
228+
229+
# We have this complicated setup because a naive `adapt` doesn't work.
230+
# Rather we copy everything to GPU-native arrays and have kernels that can work
231+
# with that.
232+
function device_transformer(proto::AbstractArray, transformer, p)
233+
key = transformer.data
234+
return Base.@lock DEVICE_TRANSFORMER_LOCK begin
235+
entry = get(DEVICE_TRANSFORMER_CACHE, objectid(key), nothing)
236+
if isnothing(entry) || entry[1].value !== key
237+
filter!(kv -> !isnothing(last(kv)[1].value), DEVICE_TRANSFORMER_CACHE)
238+
entry = (WeakRef(key), Dict{Any, Any}())
239+
DEVICE_TRANSFORMER_CACHE[objectid(key)] = entry
240+
end
241+
get!(last(entry), (typeof(proto), p)) do
242+
# be careful about the lifetime of these, since they live as long as their
243+
# "parent" on the CPU, so they can persist beyond the call
244+
GPUArrays.@uncached Adapt.adapt(
245+
StorageAdaptor(proto), _device_transformer(transformer, p)
246+
)
247+
end
248+
end
249+
end
250+
251+
_device_transformer(t::TensorKit.AbelianTreeTransformer, p) = DeviceAbelianTreeTransformer(t, p)
252+
253+
# COV_EXCL_START
254+
# kernels are not reachable by coverage
255+
256+
# largest `i` with `offsets[i] <= w`. This corresponds to the
257+
# block which this kernel thread will work on.
258+
@inline function _searchblock(offsets, w)
259+
lo, hi = 1, length(offsets)
260+
while lo < hi
261+
mid = (lo + hi + 1) >>> 1
262+
if @inbounds offsets[mid] <= w
263+
lo = mid
264+
else
265+
hi = mid - 1
266+
end
267+
end
268+
return lo
269+
end
270+
271+
# Cartesian coordinates of the `w`-th (0-based) entry of a dense subblock of shape `sz`.
272+
# Computed once per thread and then reused for every strided view of that subblock.
273+
# This avoids `StridedView` redoing these divisions on every single element access.
274+
# Integer division on GPU is usually pretty slow.
275+
@inline function _coordinates(w, sz::NTuple{N, Int}, densestrides::NTuple{N, Int}) where {N}
276+
return ntuple(n -> (w ÷ densestrides[n]) % sz[n], Val(N))
277+
end
278+
279+
# finds the overall offset in the output and input arrays corresponding to the **sublock**
280+
# coordinates currently being worked on
281+
@inline function _offset(coords::NTuple{N, Int}, st::NTuple{N, Int}, offs) where {N}
282+
return offs + sum(ntuple(n -> coords[n] * st[n], Val(N))) + 1
283+
end
284+
285+
# One thread per destination element in `data_dst`.
286+
@kernel function abelian_batched_permute!(
287+
data_dst, data_src, blocks, work_offsets, α, β, nwork, ::Val{N}
288+
) where {N}
289+
w = @index(Global, Linear) - 1
290+
if w < nwork
291+
b = _searchblock(work_offsets, w)
292+
blk = @inbounds blocks[b]
293+
coords = _coordinates(w - (@inbounds work_offsets[b]), blk.sz, blk.densestrides)
294+
i_dst = _offset(coords, blk.st_dst, blk.offs_dst)
295+
i_src = _offset(coords, blk.pst_src, blk.offs_src)
296+
@inbounds data_dst[i_dst] = α * blk.coeff * data_src[i_src] + β * data_dst[i_dst]
297+
end
298+
end
299+
300+
# COV_EXCL_STOP
301+
302+
function _launch_abelian!(data_dst, data_src, transformer, α, β, ::Val{N}) where {N}
303+
nwork = transformer.nwork
304+
nwork == 0 && return nothing
305+
abelian_batched_permute!(get_backend(data_dst))(
306+
data_dst, data_src, transformer.blocks, transformer.work_offsets, α, β, nwork,
307+
Val(N); ndrange = nwork
308+
)
309+
return nothing
310+
end
311+
312+
function TensorKit.add_transform_kernel!(
313+
data_dst::A, data_src::A, p, transformer::TensorKit.AbelianTreeTransformer{T, N},
314+
α, β, backend, allocator, ntasks::Int
315+
) where {T, N, A <: AnyGPUArray}
316+
# GPU-side object to hold the treetransformer information
317+
device = device_transformer(data_dst, transformer, linearize(p))::DeviceAbelianTreeTransformer
318+
_launch_abelian!(data_dst, data_src, device, α, β, Val(N))
319+
return nothing
320+
end
124321

125322
end

0 commit comments

Comments
 (0)