Skip to content

Commit 58c6e03

Browse files
authored
add CUDA buffer support (#293)
* add CUDA buffer support * update pagesize information * docs: name CUDABufferAllocator in the cuTENSOR allocator section The prose said `BufferAllocator` while the example below it constructs a `CUDABufferAllocator`, which read as inconsistent.
1 parent 8f98d7e commit 58c6e03

6 files changed

Lines changed: 478 additions & 17 deletions

File tree

‎docs/src/man/backends.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,8 @@ Optionally, it can be useful to use the `ManualAllocator`, as the manual memory
137137
In particular in multi-threaded applications, this can sometimes lead to a significant performance improvement.
138138
On the other hand, for repeated (but thread-safe!) `@tensor` calls, the `BufferAllocator` is a lightweight slab allocator that pre-allocates a buffer for temporaries, falling back to Julia's default if needed.
139139
Upon repeated use it will automatically resize the buffer to accommodate the requested temporaries, avoiding repeated reallocation.
140+
The container that backs the buffer is a type parameter, such that the same slab strategy can also be used for other kinds of memory.
141+
In particular, a `CuArray`-backed buffer, which is constructed through `CUDABufferAllocator`, hands out `CuArray` temporaries that are carved out of a single device allocation, thus avoiding repeated round-trips to the CUDA memory pool.
140142

141143
Finally, users can also opt to use the `Bumper.jl` system, which pre-allocates a slab of memory that can be re-used afterwards.
142144
This is available through a package extension for `Bumper`.
@@ -162,8 +164,20 @@ with respect to temporaries, as well as input and output tensors.
162164

163165
```@docs
164166
TensorOperations.CUDAAllocator
167+
TensorOperations.CUDABufferAllocator
165168
```
166169

170+
Alternatively, the `CUDABufferAllocator` can also be used with the `cuTENSORBackend()`. This is simply a `BufferAllocator` backed by CUDA memory:
171+
172+
```julia
173+
using TensorOperations, cuTENSOR
174+
allocator = TensorOperations.CUDABufferAllocator(; sizehint = 2^20)
175+
@tensor backend = cuTENSORBackend() allocator = allocator A[i,j] := B[i,k] * C[k,j]
176+
```
177+
178+
Here, all temporaries are taken from the pre-allocated device buffer, which is grown automatically until it is large enough to hold all temporaries of a single `@tensor` block.
179+
Just like `CUDAAllocator`, this will produce `CuArray` outputs even when the inputs are regular host arrays.
180+
167181
### Custom Allocators
168182

169183
Users can also define their own allocators, to facilitate experimentation with new implementations.
@@ -189,3 +203,12 @@ For allocators that manage reusable buffers or maintain state across multiple co
189203

190204
Here we are guaranteeing that every created checkpoint will be restored, and all temporary allocations that are enclosed within this scope will no longer be accessed.
191205
Additionally, if multiple checkpoints are created, they will be restored in a first-in-last-out order.
206+
207+
Finally, rather than writing an allocator from scratch, the built-in `BufferAllocator` can be reused with a different kind of storage, by implementing the two methods below.
208+
The bookkeeping of the buffer itself, i.e. the high-water mark, the automatic resizing and the checkpointing, is then shared with the default implementation.
209+
210+
```@docs
211+
TensorOperations.buffer_arraytype
212+
TensorOperations.unsafe_buffer_wrap
213+
TensorOperations.buffer_alignment
214+
```

‎ext/TensorOperationsCUDACoreExt.jl‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,71 @@ function TO.tensorfree!(C::CuArray, ::TO.CUDAAllocator)
5454
return nothing
5555
end
5656

57+
#-------------------------------------------------------------------------------------------
58+
# BufferAllocator with CuArray storage
59+
#-------------------------------------------------------------------------------------------
60+
61+
const CuBufferAllocator{M} = TO.BufferAllocator{CuArray{UInt8, 1, M}}
62+
63+
# Note: different binding of the same name because type alias cannot be exported from extension
64+
function TO.CUDABufferAllocator(; sizehint::Integer = 0, memory = CUDACore.default_memory)
65+
return TO.BufferAllocator{CuArray{UInt8, 1, memory}}(; sizehint)
66+
end
67+
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+
75+
# CUDA allocations are 256-byte aligned, and cuTENSOR selects noticeably faster kernels for 256-byte aligned data.
76+
# The padding this costs is at most 255 bytes per temporary, which is negligible in comparison.
77+
TO.buffer_alignment(::CuBufferAllocator) = 256
78+
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+
86+
# mirror the `CUDAAllocator` behavior: results and temporaries are `CuArray`s, even if the inputs are regular host arrays
87+
function TO.tensoralloc_add(
88+
TC, A::AbstractArray, pA::Index2Tuple, conjA::Bool,
89+
istemp::Val, allocator::CuBufferAllocator
90+
)
91+
ttype = CuArray{TC, TO.numind(pA)}
92+
structure = TO.tensoradd_structure(A, pA, conjA)
93+
return TO.tensoralloc(ttype, structure, istemp, allocator)::ttype
94+
end
95+
96+
function TO.tensoralloc_contract(
97+
TC,
98+
A::AbstractArray, pA::Index2Tuple, conjA::Bool,
99+
B::AbstractArray, pB::Index2Tuple, conjB::Bool,
100+
pAB::Index2Tuple,
101+
istemp::Val, allocator::CuBufferAllocator
102+
)
103+
ttype = CuArray{TC, TO.numind(pAB)}
104+
structure = TO.tensorcontract_structure(A, pA, conjA, B, pB, conjB, pAB)
105+
return TO.tensoralloc(ttype, structure, istemp, allocator)::ttype
106+
end
107+
108+
# NOTE: this is a no-op for tensors that are backed by the buffer, as `unsafe_wrap` creates a non-owning reference
109+
function TO.tensorfree!(C::CuArray, ::CuBufferAllocator)
110+
CUDACore.unsafe_free!(C)
111+
return nothing
112+
end
113+
114+
function Base.resize!(buffer::CuBufferAllocator{M}, n::Integer) where {M}
115+
isempty(buffer) || error("Cannot resize a buffer that still contains elements")
116+
n = TO._buffersz(n)
117+
if n != length(buffer)
118+
CUDACore.unsafe_free!(buffer.buffer) # free before allocating new one to reduce memory pressure
119+
buffer.buffer = CuArray{UInt8, 1, M}(undef, n)
120+
end
121+
return buffer
122+
end
123+
57124
end

‎ext/TensorOperationscuTENSORExt.jl‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,9 @@ function TO.tensortrace!(
120120
end
121121

122122
_custrided(A::AbstractArray, ::DefaultAllocator) = _custrided(A, CUDAAllocator())
123+
# input tensors are marshalled to the device in the same way as for the default allocator:
124+
# the buffer is reserved for the temporaries that are created by the tensor operations
125+
_custrided(A::AbstractArray, ::TO.BufferAllocator) = _custrided(A, CUDAAllocator())
123126
function _custrided(
124127
A::AbstractArray, allocator::CUDAAllocator{Mout, Min, Mtemp}
125128
) where {Mout, Min, Mtemp}

‎src/implementation/allocator.jl‎

Lines changed: 117 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,22 @@ Allocator that uses the AMD memory manager and will thus allocate `ROCArray` ins
3737
"""
3838
struct AMDAllocator end
3939

40+
"""
41+
CUDABufferAllocator(; sizehint = 0, memory = CUDA.default_memory)
42+
43+
Convenience constructor for a [`BufferAllocator`](@ref) that is backed by CUDA memory, and
44+
which will thus hand out `CuArray` instances that are carved out of a single pre-allocated
45+
buffer. The `memory` keyword can be any of the CUDA.jl memory types, i.e.
46+
`CUDA.DeviceMemory`, `CUDA.UnifiedMemory` or `CUDA.HostMemory`, and determines both where the
47+
buffer itself lives and in which memory space the temporary tensors will be located.
48+
49+
This requires `CUDACore` to be loaded, and is equivalent to spelling out the storage type as
50+
`BufferAllocator{CuArray{UInt8, 1, memory}}(; sizehint)`.
51+
52+
See also [`TensorOperations.BufferAllocator`](@ref) and [`TensorOperations.CUDAAllocator`](@ref).
53+
"""
54+
function CUDABufferAllocator end
55+
4056
"""
4157
ManualAllocator()
4258
@@ -50,13 +66,21 @@ struct ManualAllocator end
5066

5167
"""
5268
BufferAllocator(; sizehint = 0)
69+
BufferAllocator{Storage}(; sizehint = 0)
5370
5471
Allocator that uses a pre-allocated buffer for storing temporary tensors.
5572
When the buffer is full, the allocator falls back on Julia's default allocation mechanism
5673
to create temporary tensors, but keeps track of how much additional memory is required.
5774
When the buffer is fully reset, the buffer is automatically resized to ensure subsequent
5875
contractions will now fit in the buffer.
5976
77+
The optional type parameter `Storage` determines the container that backs the buffer, and
78+
must have single-byte elements. It defaults to `Memory{UInt8}` (or `Vector{UInt8}` on Julia
79+
versions without `Memory`), which hands out regular `Array` temporaries. Other storage types
80+
can be supported by implementing [`TensorOperations.buffer_arraytype`](@ref) and
81+
[`TensorOperations.unsafe_buffer_wrap`](@ref); in particular, `CuArray`-backed buffers are
82+
supported through [`TensorOperations.CUDABufferAllocator`](@ref).
83+
6084
!!! warning
6185
This allocator is **not** thread-safe, and it is the user's responsibility to avoid running
6286
the same allocator on concurrent jobs. For concurrent usage, it is recommended to either
@@ -80,8 +104,24 @@ end
80104
const DefaultStorageType = @static isdefined(Core, :Memory) ? Memory{UInt8} : Vector{UInt8}
81105
BufferAllocator(; kwargs...) = BufferAllocator{DefaultStorageType}(; kwargs...)
82106

83-
# allocate buffers in sizes that are powers of 2
84-
_buffersz(x::Integer) = iszero(x) ? x : Base.nextpow(2, x)
107+
# `Sys.PAGESIZE` only exists on sufficiently recent Julia versions; fall back on the standard
108+
# page size otherwise, as this only serves as a granularity for rounding buffer sizes.
109+
# Note the conversion to `Int`: the underlying `Clong` is 32 bits wide on Windows.
110+
@static if isdefined(Sys, :PAGESIZE)
111+
_pagesize() = Int(Sys.PAGESIZE)
112+
else
113+
_pagesize() = 4096
114+
end
115+
116+
# Allocate buffers in sizes that are a multiple of the page size.
117+
# Below a single page, powers of two are used instead, as rounding every small buffer up to a full page would be wasteful.
118+
# The result is always an `Int`, as that is what the storage constructors expect.
119+
function _buffersz(x::Integer)
120+
iszero(x) && return 0
121+
pagesize = _pagesize()
122+
x ≤ pagesize && return Int(Base.nextpow(2, x))
123+
return Int(cld(x, pagesize) * pagesize)
124+
end
85125

86126
# ------------------------------------------------------------------------------------------
87127
# Generic implementation
@@ -270,26 +310,87 @@ end
270310
allocation_size(::Type{T}, structure::Base.Dims) where {T} = prod(structure) * sizeof(T)
271311
allocation_size(::Type{T}, structure::Int) where {T} = structure * sizeof(T)
272312

313+
"""
314+
buffer_alignment(buffer::BufferAllocator)
315+
316+
The alignment, in bytes, to which the temporaries handed out by `buffer` are padded.
317+
This has to be a power of two, and currently there is no point in making it larger
318+
than the alignment of the buffer's own base pointer, as the padding would then not
319+
actually buy any alignment.
320+
321+
Defaults to `16`, which is the alignment that Julia guarantees for its allocations,
322+
and which covers the natural alignment of all standard element types.
323+
324+
See also [`TensorOperations.buffer_arraytype`](@ref).
325+
"""
326+
buffer_alignment(::BufferAllocator) = 16
327+
328+
# round `offset` up to the next multiple of `alignment`, which has to be a power of 2
329+
function _alignup(offset::Integer, alignment::Integer)
330+
a = oftype(offset, alignment)
331+
return (offset + a - one(a)) & ~(a - one(a))
332+
end
333+
334+
"""
335+
buffer_arraytype(::Type{A}, buffer::BufferAllocator)
336+
337+
Return the concrete array type that is used to serve a temporary allocation of type `A` from
338+
`buffer`, or `nothing` if `buffer` cannot back arrays of type `A`, in which case the regular
339+
allocation path is used instead. This only depends on the types involved, such that the
340+
choice is resolved at compile time.
341+
342+
See also [`TensorOperations.unsafe_buffer_wrap`](@ref).
343+
"""
344+
function buffer_arraytype(::Type{A}, ::BufferAllocator) where {A <: AbstractArray}
345+
return A <: Array ? A : nothing
346+
end
347+
348+
"""
349+
unsafe_buffer_wrap(::Type{A}, buffer::BufferAllocator, start, structure) -> A
350+
351+
Wrap the memory of `buffer`, starting at byte offset `start`, into an array of type `A` with
352+
shape `structure`. Here, `A` is the type returned by
353+
[`TensorOperations.buffer_arraytype`](@ref), and it is the caller's responsibility to ensure
354+
that the requested range actually fits within the buffer.
355+
"""
356+
function unsafe_buffer_wrap(
357+
::Type{A}, buffer::BufferAllocator, start, structure
358+
) where {A <: Array}
359+
ptr = convert(Ptr{eltype(A)}, pointer(buffer, start))
360+
return Base.unsafe_wrap(Array, ptr, structure)
361+
end
362+
273363
function tensoralloc(
274364
::Type{A}, structure, ::Val{istemp}, buffer::BufferAllocator
275365
) where {A <: AbstractArray, istemp}
276-
if istemp
277-
T = eltype(A)
278-
offset = buffer.offset + allocation_size(T, structure)
279-
sizehint!(buffer, offset)
280-
281-
# grow buffer if empty
282-
isempty(buffer) && resize!(buffer, buffer.max_offset)
283-
284-
# Use pointer if there is enough space
285-
if offset < length(buffer)
286-
ptr = convert(Ptr{T}, pointer(buffer, buffer.offset))
287-
buffer.offset = offset
288-
return Base.unsafe_wrap(Array, ptr, structure)
366+
AA = buffer_arraytype(A, buffer)
367+
if istemp && AA !== nothing
368+
T = eltype(AA)
369+
nbytes = allocation_size(T, structure)
370+
if !iszero(nbytes) # empty temporaries have no meaningful pointer
371+
alignment = max(Base.datatype_alignment(T), buffer_alignment(buffer))
372+
start = _alignup(buffer.offset, alignment)
373+
offset = start + nbytes
374+
sizehint!(buffer, offset)
375+
376+
# grow buffer if empty: this should never shrink the buffer, as that would
377+
# discard the size that was requested through `sizehint` or `resize!`
378+
if isempty(buffer) && buffer.max_offset > length(buffer)
379+
resize!(buffer, buffer.max_offset)
380+
end
381+
382+
# Use pointer if there is enough space
383+
if offset <= length(buffer)
384+
buffer.offset = offset
385+
return unsafe_buffer_wrap(AA, buffer, start, structure)
386+
end
289387
end
388+
389+
# Allocate in the same memory space as the buffer if it does not fit
390+
return AA(undef, structure)
290391
end
291392

292-
# Allocate default if not
393+
# Allocate default if the buffer cannot back this type of array
293394
return A(undef, structure)
294395
end
295396

‎test/allocator.jl‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ using LinearAlgebra
2727
@test buffer3 isa BufferAllocator{Vector{UInt8}}
2828
@test length(buffer3) >= 512
2929

30-
# sizehint! grows to next power-of-two elements (UInt8)
30+
# buffers smaller than a page are rounded up to a power of two (UInt8 elements)
3131
resize!(buffer, 3000)
3232
@test length(buffer) == 4096
3333
@test isempty(buffer)
@@ -50,6 +50,33 @@ using LinearAlgebra
5050
@test buffer.max_offset == 1024
5151
end
5252

53+
@testset "Buffer sizes" begin
54+
P = TensorOperations._pagesize()
55+
56+
# below a page, sizes are rounded up to a power of two
57+
@test length(BufferAllocator(; sizehint = 0)) == 0
58+
@test length(BufferAllocator(; sizehint = 100)) == 128
59+
@test length(BufferAllocator(; sizehint = P)) == P
60+
61+
# above a page, sizes are rounded up to a multiple of a page, and not all the way
62+
# up to the next power of two
63+
@test length(BufferAllocator(; sizehint = P + 1)) == 2P
64+
@test length(BufferAllocator(; sizehint = 10P + 1)) == 11P
65+
buffer = BufferAllocator(; sizehint = 4P + 123)
66+
@test length(buffer) == 5P
67+
resize!(buffer, 2^20 + 1)
68+
@test length(buffer) == cld(2^20 + 1, P) * P
69+
@test length(buffer) < 2^21
70+
71+
# sizes are normalized to `Int`, whatever integer type they are computed from:
72+
# the storage constructors do not accept e.g. the `Int32` that `Clong` is on Windows
73+
@test TensorOperations._pagesize() isa Int
74+
@test TensorOperations._buffersz(Int32(100)) === 128
75+
@test TensorOperations._buffersz(UInt(10P + 1)) === 11P
76+
@test length(BufferAllocator(; sizehint = Int32(100))) == 128
77+
@test length(BufferAllocator(; sizehint = UInt(100))) == 128
78+
end
79+
5380
@testset "Checkpoint and reset" begin
5481
buffer = BufferAllocator(sizehint = 128)
5582
L = length(buffer)

0 commit comments

Comments
 (0)