Skip to content
This repository has been archived by the owner on Nov 4, 2024. It is now read-only.

Commit

Permalink
refactor: move turbo into single function
Browse files Browse the repository at this point in the history
  • Loading branch information
avik-pal committed Jul 22, 2024
1 parent c958ead commit ac05170
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 19 deletions.
5 changes: 4 additions & 1 deletion src/api/activation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,7 @@ function _fast_activation!!(::Val{true}, σ::F, x::AbstractArray) where {F}
return _fast_activation(σ, x)
end

_fast_activation!!(::Val{false}, σ::F, x::AbstractArray) where {F} = _fast_activation!(σ, x)
function _fast_activation!!(::Val{false}, σ::F, x::AbstractArray) where {F}
_fast_activation!(σ, x)
return x
end
35 changes: 17 additions & 18 deletions src/impl/activation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,37 +19,36 @@ function __activation_gradient(Δ, out, act::F, x) where {F}
return broadcast(only_deriv, Δ, out, x)
end

function _fast_activation!(
::LoopedArrayOp, y::AbstractArray, σ::F, x::AbstractArray) where {F}
@turbo for I in eachindex(y, x)
@inbounds y[I] = σ(x[I])
end
end
function _fast_activation!(opmode, y::AbstractArray, σ::F, x::AbstractArray) where {F}
broadcast!(σ, y, x)
return
end

# Entry Points to the implementation
_fast_activation(::typeof(identity), x::AbstractArray) = x

@stable default_mode="disable" function _fast_activation::F, x::AbstractArray) where {F}
if internal_operation_mode(x) isa LoopedArrayOp
RT = Core.Compiler._return_type(σ, Tuple{eltype(x)})
y = similar(x, RT)
@turbo for I in eachindex(y, x)
@inbounds y[I] = σ(x[I])
end
return y
end
return broadcast(σ, x)
y = similar(x, Core.Compiler._return_type(σ, Tuple{eltype(x)}))
_fast_activation!(internal_operation_mode(x), y, σ, x)
return y
end

function CRC.rrule(cfg::RuleConfig{>:HasReverseMode}, ::typeof(_fast_activation),
σ::F, x::AbstractArray{T}) where {F, T}
return CRC.rrule_via_ad(cfg, broadcast, σ, x)
end

_fast_activation!(::typeof(identity), x::AbstractArray) = x
_fast_activation!(::typeof(identity), x::AbstractArray) = nothing

@stable default_mode="disable" function _fast_activation!::F, x::AbstractArray) where {F}
if internal_operation_mode(x) isa LoopedArrayOp
@turbo for I in eachindex(x)
@inbounds x[I] = σ(x[I])
end
return x
end
broadcast!(σ, x, x)
return x
_fast_activation!(internal_operation_mode(x), x, σ, x)
return nothing
end

# Define rrule for `fast_activation!!`
Expand Down

0 comments on commit ac05170

Please sign in to comment.