CLS and Register Token Sequence Length
Problem Statement
A ViT prepends a learnable [CLS] token and, in newer designs (DINOv2, "registers"), a few extra register tokens to the patch sequence before the transformer. Compute the final sequence length fed to the encoder.
Background
The transformer input length is
The CLS token contributes exactly one slot when present; register tokens add n_register more. These extra tokens carry no image content but occupy real positions in the attention matrix, so they count toward compute.
Your Task
Implement:
def sequence_length(rows, cols, use_cls=True, n_register=0):
Return the total sequence length as an int.
Input Format
- rows, cols (int): patch grid dimensions.
- use_cls (bool): whether a CLS token is prepended.
- n_register (int): number of register tokens.
Output Format
- A single int.
Sample
print(sequence_length(14, 14, True, 0))
Output:
197
Example
print(sequence_length(14, 14, True, 0))
197
- Calculate the number of image patch tokens by multiplying the grid dimensions: .
- Determine the contribution of the CLS token; since
use_clsis True, it adds exactly 1 slot to the sequence. - Add the number of register tokens; since
n_registeris 0, this adds 0 to the total. - Sum these components to find the total sequence length: .
- The final output is 197
Constraints
1 <= rows, cols <= 256,0 <= n_register <= 64- Add 1 only when
use_clsis true. - Return an int.