Skip to content

Commit 98d8c28

Browse files
lkdvosclaude
andauthored
fix + uniform approach to GPU buffers (#296)
* Fix JLArray buffer-backed temporaries against JLArrays 0.3.2 JLArrays 0.3.2 changed `JLArray`'s `offset` field from a count of elements to a count of bytes, and `pointer` from `pointer(x.data) + x.offset*elsize(x)` to `pointer(x.data) + x.offset`. `unsafe_buffer_wrap` built the temporary with the constructor directly, so under 0.3.2 every buffer-backed temporary landed at byte `start ÷ sizeof(T)` instead of `start`: misaligned, and overlapping both each other and earlier temporaries, which silently corrupted results. Go through `GPUArrays.derive` instead, the documented backend hook for producing an array of a different type and size backed by the same data. Its offset is expressed in elements on both versions, so this is insensitive to how the backend stores it. `ROCArray` already used a byte offset directly and was unaffected. Compat gets a `0.3.1` lower bound, matching the versions this was verified on. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Share the buffer-backing implementation across GPU backends `unsafe_buffer_wrap` was written three times, once per backend, and each reached for a different private detail: `JLArray`'s constructor with an element offset, `ROCArray`'s with a byte offset, and `unsafe_wrap` on a raw `CuPtr`. The first of those is what broke against JLArrays 0.3.2. Route all three through `GPUArrays.derive` in a new `TensorOperationsGPUArraysExt` instead. It is the documented backend hook for producing an array of a different type and size backed by the same data, its offset is in elements on every backend and version, and sharing the storage's refcounted handle keeps the buffer alive for as long as a temporary derived from it -- which the `CuArray` path, wrapping a bare pointer, did not do. `buffer_arraytype` likewise collapses into one method, via a new `buffer_similartype` that asks the buffer's own storage what it produces for the requested element type and rank. This resolves at compile time and reproduces each backend's answer exactly, memory space and buffer type included. It stays out of the core default because a storage is not always the kind of array it hands out: `similar(::Memory{UInt8}, T, Dims{1})` is a `Memory`, not a `Vector`. Since `derive` offsets by whole elements, the element-addressability restriction that only `JLArray` applied now covers all three, as `buffer_iselementaddressable`. Element types it rejects fall back on a regular allocation, so this costs buffer backing for exotic types, never correctness. Verified against JLArrays 0.3.1 and 0.3.2, so the compat bound stays at "0.3". Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Make the buffer's element-offset restriction unnecessary `GPUArrays.derive` counts its offset in elements, which previously restricted buffer-backed temporaries to element types whose size divides the alignment the offset is padded to: `buffer_iselementaddressable` rejected the others, and the GPUArrays extension had to override `buffer_arraytype` to apply that check. Pad the offset to a multiple of `sizeof(T)` instead. This is the only padding that can express a byte offset as an element offset on every backend -- some carry the offset in bytes, others in elements, and no way of calling `derive` can represent a non-element-aligned offset in the latter -- and it costs no additional padding for element types whose size divides the alignment, which is all the standard ones. Oversized and oddly sized element types are now served from the buffer as well, rather than falling back on a regular allocation. With the check gone, what is left of the extension's `buffer_arraytype` is the `similar`-based rule, which is the right default for any storage: promote it to the default implementation, and keep an `Array` answer for `Memory` storage, the one storage whose `similar` stays a `Memory` at rank 1 while the temporaries it hands out are `Array`s at every rank. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Trim the comments and docstrings down Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Infer `buffer_arraytype` from `unsafe_buffer_wrap` itself Asking `similar` what the storage would produce needed a `Memory` exception, since a `Memory` stays a `Memory` at rank 1 while the temporaries it hands out are `Array`s. Infer the wrap instead: the answer is then the type that is actually handed out, and no method applying is itself the `nothing` answer, so a storage only has to implement `unsafe_buffer_wrap` to be served from the buffer. Dispatch that host method on host storages, so that a device buffer asked for an `Array` has no method rather than a pointer conversion that would throw. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 609be29 commit 98d8c28

7 files changed

Lines changed: 99 additions & 84 deletions

File tree

‎Project.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
2323
CUDACore = "bd0ed864-bdfe-4181-a5ed-ce625a5fdea2"
2424
cuTENSOR = "011b41b2-24ef-40a8-b3eb-fa098493e9e1"
2525
Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9"
26+
GPUArrays = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7"
2627
JLArrays = "27aeb0d3-9eb9-45fb-866b-73c2ecf80fcb"
2728
Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6"
2829

@@ -33,6 +34,7 @@ TensorOperationsChainRulesCoreExt = "ChainRulesCore"
3334
TensorOperationsMooncakeExt = "Mooncake"
3435
TensorOperationsCUDACoreExt = "CUDACore"
3536
TensorOperationsEnzymeExt = "Enzyme"
37+
TensorOperationsGPUArraysExt = "GPUArrays"
3638
TensorOperationscuTENSORExt = "cuTENSOR"
3739
TensorOperationsJLArraysExt = "JLArrays"
3840

@@ -47,6 +49,7 @@ ChainRulesTestUtils = "1"
4749
DynamicPolynomials = "0.5, 0.6"
4850
Enzyme = "0.13.183"
4951
EnzymeTestUtils = "0.2"
52+
GPUArrays = "11"
5053
JLArrays = "0.3"
5154
LRUCache = "1"
5255
LinearAlgebra = "1.6"

‎ext/TensorOperationsAMDGPUExt.jl‎

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -59,31 +59,9 @@ function TO.AMDBufferAllocator(;
5959
return TO.BufferAllocator{ROCArray{UInt8, 1, buftype}}(; sizehint)
6060
end
6161

62-
# AMD buffers can only back `ROCArray`s; the generic implementation already takes care of
63-
# the converse, i.e. that host buffers can never back `ROCArray`s
64-
function TO.buffer_arraytype(
65-
::Type{<:ROCArray{T, N}}, ::ROCBufferAllocator{B}
66-
) where {T, N, B}
67-
return ROCArray{T, N, B}
68-
end
69-
TO.buffer_arraytype(::Type{<:Array}, ::ROCBufferAllocator) = nothing
70-
7162
# HIP allocations are 256-byte aligned; matching that keeps rocBLAS kernel selection identical, at ≤255 bytes of padding
7263
TO.buffer_alignment(::ROCBufferAllocator) = 256
7364

74-
# Share the buffer's refcounted `DataRef` at a byte offset, as `reshape` does: that keeps the buffer alive, and
75-
# avoids the `hipPointerGetAttributes` query that `unsafe_wrap` would do per temporary
76-
function TO.unsafe_buffer_wrap(
77-
::Type{ROCArray{T, N, B}}, buffer::ROCBufferAllocator{B}, start, structure
78-
) where {T, N, B}
79-
ref = copy(AMDGPU.GPUArrays.storage(buffer.buffer))
80-
return ROCArray{T, N}(ref, _asdims(structure); offset = Int(start))
81-
end
82-
83-
# `structure` is a shape for arrays, but a bare length is accepted for vectors
84-
_asdims(structure::Base.Dims) = structure
85-
_asdims(n::Integer) = (Int(n),)
86-
8765
# mirror the `AMDAllocator` behavior: results and temporaries are `ROCArray`s, even if the inputs are regular host arrays
8866
function TO.tensoralloc_add(
8967
TC, A::AbstractArray, pA::Index2Tuple, conjA::Bool,

‎ext/TensorOperationsCUDACoreExt.jl‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,24 +65,10 @@ function TO.CUDABufferAllocator(; sizehint::Integer = 0, memory = CUDACore.defau
6565
return TO.BufferAllocator{CuArray{UInt8, 1, memory}}(; sizehint)
6666
end
6767

68-
# CUDA buffers can only back `CuArray`s; the generic implementation already takes care of
69-
# the converse, i.e. that host buffers can never back `CuArray`s
70-
function TO.buffer_arraytype(::Type{<:CuArray{T, N}}, ::CuBufferAllocator{M}) where {T, N, M}
71-
return CuArray{T, N, M}
72-
end
73-
TO.buffer_arraytype(::Type{<:Array}, ::CuBufferAllocator) = nothing
74-
7568
# CUDA allocations are 256-byte aligned, and cuTENSOR selects noticeably faster kernels for 256-byte aligned data.
7669
# The padding this costs is at most 255 bytes per temporary, which is negligible in comparison.
7770
TO.buffer_alignment(::CuBufferAllocator) = 256
7871

79-
function TO.unsafe_buffer_wrap(
80-
::Type{CuArray{T, N, M}}, buffer::CuBufferAllocator{M}, start, structure
81-
) where {T, N, M}
82-
ptr = convert(CuPtr{T}, pointer(buffer, start))
83-
return unsafe_wrap(CuArray{T, N, M}, ptr, structure)
84-
end
85-
8672
# mirror the `CUDAAllocator` behavior: results and temporaries are `CuArray`s, even if the inputs are regular host arrays
8773
function TO.tensoralloc_add(
8874
TC, A::AbstractArray, pA::Index2Tuple, conjA::Bool,
@@ -105,7 +91,7 @@ function TO.tensoralloc_contract(
10591
return TO.tensoralloc(ttype, structure, istemp, allocator)::ttype
10692
end
10793

108-
# NOTE: this is a no-op for tensors that are backed by the buffer, as `unsafe_wrap` creates a non-owning reference
94+
# NOTE: for tensors backed by the buffer this only releases the reference that `unsafe_buffer_wrap` retained
10995
function TO.tensorfree!(C::CuArray, ::CuBufferAllocator)
11096
CUDACore.unsafe_free!(C)
11197
return nothing
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
module TensorOperationsGPUArraysExt
2+
3+
using GPUArrays
4+
using TensorOperations
5+
using TensorOperations: TensorOperations as TO
6+
7+
#-------------------------------------------------------------------------------------------
8+
# BufferAllocator with AbstractGPUArray storage
9+
#-------------------------------------------------------------------------------------------
10+
11+
const GPUBufferAllocator = TO.BufferAllocator{<:AbstractGPUArray}
12+
13+
# `GPUArrays.derive` is the backend hook that `reshape` and contiguous `view`s go through: it
14+
# shares the buffer's refcounted storage, which keeps it alive for as long as the temporary,
15+
# and is insensitive to how a backend represents the offset internally
16+
function TO.unsafe_buffer_wrap(
17+
::Type{A}, buffer::GPUBufferAllocator, start, structure
18+
) where {A <: AbstractGPUArray}
19+
T = eltype(A)
20+
return GPUArrays.derive(T, buffer.buffer, TO._asdims(structure), Int(start) ÷ sizeof(T))
21+
end
22+
23+
end

‎ext/TensorOperationsJLArraysExt.jl‎

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -21,32 +21,6 @@ const JLBuffer = TO.BufferAllocator{JLArray{UInt8, 1}}
2121
TO.JLBufferAllocator(; sizehint::Integer = 0) =
2222
TO.BufferAllocator{JLArray{UInt8, 1}}(; sizehint)
2323

24-
# `JLArray`s are addressed by element offset, so `T`s whose size does not divide the alignment cannot be buffer-backed
25-
function _iselementaddressable(::Type{T}, buffer::JLBuffer) where {T}
26-
sz = sizeof(T)
27-
alignment = max(Base.datatype_alignment(T), TO.buffer_alignment(buffer))
28-
return !iszero(sz) && iszero(alignment % sz)
29-
end
30-
31-
# JLArray buffers can only back `JLArray`s; the generic implementation already takes care of
32-
# the converse, i.e. that host buffers can never back `JLArray`s
33-
function TO.buffer_arraytype(::Type{<:JLArray{T, N}}, buffer::JLBuffer) where {T, N}
34-
return _iselementaddressable(T, buffer) ? JLArray{T, N} : nothing
35-
end
36-
TO.buffer_arraytype(::Type{<:Array}, ::JLBuffer) = nothing
37-
38-
# Share the buffer's refcounted `DataRef` at an element offset, as `reshape` does, so the buffer outlives the temporary
39-
function TO.unsafe_buffer_wrap(
40-
::Type{JLArray{T, N}}, buffer::JLBuffer, start, structure
41-
) where {T, N}
42-
ref = copy(JLArrays.GPUArrays.storage(buffer.buffer))
43-
return JLArray{T, N}(ref, _asdims(structure); offset = Int(start) ÷ sizeof(T))
44-
end
45-
46-
# `structure` is a shape for arrays, but a bare length is accepted for vectors
47-
_asdims(structure::Base.Dims) = structure
48-
_asdims(n::Integer) = (Int(n),)
49-
5024
# mirror the GPU allocator behavior: results and temporaries are `JLArray`s, even if the inputs are regular host arrays
5125
function TO.tensoralloc_add(
5226
TC, A::AbstractArray, pA::Index2Tuple, conjA::Bool,

‎src/implementation/allocator.jl‎

Lines changed: 39 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ contractions will now fit in the buffer.
108108
The optional type parameter `Storage` determines the container that backs the buffer, and
109109
must have single-byte elements. It defaults to `Memory{UInt8}` (or `Vector{UInt8}` on Julia
110110
versions without `Memory`), which hands out regular `Array` temporaries. Other storage types
111-
can be supported by implementing [`TensorOperations.buffer_arraytype`](@ref) and
112-
[`TensorOperations.unsafe_buffer_wrap`](@ref); in particular, `CuArray`-, `ROCArray`- and
111+
can be supported by implementing [`TensorOperations.unsafe_buffer_wrap`](@ref);
112+
in particular, `CuArray`-, `ROCArray`- and
113113
`JLArray`-backed buffers are supported through [`TensorOperations.CUDABufferAllocator`](@ref),
114114
[`TensorOperations.AMDBufferAllocator`](@ref) and [`TensorOperations.JLBufferAllocator`](@ref).
115115
@@ -136,6 +136,9 @@ end
136136
const DefaultStorageType = @static isdefined(Core, :Memory) ? Memory{UInt8} : Vector{UInt8}
137137
BufferAllocator(; kwargs...) = BufferAllocator{DefaultStorageType}(; kwargs...)
138138

139+
# storages whose `pointer` is a host pointer, so that an `Array` can be wrapped around it
140+
const HostStorageType = @static isdefined(Core, :Memory) ? Union{Memory, Array} : Array
141+
139142
# `Sys.PAGESIZE` only exists on sufficiently recent Julia versions; fall back on the standard
140143
# page size otherwise, as this only serves as a granularity for rounding buffer sizes.
141144
# Note the conversion to `Int`: the underlying `Clong` is 32 bits wide on Windows.
@@ -345,10 +348,11 @@ allocation_size(::Type{T}, structure::Int) where {T} = structure * sizeof(T)
345348
"""
346349
buffer_alignment(buffer::BufferAllocator)
347350
348-
The alignment, in bytes, to which the temporaries handed out by `buffer` are padded.
351+
The minimum alignment, in bytes, to which the temporaries handed out by `buffer` are padded.
349352
This has to be a power of two, and currently there is no point in making it larger
350353
than the alignment of the buffer's own base pointer, as the padding would then not
351-
actually buy any alignment.
354+
actually buy any alignment. Element types whose size is not a divisor of it are padded
355+
further, to a multiple of that size as well.
352356
353357
Defaults to `16`, which is the alignment that Julia guarantees for its allocations,
354358
and which covers the natural alignment of all standard element types.
@@ -357,12 +361,26 @@ See also [`TensorOperations.buffer_arraytype`](@ref).
357361
"""
358362
buffer_alignment(::BufferAllocator) = 16
359363

360-
# round `offset` up to the next multiple of `alignment`, which has to be a power of 2
364+
# round `offset` up to the next multiple of `alignment`
361365
function _alignup(offset::Integer, alignment::Integer)
362366
a = oftype(offset, alignment)
363-
return (offset + a - one(a)) & ~(a - one(a))
367+
# the bit trick only holds for powers of two, which `_buffer_alignment` is free not to be
368+
ispow2(a) && return (offset + a - one(a)) & ~(a - one(a))
369+
return cld(offset, a) * a
370+
end
371+
372+
# The alignment `tensoralloc` pads a temporary of element type `T` to. The multiple of
373+
# `sizeof(T)` keeps the offset expressible in elements, which is how some backends carry it,
374+
# and costs no additional padding for element types whose size divides the alignment.
375+
function _buffer_alignment(::Type{T}, buffer::BufferAllocator) where {T}
376+
alignment = max(Base.datatype_alignment(T), buffer_alignment(buffer))
377+
return iszero(sizeof(T)) ? alignment : lcm(sizeof(T), alignment)
364378
end
365379

380+
# `structure` is a shape for arrays, but a bare length is accepted for vectors
381+
_asdims(structure::Base.Dims) = structure
382+
_asdims(n::Integer) = (Int(n),)
383+
366384
"""
367385
buffer_arraytype(::Type{A}, buffer::BufferAllocator)
368386
@@ -371,10 +389,17 @@ Return the concrete array type that is used to serve a temporary allocation of t
371389
allocation path is used instead. This only depends on the types involved, such that the
372390
choice is resolved at compile time.
373391
374-
See also [`TensorOperations.unsafe_buffer_wrap`](@ref).
392+
The default answer is inferred from [`TensorOperations.unsafe_buffer_wrap`](@ref): the type
393+
that wrapping `buffer`'s memory actually produces, or `nothing` if that is not a concrete
394+
subtype of `A`, which includes the case where no method applies. A storage therefore only has
395+
to implement `unsafe_buffer_wrap` for its arrays to be served from the buffer, and one whose
396+
wrap is not inferrable loses buffer backing rather than becoming incorrect.
375397
"""
376-
function buffer_arraytype(::Type{A}, ::BufferAllocator) where {A <: AbstractArray}
377-
return A <: Array ? A : nothing
398+
function buffer_arraytype(::Type{A}, buffer::BufferAllocator) where {A <: AbstractArray}
399+
S = Base.promote_op(
400+
unsafe_buffer_wrap, Type{A}, typeof(buffer), Int, Base.Dims{ndims(A)}
401+
)
402+
return (isconcretetype(S) && S <: A) ? S : nothing
378403
end
379404

380405
"""
@@ -384,9 +409,12 @@ Wrap the memory of `buffer`, starting at byte offset `start`, into an array of t
384409
shape `structure`. Here, `A` is the type returned by
385410
[`TensorOperations.buffer_arraytype`](@ref), and it is the caller's responsibility to ensure
386411
that the requested range actually fits within the buffer.
412+
413+
`start` is guaranteed to be a multiple of `sizeof(eltype(A))`, so arrays that carry an element
414+
offset rather than a pointer can use `start ÷ sizeof(eltype(A))` without losing bytes.
387415
"""
388416
function unsafe_buffer_wrap(
389-
::Type{A}, buffer::BufferAllocator, start, structure
417+
::Type{A}, buffer::BufferAllocator{<:HostStorageType}, start, structure
390418
) where {A <: Array}
391419
ptr = convert(Ptr{eltype(A)}, pointer(buffer, start))
392420
return Base.unsafe_wrap(Array, ptr, structure)
@@ -400,8 +428,7 @@ function tensoralloc(
400428
T = eltype(AA)
401429
nbytes = allocation_size(T, structure)
402430
if !iszero(nbytes) # empty temporaries have no meaningful pointer
403-
alignment = max(Base.datatype_alignment(T), buffer_alignment(buffer))
404-
start = _alignup(buffer.offset, alignment)
431+
start = _alignup(buffer.offset, _buffer_alignment(T, buffer))
405432
offset = start + nbytes
406433
sizehint!(buffer, offset)
407434

‎test/allocator.jl‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,22 @@ using JLArrays
7979
@test length(BufferAllocator(; sizehint = UInt(100))) == 128
8080
end
8181

82+
@testset "buffer_arraytype" begin
83+
# a host buffer serves `Array`s at every rank, including the rank where `similar` of
84+
# the default `Memory` storage stays a `Memory`
85+
for buffer in (BufferAllocator(), BufferAllocator{Vector{UInt8}}(; sizehint = 1024))
86+
for A in (
87+
Vector{Float64}, Matrix{ComplexF64}, Array{Float32, 3},
88+
Vector{NTuple{4, Float64}},
89+
)
90+
@test TensorOperations.buffer_arraytype(A, buffer) === A
91+
end
92+
@static if isdefined(Core, :Memory)
93+
@test TensorOperations.buffer_arraytype(Memory{Float64}, buffer) === nothing
94+
end
95+
end
96+
end
97+
8298
@testset "Checkpoint and reset" begin
8399
buffer = BufferAllocator(sizehint = 128)
84100
L = length(buffer)
@@ -245,17 +261,25 @@ end
245261
@test iszero(UInt(pointer(C2)) % 16)
246262
end
247263

248-
# `JLArray`s address their data by an element offset, which the 16-byte padding can only
249-
# express for element types that are at most that large: bigger ones fall back on a
250-
# regular allocation rather than silently landing on a truncated offset
264+
# element types whose size does not divide the alignment are padded to a multiple of
265+
# that size instead, so that the offset survives the conversion to elements that
266+
# `GPUArrays.derive` takes rather than truncating onto the previous temporary
251267
@test TensorOperations.buffer_arraytype(JLArray{ComplexF64, 1}, buffer) ===
252268
JLArray{ComplexF64, 1}
253-
@test TensorOperations.buffer_arraytype(JLArray{NTuple{4, Float64}, 1}, buffer) === nothing
254-
offset = buffer.offset
255-
C3 = tensoralloc(JLArray{NTuple{4, Float64}, 1}, (4,), Val(true), buffer)
256-
@test C3 isa JLArray{NTuple{4, Float64}, 1}
257-
@test !isbufferbacked(C3, buffer)
258-
@test buffer.offset == offset
269+
@test TensorOperations.buffer_arraytype(JLArray{NTuple{4, Float64}, 1}, buffer) ===
270+
JLArray{NTuple{4, Float64}, 1}
271+
for T in (NTuple{4, Float64}, NTuple{3, Float32})
272+
empty!(buffer)
273+
C3 = tensoralloc(JLArray{UInt8, 1}, (3,), Val(true), buffer)
274+
C4 = tensoralloc(JLArray{T, 1}, (4,), Val(true), buffer)
275+
@test isbufferbacked(C4, buffer)
276+
start = UInt(pointer(C4)) - UInt(pointer(buffer))
277+
@test iszero(start % sizeof(T))
278+
@test iszero(start % TensorOperations.buffer_alignment(buffer))
279+
# no overlap with the 3 bytes that `C3` occupies
280+
@test start ≥ 3
281+
@test buffer.offset == start + 4 * sizeof(T)
282+
end
259283
end
260284

261285
@testset "checkpoint and reset" begin

0 commit comments

Comments
 (0)