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

Allow 2d input if RNN order is BatchLastIndex #778

Merged
merged 6 commits into from
Jul 18, 2024
Merged
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
5 changes: 1 addition & 4 deletions src/layers/recurrent.jl
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,7 @@ end

_eachslice(x::AbstractArray, ::TimeLastIndex) = _eachslice(x, Val(ndims(x)))
_eachslice(x::AbstractArray, ::BatchLastIndex) = _eachslice(x, Val(ndims(x) - 1))
function _eachslice(::AbstractMatrix, ::BatchLastIndex)
error("`BatchLastIndex` not supported for AbstractMatrix. You probably want to use \
`TimeLastIndex`.")
end
_eachslice(x::AbstractMatrix, ::BatchLastIndex) = _eachslice(x, Val(ndims(x)))

@inline function (r::Recurrence)(x::AbstractArray, ps, st::NamedTuple)
return apply(r, _eachslice(x, r.ordering), ps, st)
Expand Down
21 changes: 10 additions & 11 deletions test/layers/recurrent_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,6 @@ end
@eval @test_gradients $__f $ps atol=1e-2 rtol=1e-2 gpu_testing=$ongpu
end

ordering isa BatchLastIndex && continue

# Batched Time Series without data batches
@testset "typeof(x): $(typeof(x))" for x in (
randn(rng, Float32, 3, 4) |> aType,
Expand All @@ -340,6 +338,16 @@ end
@test size(y) == (5,)
@test length(y_) == 4
@test all(x -> size(x) == (5,), y_)

if x isa AbstractMatrix && ordering isa BatchLastIndex
x2 = reshape(x, Val(3))

y2, _ = rnn(x2, ps, st)
@test y == vec(y2)

y2_, _ = rnn_seq(x2, ps, st)
@test all(x -> x[1] == vec(x[2]), zip(y_, y2_))
end

__f = p -> sum(first(rnn(x, p, st)))
@eval @test_gradients $__f $ps atol=1e-2 rtol=1e-2 gpu_testing=$ongpu
Expand All @@ -366,15 +374,6 @@ end
end
end

@testitem "RNN Error Checks" setup=[SharedTestSetup] tags=[:recurrent_layers] begin
rng = StableRNG(12345)

@testset "$mode" for (mode, aType, device, ongpu) in MODES
x = randn(rng, 2, 3) |> aType
@test_throws ErrorException Lux._eachslice(x, BatchLastIndex())
end
end

@testitem "Bidirectional" timeout=3000 setup=[SharedTestSetup] tags=[:recurrent_layers] begin
rng = StableRNG(12345)

Expand Down
Loading