[SpeechEncoderDecoderModel] Fix bug in reshaping labels #16748
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently, the target
labels
are reshaped using theview
method before being passed into the loss function:transformers/src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py
Line 560 in 06b4aac
The
view
method requires the Torch Tensor to be contiguous (cf https://pytorch.org/docs/stable/generated/torch.Tensor.view.html).There are certain operations that are commonly performed on the
labels
that might cause them to not be contiguous, for example slicing. For speech seq2seq models, if the bos token is appended in the tokenisation step, we cut the bos token by slicing thelabels
as follows:transformers/examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py
Lines 207 to 210 in 06b4aac
This slicing operation causes the
labels
to be not contiguous. Iflabels
are not contiguous, callinglabels.view(-1)
will throw a RuntimeError. This is demonstrated by the following code snippet:Output:
And similarly for the speech encoder-decoder model:
Output:
This PR follows the advice provided in the PyTorch docs by calling the
.reshape(...)
method instead of.view(...)
. Callingreshape
returnsview
if the shapes are compatible, and copies (equivalent to callingcontiguous()
) otherwise.