Batching and serving algorithms · Easy

Last Real Token Logits

Problem 41 of 50 · Python and NumPy

Problem

For each sequence in a padded batch, return the vocabulary-logit row at its greatest token position whose mask is true. A sequence with no true mask entry returns a zero vector of vocabulary width.

Masks may have left padding, right padding, or gaps. Counting true tokens does not identify the last valid index in the general case. Return shape B × V.

def last_token_logits(logits, mask):

Constraints

  • logits is B × T × V and mask is B × T booleans; dimensions are 1..16.
  • All logits are finite.
  • Inputs satisfy these constraints; invalid-input handling is not graded. Use only Python standard library and NumPy.

Examples

Example 1

Arguments: [
  [
    [
      [
        1,
        2
      ],
      [
        3,
        4
      ],
      [
        9,
        9
      ]
    ]
  ],
  [
    [
      true,
      true,
      false
    ]
  ]
]
Expected result: [
  [
    3,
    4
  ]
]

The last real token is at index 1, so select [3,4] rather than padded logits [9,9].

Example 2

Arguments: [
  [
    [
      [
        9,
        9
      ],
      [
        1,
        2
      ],
      [
        3,
        4
      ]
    ]
  ],
  [
    [
      false,
      true,
      true
    ]
  ]
]
Expected result: [
  [
    3,
    4
  ]
]

Despite left padding, the last true position is index 2, giving [3,4].

Sign in to solve this problem

Browse all coding problems · Learn the foundations