Repository navigation
Expand file tree
/
Copy pathallocator.jl
More file actions
306 lines (254 loc) · 11.5 KB
/
Copy pathallocator.jl
File metadata and controls
306 lines (254 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# ------------------------------------------------------------------------------------------
# Allocator backends
# ------------------------------------------------------------------------------------------
"""
DefaultAllocator()
Default allocator for tensor operations if no explicit allocator is specified. This will
just use the standard constructor for the tensor type, and thus probably uses Julia's
default memory manager.
"""
struct DefaultAllocator end
"""
CUDAAllocator{Mout,Min,Mtemp}()
Allocator that uses the CUDA memory manager and will thus allocate `CuArray` instances. The
parameters `Min`, `Mout`, `Mtemp` can be any of the CUDA.jl memory types, i.e.
`CUDA.DeviceMemory`, `CUDA.UnifiedMemory` or `CUDA.HostMemory`.
* `Mout` is used to determine how to deal with output tensors; with `Mout=CUDA.HostMemory`
or `Mout=CUDA.UnifiedMemory` the CUDA runtime will ensure that the data is also available
at in the host memory, and can thus be converted back to normal arrays using
`unsafe_wrap(Array, outputtensor)`. If `Mout=CUDA.DeviceMemory` the data will remain on
the GPU, untill an explict `Array(outputtensor)` is called.
* `Min` is used to determine how to deal with input tensors; with `Min=CUDA.HostMemory` the
CUDA runtime will itself take care of transferring the data to the GPU, otherwise it is
copied explicitly.
* `Mtemp` is used to allocate space for temporary tensors; it defaults to
`CUDA.default_memory` which is `CUDA.DeviceMemory`. Only if many or huge temporary tensors
are expected could it be useful to choose `CUDA.UnifiedMemory`.
"""
struct CUDAAllocator{Mout, Min, Mtemp} end
"""
ManualAllocator()
Allocator that bypasses Julia's memory management for temporary tensors by leveraging `Libc.malloc`
and `Libc.free` directly. This can be useful for reducing the pressure on the garbage collector.
This backend will allocate using `DefaultAllocator` for output tensors that escape the `@tensor`
block, which will thus still be managed using Julia's GC. The other tensors will be backed by
`PtrArray` instances, from `PtrArrays.jl`, thus requiring compatibility with that interface.
"""
struct ManualAllocator end
"""
BufferAllocator(; sizehint = 0)
Allocator that uses a pre-allocated buffer for storing temporary tensors.
When the buffer is full, the allocator falls back on Julia's default allocation mechanism
to create temporary tensors, but keeps track of how much additional memory is required.
When the buffer is fully reset, the buffer is automatically resized to ensure subsequent
contractions will now fit in the buffer.
!!! warning
This allocator is **not** thread-safe, and it is the user's responsibility to avoid running
the same allocator on concurrent jobs. For concurrent usage, it is recommended to either
manually use a separate buffer per task, or leverage Bumper.jl through [`@butensor`](@ref)
instead.
"""
mutable struct BufferAllocator{Storage}
buffer::Storage
offset::UInt
max_offset::UInt
function BufferAllocator{Storage}(; sizehint::Integer = 0) where {Storage}
T = eltype(Storage)
(isbitstype(T) && sizeof(T) == 1) ||
throw(ArgumentError("Buffer should have elements that take up a single byte."))
n = _buffersz(sizehint)
return new{Storage}(Storage(undef, n), 0, 0)
end
end
"""
ReactantAllocator{IsTraced}
Allocator for [Reactant](https://github.com/EnzymeAD/Reactant.jl)-backed arrays.
If `IsTraced=true`, it is supposed that [Reactant](https://github.com/EnzymeAD/Reactant.jl)
is tracing the code and thus, it will return a `TracedRArray`. Otherwise, it will allocate a
`ConcreteRArray`.
"""
struct ReactantAllocator{IsTraced} end
const DefaultStorageType = @static isdefined(Core, :Memory) ? Memory{UInt8} : Vector{UInt8}
BufferAllocator(; kwargs...) = BufferAllocator{DefaultStorageType}(; kwargs...)
# allocate buffers in sizes that are powers of 2
_buffersz(x::Integer) = iszero(x) ? x : Base.nextpow(2, x)
# ------------------------------------------------------------------------------------------
# Generic implementation
# ------------------------------------------------------------------------------------------
# function that mimicks the operations that are applied to the scalars during contraction
tensorop(args...) = +(*(args...), *(args...))
"""
promote_contract(args...)
Promote the scalar types of a tensor contraction to a common type.
"""
promote_contract(args...) = Base.promote_op(tensorop, args...)
"""
promote_add(args...)
Promote the scalar types of a tensor addition to a common type.
"""
promote_add(args...) = Base.promote_op(+, args...)
"""
tensoralloc_add(TC, A, pA, conjA, [istemp=Val(false), allocator])
Allocate a tensor `C` of scalar type `TC` that would be the result of
`tensoradd!(C, A, pA, conjA)`
The `istemp` argument is used to indicate that a tensor wlil not be used after the `@tensor`
block, and thus will be followed by an explicit call to `tensorfree!`. The `allocator` can be
used to implement different allocation strategies.
See also [`tensoralloc`](@ref) and [`tensorfree!`](@ref).
"""
function tensoralloc_add(
TC, A, pA::Index2Tuple, conjA::Bool, istemp::Val = Val(false),
allocator = DefaultAllocator()
)
ttype = tensoradd_type(TC, A, pA, conjA)
structure = tensoradd_structure(A, pA, conjA)
return tensoralloc(ttype, structure, istemp, allocator)
end
"""
tensoralloc_contract(TC, A, pA, conjA, B, pB, conjB, pAB, [istemp=Val(false), allocator])
Allocate a tensor `C` of scalar type `TC` that would be the result of
`tensorcontract!(C, A, pA, conjA, B, pB, conjB, pAB)`
The `istemp` argument is used to indicate that a tensor wlil not be used after the `@tensor`
block, and thus will be followed by an explicit call to `tensorfree!`. The `allocator` can be
used to implement different allocation strategies.
See also [`tensoralloc`](@ref) and [`tensorfree!`](@ref).
"""
function tensoralloc_contract(
TC,
A, pA::Index2Tuple, conjA::Bool,
B, pB::Index2Tuple, conjB::Bool,
pAB::Index2Tuple, istemp::Val = Val(false),
allocator = DefaultAllocator()
)
ttype = tensorcontract_type(TC, A, pA, conjA, B, pB, conjB, pAB)
structure = tensorcontract_structure(A, pA, conjA, B, pB, conjB, pAB)
return tensoralloc(ttype, structure, istemp, allocator)
end
# ------------------------------------------------------------------------------------------
# AbstractArray implementation
# ------------------------------------------------------------------------------------------
tensorstructure(A::AbstractArray) = size(A)
tensorstructure(A::AbstractArray, iA::Int, conjA::Bool) = size(A, iA)
function tensoradd_type(TC, A::Array, pA::Index2Tuple, conjA::Bool)
return Array{TC, sum(length.(pA))}
end
function tensoradd_type(TC, A::AbstractArray, pA::Index2Tuple, conjA::Bool)
return Array{TC, sum(length.(pA))}
end
function tensoradd_type(TC, A::SubArray, pA::Index2Tuple, conjA::Bool)
return tensoradd_type(TC, A.parent, pA, conjA)
end
function tensoradd_type(TC, A::Base.ReshapedArray, pA::Index2Tuple, conjA::Bool)
return tensoradd_type(TC, A.parent, pA, conjA)
end
function tensoradd_type(TC, A::Base.PermutedDimsArray, pA::Index2Tuple, conjA::Bool)
return tensoradd_type(TC, A.parent, pA, conjA)
end
function tensoradd_type(TC, A::StridedView, pA::Index2Tuple, conjA::Bool)
return tensoradd_type(TC, parent(A), pA, conjA)
end
function tensoradd_structure(A::AbstractArray, pA::Index2Tuple, conjA::Bool)
return size.(Ref(A), linearize(pA))
end
function tensorcontract_type(
TC,
A::AbstractArray, pA::Index2Tuple, conjA::Bool,
B::AbstractArray, pB::Index2Tuple, conjB::Bool,
pAB::Index2Tuple
)
T1 = tensoradd_type(TC, A, pAB, conjA)
T2 = tensoradd_type(TC, B, pAB, conjB)
if T1 == T2
return T1
else
error("incompatible types for tensorcontract!: $T1 and $T2")
end
end
function tensorcontract_structure(
A::AbstractArray, pA::Index2Tuple, conjA::Bool,
B::AbstractArray, pB::Index2Tuple, conjB::Bool,
pAB::Index2Tuple
)
return let lA = length(pA[1])
map(n -> n <= lA ? size(A, pA[1][n]) : size(B, pB[2][n - lA]), linearize(pAB))
end
end
function tensoralloc(ttype, structure, ::Val = Val(false), allocator = DefaultAllocator())
C = ttype(undef, structure)
# fix an issue with undefined references for strided arrays
if !isbitstype(scalartype(ttype))
C = zerovector!!(C)
end
return C
end
tensorfree!(C, allocator = DefaultAllocator()) = nothing
# ------------------------------------------------------------------------------------------
# ManualAllocator implementation
# ------------------------------------------------------------------------------------------
function tensoralloc(
::Type{A}, structure, ::Val{istemp}, ::ManualAllocator
) where {A <: AbstractArray, istemp}
if istemp
return malloc(eltype(A), structure...)
else
return tensoralloc(A, structure, Val(istemp))
end
end
function tensorfree!(C::PtrArray, ::ManualAllocator)
free(C)
return nothing
end
# ------------------------------------------------------------------------------------------
# BufferAllocator implementation
# ------------------------------------------------------------------------------------------
# length in bytes
Base.length(buffer::BufferAllocator) = length(buffer.buffer)
Base.isempty(buffer::BufferAllocator) = iszero(buffer.offset)
Base.pointer(buffer::BufferAllocator) = pointer(buffer.buffer)
Base.pointer(buffer::BufferAllocator, offset) = pointer(buffer) + offset
Base.empty!(buffer::BufferAllocator) = (buffer.offset = 0; buffer)
function Base.resize!(buffer::BufferAllocator, n::Integer)
isempty(buffer) || error("Cannot resize a buffer that still contains elements")
n = _buffersz(n)
n == length(buffer) || (buffer.buffer = similar(buffer.buffer, n))
return buffer
end
function Base.resize!(buffer::BufferAllocator{<:Vector}, n::Integer)
isempty(buffer) || error("Cannot resize a buffer that still contains elements")
n = _buffersz(n)
n == length(buffer) || resize!(buffer.buffer, n)
return buffer
end
function Base.sizehint!(buffer::BufferAllocator, n::Integer; shrink::Bool = false)
buffer.max_offset = shrink ? n : max(buffer.max_offset, n)
return buffer
end
# how many bytes should be reserved
allocation_size(::Type{T}, structure::Base.Dims) where {T} = prod(structure) * sizeof(T)
allocation_size(::Type{T}, structure::Int) where {T} = structure * sizeof(T)
function tensoralloc(
::Type{A}, structure, ::Val{istemp}, buffer::BufferAllocator
) where {A <: AbstractArray, istemp}
if istemp
T = eltype(A)
offset = buffer.offset + allocation_size(T, structure)
sizehint!(buffer, offset)
# grow buffer if empty
isempty(buffer) && resize!(buffer, buffer.max_offset)
# Use pointer if there is enough space
if offset < length(buffer)
ptr = convert(Ptr{T}, pointer(buffer, buffer.offset))
buffer.offset = offset
return Base.unsafe_wrap(Array, ptr, structure)
end
end
# Allocate default if not
return A(undef, structure)
end
allocator_checkpoint!(buffer::BufferAllocator) = buffer.offset
function allocator_reset!(buffer::BufferAllocator, checkpoint)
checkpoint ≤ buffer.offset ||
throw(ArgumentError("Invalid checkpoint: `allocator_reset!` has to be called in reverse order on saved checkpoints"))
buffer.offset = checkpoint
return buffer
end