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

Add shift-right method to T5 model #2131

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
22 changes: 22 additions & 0 deletions test/torchtext_unittest/models/t5_models_test_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,25 @@ def _train(model):

_train(model)
self.assertNotEqual(model.state_dict(), current_state_dict)

def test_shift_right(self) -> None:
from torchtext.models import T5Conf, T5Model

dummy_encoder_conf = T5Conf()
dummy_t5_encoder = T5Model(dummy_encoder_conf)
padding_idx = dummy_t5_encoder.padding_idx

valid_cases_input = [[[1, 2], [3, 4]], [[1]]]
valid_cases_expected = [[[padding_idx, 1], [padding_idx, 3]], [[padding_idx]]]

invalid_cases_input = [[0], [], [[]]]

for input_ids, expected in zip(valid_cases_input, valid_cases_expected):
input_ids = torch.Tensor(input_ids)
expected = torch.Tensor(expected)
self.assertEqual(dummy_t5_encoder._shift_right(input_ids), expected)

for input_ids in invalid_cases_input:
input_ids = torch.Tensor(input_ids)
with self.assertRaises(IndexError):
dummy_t5_encoder._shift_right(input_ids)
11 changes: 11 additions & 0 deletions torchtext/models/t5/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,17 @@ def _reorder_cache(self, past: List[PAST_KEY_VALUES_TYPE], beam_idx: Tensor) ->
reordered_decoder_past.append(reordered_layer_past_states)
return reordered_decoder_past

@torch.jit.export
def _shift_right(self, input_ids: Tensor) -> Tensor:
"""Shift all input sequences to the right"""
shifted_input_ids = torch.zeros_like(input_ids)
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()

# T5 implemention uses padding idx to start sequence.
shifted_input_ids[:, 0] = self.padding_idx

return shifted_input_ids

@torch.jit.export
def prepare_inputs_for_generation(
self,
Expand Down