Shift right
×Move the target one position right, so position t sees only the tokens before it.
Why
The authors offset the output embeddings by one position. Together with the mask in the decoder’s self-attention, this ensures that the predictions for position i can depend only on the known outputs at positions less than i. Transformer paper §3.1, p. 3
- in
- [B batch, T target positions]
- out
- [B batch, T target positions]
The code shifts the embedded targets rather than the IDs (shift_left_3d pads a zero vector); the zero vector is what padding id 0 embeds to, so the result is the same. The function’s name says left; its docstring and its padding say right (common_layers.py 209–215).
Sources
In codecommon_layers.shift_left_3d(targets) · transformer.py 123
Direct evidence
shift_left_3d pads one position at the start and drops the last: the targets shifted right by one.
common_layers.py 209–215 ↗ · tensorflow/tensor2tensor @ 0c66117d4297
Excerpt
def shift_left_3d(x, pad_value=None):
"""Shift the second dimension of x right by one."""
if pad_value is None:
shifted_targets = tf.pad(x, [[0, 0], [1, 0], [0, 0]])[:, :-1, :]
else:
shifted_targets = tf.concat([pad_value, x], axis=1)[:, :-1, :]
return shifted_targetsThe decoder input is the embedded targets shifted right by one position, plus the timing signal; its self-attention bias is lower-triangular.
transformer.py 109–126 ↗ · tensorflow/tensor2tensor @ 0c66117d4297
Excerpt
def transformer_prepare_decoder(targets, hparams):
"""Prepare one shard of the model for the decoder.
Args:
targets: a Tensor.
hparams: run hyperparameters
Returns:
decoder_input: a Tensor, bottom of decoder stack
decoder_self_attention_bias: a Tensor, containing large negative values
to implement masked attention and possibly baises for diagonal alignments
"""
decoder_self_attention_bias = (
common_attention.attention_bias_lower_triangle(tf.shape(targets)[1]))
decoder_input = common_layers.shift_left_3d(targets)
if hparams.pos == "timing":
decoder_input = common_attention.add_timing_signal_1d(decoder_input)
return (decoder_input, decoder_self_attention_bias)