Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve element type in stateless layers #554

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/layers/stateless.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@ using NNlib: logsoftmax, logσ

# Cost functions

mse(ŷ, y) = sum((ŷ .- y).^2)/length(y)
function mse(ŷ, y)
x = sum((ŷ .- y).^2)
return x/Tracker.tracked_eltype(x)(length(y))
end

function crossentropy(ŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)
-sum(y .* log.(ŷ) .* weight) / size(y, 2)
x = -sum(y .* log.(ŷ) .* weight)
return x/Tracker.tracked_eltype(x)(size(y, 2))
end

@deprecate logloss(x, y) crossentropy(x, y)

function logitcrossentropy(logŷ::AbstractVecOrMat, y::AbstractVecOrMat; weight = 1)
return -sum(y .* logsoftmax(logŷ) .* weight) / size(y, 2)
x = -sum(y .* logsoftmax(logŷ) .* weight)
return x/Tracker.tracked_eltype(x)(size(y, 2))
end

"""
Expand Down
5 changes: 5 additions & 0 deletions src/tracker/lib/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -494,3 +494,8 @@ if VERSION < v"1.1.0-DEV.548"
end
end
end

# Get the element type of an array or the element type of the inner array of a tracked array
tracked_eltype(x) = eltype(x)
tracked_eltype(x::TrackedArray) = eltype(data(x))
tracked_eltype(x::TrackedReal{T}) where T = T