Build teacher-forcing decoder inputs

Why it matters T5 and BART training code builds decoder inputs exactly like this.

Seq2seq decoders are trained on the target shifted right by one, with a start token in front.

Write shift_right(labels, start_id, pad_id, ignore_id=-100). labels is (batch, time). Return an array of the same shape whose first column is start_id and whose other columns are labels[:, :-1], with any ignore_id values replaced by pad_id.

Signaturedef shift_right(labels, start_id, pad_id, ignore_id=-100)

Example

shift_right([[5, 6, -100]], 0, 1) gives [[0, 5, 6]].

Understand the idea

Encoder-decoder models are trained with teacher forcing: at each step the decoder is fed the true previous token and asked to predict the current one. So the decoder input is the target sequence shifted one place to the right, with a start token in front. Labels often use -100 to mark positions the loss should ignore, but -100 is not a real token id and must not reach the embedding table. Worked example: labels = [[7, 8, 9, -100, -100]], start_id 0, pad_id 1. Shift right: [0, 7, 8, 9, -100]. Replace -100 with pad: [[0, 7, 8, 9, 1]]. The last label is dropped, since nothing comes after it. Rule: out[:, 0] = start_id; out[:, 1:] = labels[:, :-1]; then set every out value equal to ignore_id to pad_id. Keep the same shape as labels and do not change labels in place. Used in: training T5, BART and other seq2seq models, and in the helper functions that build decoder_input_ids for them.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleshift_right([[5, 6, -100]], 0, 1)
  • Sample 2: ignore insideshift_right([[7, -100, -100, -100], [1, 2, 3, 4]], 9, 0)
  • Test 3: single stepshift_right([[3]], 2, 0)