|
| 1 | +## |
| 2 | +# Implements contextual dispatch through Cassette.jl |
| 3 | +# Goals: |
| 4 | +# - Rewrite common CPU functions to appropriate GPU intrinsics |
| 5 | +# |
| 6 | +# TODO: |
| 7 | +# - error (erf, ...) |
| 8 | +# - pow |
| 9 | +# - min, max |
| 10 | +# - mod, rem |
| 11 | +# - gamma |
| 12 | +# - bessel |
| 13 | +# - distributions |
| 14 | +# - unsorted |
| 15 | + |
| 16 | +using Cassette |
| 17 | + |
| 18 | +function transform(ctx, ref) |
| 19 | + CI = ref.code_info |
| 20 | + noinline = any(@nospecialize(x) -> |
| 21 | + Core.Compiler.isexpr(x, :meta) && |
| 22 | + x.args[1] == :noinline, |
| 23 | + CI.code) |
| 24 | + CI.inlineable = !noinline |
| 25 | + |
| 26 | + CI.ssavaluetypes = length(CI.code) |
| 27 | + # Core.Compiler.validate_code(CI) |
| 28 | + return CI |
| 29 | +end |
| 30 | + |
| 31 | +const InlinePass = Cassette.@pass transform |
| 32 | + |
| 33 | +Cassette.@context CUDACtx |
| 34 | +const cudactx = Cassette.disablehooks(CUDACtx(pass = InlinePass)) |
| 35 | + |
| 36 | +### |
| 37 | +# Cassette fixes |
| 38 | +### |
| 39 | + |
| 40 | +# kwfunc fix |
| 41 | +Cassette.overdub(::CUDACtx, ::typeof(Core.kwfunc), f) = return Core.kwfunc(f) |
| 42 | + |
| 43 | +# the functions below are marked `@pure` and by rewritting them we hide that from |
| 44 | +# inference so we leave them alone (see https://github.com/jrevels/Cassette.jl/issues/108). |
| 45 | +@inline Cassette.overdub(::CUDACtx, ::typeof(Base.isimmutable), x) = return Base.isimmutable(x) |
| 46 | +@inline Cassette.overdub(::CUDACtx, ::typeof(Base.isstructtype), t) = return Base.isstructtype(t) |
| 47 | +@inline Cassette.overdub(::CUDACtx, ::typeof(Base.isprimitivetype), t) = return Base.isprimitivetype(t) |
| 48 | +@inline Cassette.overdub(::CUDACtx, ::typeof(Base.isbitstype), t) = return Base.isbitstype(t) |
| 49 | +@inline Cassette.overdub(::CUDACtx, ::typeof(Base.isbits), x) = return Base.isbits(x) |
| 50 | + |
| 51 | +@inline Cassette.overdub(::CUDACtx, ::typeof(datatype_align), ::Type{T}) where {T} = datatype_align(T) |
| 52 | + |
| 53 | +### |
| 54 | +# Rewrite functions |
| 55 | +### |
| 56 | +Cassette.overdub(ctx::CUDACtx, ::typeof(isdevice)) = true |
| 57 | + |
| 58 | +# libdevice.jl |
| 59 | +for f in (:cos, :cospi, :sin, :sinpi, :tan, |
| 60 | + :acos, :asin, :atan, |
| 61 | + :cosh, :sinh, :tanh, |
| 62 | + :acosh, :asinh, :atanh, |
| 63 | + :log, :log10, :log1p, :log2, |
| 64 | + :exp, :exp2, :exp10, :expm1, :ldexp, |
| 65 | + :isfinite, :isinf, :isnan, |
| 66 | + :signbit, :abs, |
| 67 | + :sqrt, :cbrt, |
| 68 | + :ceil, :floor,) |
| 69 | + @eval function Cassette.overdub(ctx::CUDACtx, ::typeof(Base.$f), x::Union{Float32, Float64}) |
| 70 | + @Base._inline_meta |
| 71 | + return CUDAnative.$f(x) |
| 72 | + end |
| 73 | +end |
| 74 | + |
| 75 | +contextualize(f::F) where F = (args...) -> Cassette.overdub(cudactx, f, args...) |
0 commit comments