|
| 1 | +# Heterogeneous computing |
| 2 | + |
| 3 | +Support for heterogeneous computing is currently being worked on. |
| 4 | + |
| 5 | +## The use of Adapt.jl |
| 6 | + |
| 7 | +[`Adapt.jl`](https://github.com/JuliaGPU/Adapt.jl) is a package in the JuliaGPU family that allows for |
| 8 | +the translation of nested data structures. The primary goal is to allow the substitution of `Array` |
| 9 | +at the storage leaves with a GPU array like `CuArray`. |
| 10 | + |
| 11 | +To facilitate this data structures must be parameterized, so instead of: |
| 12 | + |
| 13 | +```julia |
| 14 | +struct Container |
| 15 | + data::Array{Float64,2} |
| 16 | +end |
| 17 | +``` |
| 18 | + |
| 19 | +They must be written as: |
| 20 | + |
| 21 | +```julia |
| 22 | +struct Container{D<:AbstractArray} <: Trixi.AbstractContainer |
| 23 | + data::D |
| 24 | +end |
| 25 | +``` |
| 26 | + |
| 27 | +furthermore, we need to define a function that allows for the conversion of storage |
| 28 | +of our types: |
| 29 | + |
| 30 | +```julia |
| 31 | +function Adapt.adapt_structure(to, C::Container) |
| 32 | + return Container(adapt(to, C.data)) |
| 33 | +end |
| 34 | +``` |
| 35 | + |
| 36 | +or simply |
| 37 | + |
| 38 | +```julia |
| 39 | +Adapt.@adapt_structure(Container) |
| 40 | +``` |
| 41 | + |
| 42 | +additionally, we must define `Adapt.parent_type`. |
| 43 | + |
| 44 | +```julia |
| 45 | +function Adapt.parent_type(::Type{<:Container{D}}) where D |
| 46 | + return D |
| 47 | +end |
| 48 | +``` |
| 49 | + |
| 50 | +```julia-repl |
| 51 | +julia> C = Container(zeros(3)) |
| 52 | +Container{Vector{Float64}}([0.0, 0.0, 0.0]) |
| 53 | +
|
| 54 | +julia> Trixi.storage_type(C) |
| 55 | +Array |
| 56 | +
|
| 57 | +julia> using CUDA |
| 58 | +
|
| 59 | +julia> GPU_C = adapt(CuArray, C) |
| 60 | +Container{CuArray{Float64, 1, CUDA.DeviceMemory}}([0.0, 0.0, 0.0]) |
| 61 | +
|
| 62 | +julia> Trixi.storage_type(C) |
| 63 | +CuArray |
| 64 | +``` |
| 65 | + |
| 66 | +## Element-type conversion with `Trixi.trixi_adapt`. |
| 67 | + |
| 68 | +We can use Trixi.trixi_adapt to perform both an element-type and a storage-type adoption |
| 69 | + |
| 70 | +```julia-repl |
| 71 | +julia> C = Container(zeros(3)) |
| 72 | +Container{Vector{Float64}}([0.0, 0.0, 0.0]) |
| 73 | +
|
| 74 | +julia> Trixi.trixi_adapt(Array, Float32, C) |
| 75 | +Container{Vector{Float32}}(Float32[0.0, 0.0, 0.0]) |
| 76 | +
|
| 77 | +julia> Trixi.trixi_adapt(CuArray, Float32, C) |
| 78 | +Container{CuArray{Float32, 1, CUDA.DeviceMemory}}(Float32[0.0, 0.0, 0.0]) |
| 79 | +``` |
| 80 | + |
| 81 | +!!! note |
| 82 | + `adapt(Array{Float32}, C)` is tempting but will do the wrong thing in the presence of `StaticArrays`. |
0 commit comments