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

Fix PyTorch stateful RNN/LSTM gradient computation error resolves #20875 #20916

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
8 changes: 8 additions & 0 deletions keras/src/layers/rnn/rnn.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,14 @@ def inner_loop(self, sequences, initial_state, mask, training=False):
cell_kwargs["training"] = training

def step(inputs, states):
"""
Create new tensor copies when using PyTorch backend
with stateful=True. This prevents in-place modifications
that would otherwise break PyTorch's autograd functionality
by modifying tensors needed for gradient computation.
"""
if backend.backend() == "torch" and self.stateful:
states = tree.map_structure(ops.copy, states)
output, new_states = self.cell(inputs, states, **cell_kwargs)
if not tree.is_nested(new_states):
new_states = [new_states]
Expand Down
15 changes: 15 additions & 0 deletions keras/src/layers/rnn/rnn_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,4 +383,19 @@ def test_serialization(self):
layer = layers.RNN(OneStateRNNCell(2), return_sequences=False)
self.run_class_serialization_test(layer)

@pytest.mark.torch
def test_stateful_state_copying(self):
sequence = np.ones((1, 2, 3))
layer = layers.RNN(
TwoStatesRNNCell(2),
stateful=True,
return_state=True,
)
_, state1, state2 = layer(sequence)

self.assertIsNot(state1, layer.states[0])
self.assertIsNot(state2, layer.states[1])
self.assertAllClose(state1, layer.states[0])
self.assertAllClose(state2, layer.states[1])

# TODO: test masking