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 pad_packed_sequence method input requires_grad==True #8574

Merged
merged 6 commits into from
Jul 6, 2022
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
3 changes: 2 additions & 1 deletion python/oneflow/nn/utils/rnn.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,7 @@ def pad_packed_sequence(
device=sequence.data.device,
requires_grad=sequence.data.requires_grad,
)
padded_output = padded_output.clone()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

对了,我昨天突然想到这里不应该这么写,应该先判断一下 requires_grad 再 clone,否则的话在 requires_grad 为 False 时,会有一次多余的 memcpy 操作,有计算的浪费

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

好的,我再改下


# This will be modified at every iteration, but we reserve memory for it now.
tmp_view_size = output_size # == [-1, -1, *sequence.data.size()[1:]]
Expand Down Expand Up @@ -390,7 +391,7 @@ def pad_packed_sequence(
prev_batch_size = batch_size

if batch_first:
permute_dims = (1, 0)
permute_dims = [1, 0]
for i in range(2, padded_output.ndim):
permute_dims.append(i)
padded_output = padded_output.permute(permute_dims)
Expand Down
8 changes: 8 additions & 0 deletions python/oneflow/test/expensive/test_rnn_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ def _test_rnn_utils_pack_padded_sequence(test_case, device):
padded_inputs[0 : lengths[i], i : i + 1, :] = i + 1

inputs = flow.from_numpy(padded_inputs).to(device)
inputs.requires_grad = True
flow_res = flow_rnn_utils.pack_padded_sequence(inputs, lengths)

torch_inputs = torch.from_numpy(padded_inputs).to(device)
torch_inputs.requires_grad = True
torch_res = torch_rnn_utils.pack_padded_sequence(torch_inputs, lengths)

test_case.assertTrue(
Expand All @@ -70,6 +72,9 @@ def _test_rnn_utils_pack_padded_sequence(test_case, device):
flow_res, batch_first=False
)

torch_seq_unpacked.sum().backward()
flow_seq_unpacked.sum().backward()

test_case.assertTrue(
np.allclose(
torch_seq_unpacked.cpu().detach().numpy(),
Expand All @@ -85,6 +90,9 @@ def _test_rnn_utils_pack_padded_sequence(test_case, device):
atol=1e-8,
)
)
test_case.assertTrue(
np.allclose(inputs.grad.cpu().numpy(), torch_inputs.grad.cpu().numpy())
)


def _test_rnn_utils_pad_sequence(test_case, device):
Expand Down