TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Tokenizers in Practice: Special Tokens, Offsets and Padding

Tokenizers in Practice: Special Tokens, Offsets and Padding

The previous lessons built the core of three tokenizers: BPE merges, WordPiece's longest match, Unigram's Viterbi. A production tokenizer wraps that core in a pipeline, and most tokenizer bugs in real projects come from the wrapper, not the core: a missing [SEP], padding on the wrong side, a truncated answer, entity labels shifted by one subword, a cost estimate made with the wrong tokenizer.

A Hugging Face fast tokenizer (Rust, from the tokenizers library) runs five stages:

  1. Normaliser: Unicode normalisation, lower-casing, accent stripping (BERT uncased), or nothing (GPT-2).
  2. Pre-tokeniser: splits into words, on whitespace and punctuation (BERT), with the GPT-2 regex and the byte alias table (GPT-2), or not at all (SentencePiece).
  3. Model: BPE, WordPiece or Unigram, as in the last two lessons.
  4. Post-processor: adds special tokens and builds token_type_ids.
  5. Decoder: turns ids back into text (## removal, byte decoding, ▁ to space).

Along the way it records, for every token, which characters of the original text it came from, so every result can be mapped back to the input. This lesson walks through what each stage means for your code. The examples are recorded with BERT's and GPT-2's real tokenizers; the first one builds the two key mechanisms, offsets and padding, from scratch and runs in the browser.

Offsets and padding from scratch

python · try it yourself
import re

def tokenize_with_offsets(text):
    """A regex tokenizer that also returns each token's (start, end) characters, like offset_mapping."""
    return [(m.group(), (m.start(), m.end())) for m in re.finditer(r"\w+|[^\w\s]", text)]

def collate(batch_ids, pad_id, side="right"):
    """Pad a list of id lists to one length; return ids, attention mask and position ids."""
    n = max(len(x) for x in batch_ids)
    ids, mask, pos = [], [], []
    for x in batch_ids:
        pad = n - len(x)
        if side == "right":
            ids.append(x + [pad_id] * pad); mask.append([1] * len(x) + [0] * pad)
            pos.append(list(range(len(x))) + [0] * pad)
        else:
            ids.append([pad_id] * pad + x); mask.append([0] * pad + [1] * len(x))
            pos.append([0] * pad + list(range(len(x))))
    return ids, mask, pos

text = "Bike #42 won't unlock in Graz."
toks = tokenize_with_offsets(text)
print(toks)
span = (25, 29)                                    # the annotated location "Graz"
print("tokens inside the span:", [t for t, (s, e) in toks if s >= span[0] and e <= span[1]], "->", text[slice(*span)])

vocab = {t: i for i, t in enumerate(["<pad>", "<bos>"] + sorted({t for t, _ in toks}))}
a = [vocab["<bos>"]] + [vocab[t] for t, _ in toks[:3]]
b = [vocab["<bos>"]] + [vocab[t] for t, _ in toks]
for side in ("right", "left"):
    ids, mask, pos = collate([a, b], vocab["<pad>"], side)
    print(f"{side:5s} ids {ids[0]} mask {mask[0]} positions {pos[0]} | last real token of row 0 at index",
          max(i for i, m in enumerate(mask[0]) if m))
[('Bike', (0, 4)), ('#', (5, 6)), ('42', (6, 8)), ('won', (9, 12)), ("'", (12, 13)), ('t', (13, 14)), ('unlock', (15, 21)), ('in', (22, 24)), ('Graz', (25, 29)), ('.', (29, 30))]
tokens inside the span: ['Graz'] -> Graz
right ids [1, 6, 2, 5, 0, 0, 0, 0, 0, 0, 0] mask [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0] positions [0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0] | last real token of row 0 at index 3
left  ids [0, 0, 0, 0, 0, 0, 0, 1, 6, 2, 5] mask [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1] positions [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3] | last real token of row 0 at index 10

Two ideas to keep from this. Offsets: if a tokenizer returns each token's (start, end) character span, an annotation given in characters ("Graz" is characters 25 to 29) can be matched to tokens and a prediction on tokens can be mapped back to the text, whatever the tokenizer did to the string in between. Padding: a batch must be rectangular, so shorter sequences get <pad> ids, and the attention mask (1 = real, 0 = padding) tells the model to ignore them. The side matters: with right padding, the last real token of row 0 is at index 3; with left padding, it is at the last index, 10, as in every other row. Position ids must count only real tokens, so they restart after left padding.

Special tokens

Models are pretrained with special tokens in fixed places, and fine-tuning or inference must put them in the same places.

python · try it yourself
from transformers import AutoTokenizer

bert = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
gpt2 = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
print("BERT special tokens:", {k: v for k, v in bert.special_tokens_map.items()})
print("  ids:", bert.convert_tokens_to_ids(["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"]))
enc = bert("Where is the station?", "Next to the harbour.")
print("pair:", bert.convert_ids_to_tokens(enc.input_ids))
print("token_type_ids:", enc.token_type_ids)
print("special_tokens_mask:", bert("Next to the harbour.", return_special_tokens_mask=True).special_tokens_mask)
print("GPT-2 special tokens:", gpt2.special_tokens_map, "| pad token:", gpt2.pad_token)
print("GPT-2 adds nothing:", gpt2.convert_ids_to_tokens(gpt2("Next to the harbour.").input_ids))
BERT special tokens: {'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]', 'cls_token': '[CLS]', 'mask_token': '[MASK]'}
  ids: [0, 100, 101, 102, 103]
pair: ['[CLS]', 'where', 'is', 'the', 'station', '?', '[SEP]', 'next', 'to', 'the', 'harbour', '.', '[SEP]']
token_type_ids: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
special_tokens_mask: [1, 0, 0, 0, 0, 0, 1]
GPT-2 special tokens: {'bos_token': '<|endoftext|>', 'eos_token': '<|endoftext|>', 'unk_token': '<|endoftext|>'} | pad token: None
GPT-2 adds nothing: ['Next', 'Ġto', 'Ġthe', 'Ġharbour', '.']

BERT's post-processor wraps one text as [CLS] text [SEP] and a pair as [CLS] a [SEP] b [SEP], with token_type_ids 0 for the first segment and 1 for the second (BERT's next-sentence-prediction pretraining used pairs; question answering and cross-encoders still do). [CLS] is the position whose final vector feeds a sequence classifier, [MASK] is the token masked-language-model pretraining hides, and [PAD] is id 0. special_tokens_mask marks the added tokens so code can skip them.

GPT-2 is different: its only special token is <|endoftext|>, which serves as BOS, EOS and UNK, the tokenizer adds nothing by default, and there is no pad token. Many decoder models behave like this; others add a BOS token (<s> in Llama 2) automatically. Chat models add more special tokens for roles and turns, written by a chat template (Instruction Tuning and Chat Templates). Always check tok("x").input_ids once for a new model: a double BOS or a missing EOS in fine-tuning data is a silent bug.

Padding side and generation

For an encoder (BERT), padding goes on the right and the attention mask handles it. For batched generation with a decoder, the next token is predicted from the logits at the last position, so every row must end with a real token: pad on the left. The example measures it with GPT-2's tokenizer and the tiny random-weight GPT-2 (its predictions are noise, but logits are logits: they must not depend on what else is in the batch).

python · try it yourself
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from transformers.utils import logging
logging.set_verbosity_error()

tok = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
model = AutoModelForCausalLM.from_pretrained("sshleifer/tiny-gpt2").eval()
tok.pad_token = tok.eos_token                      # GPT-2 has no pad token; reuse <|endoftext|>
prompts = ["The shop opens at", "Mira replaced the worn brake pads on the"]

for side in ["right", "left"]:
    tok.padding_side = side
    batch = tok(prompts, padding=True, return_tensors="pt")
    print(f"{side} padding: ids[0] = {batch.input_ids[0].tolist()}")
    print(f"   attention_mask[0] = {batch.attention_mask[0].tolist()}")
    print("   last position holds:", [tok.convert_ids_to_tokens(int(i)) for i in batch.input_ids[:, -1]])

def next_logits(side, positions):                  # logits for prompt 0's next token, computed in a batch
    tok.padding_side = side
    batch = tok(prompts, padding=True, return_tensors="pt")
    pos = (batch.attention_mask.cumsum(1) - 1).clamp(min=0) if positions else None
    return model(**batch, position_ids=pos).logits[0, -1], batch

with torch.no_grad():
    alone = model(**tok(prompts[0], return_tensors="pt")).logits[0, -1]
    for side, positions in [("right", False), ("left", False), ("left", True)]:
        logits, batch = next_logits(side, positions)
        print(f"{side} padding, position_ids from the mask: {positions!s:5s} -> max |difference| from the",
              f"prompt alone: {(logits - alone).abs().max().item():.4f}")
out = model.generate(**batch, max_new_tokens=3, do_sample=False, pad_token_id=tok.pad_token_id)
print("generate output shape:", tuple(out.shape), "= 2 prompts x (", batch.input_ids.shape[1], "+ 3 new tokens )")
right padding: ids[0] = [464, 6128, 9808, 379, 50256, 50256, 50256, 50256, 50256]
   attention_mask[0] = [1, 1, 1, 1, 0, 0, 0, 0, 0]
   last position holds: ['<|endoftext|>', 'Ġthe']
left padding: ids[0] = [50256, 50256, 50256, 50256, 50256, 464, 6128, 9808, 379]
   attention_mask[0] = [0, 0, 0, 0, 0, 1, 1, 1, 1]
   last position holds: ['Ġat', 'Ġthe']
right padding, position_ids from the mask: False -> max |difference| from the prompt alone: 0.2173
left padding, position_ids from the mask: False -> max |difference| from the prompt alone: 0.0098
left padding, position_ids from the mask: True  -> max |difference| from the prompt alone: 0.0000
generate output shape: (2, 12) = 2 prompts x ( 9 + 3 new tokens )

With right padding, the last position of the short prompt holds <|endoftext|> padding, and its logits differ from those of the prompt alone by up to 0.2173. With left padding the last position is "at", but the logits still differ by 0.0098: the model's position embeddings counted the padding. Only with position_ids computed from the attention mask (cumulative sum minus 1) does the batched result equal the unbatched one. generate does this for you when you pass the attention mask, which is one more reason to always pass it. The rules: tok.pad_token = tok.eos_token if the model has no pad token, padding_side="left" for generation, and right padding (the default) for training a causal LM with a loss mask.

Truncation, stride and overflowing tokens

A model has a maximum length (512 tokens for BERT). Longer inputs are cut, and what is cut is lost. For classification that may be acceptable; for extractive question answering or NER on long documents it is not. The fix is to split the document into overlapping windows: stride is the number of tokens repeated between consecutive windows, so an answer or entity cut at the end of one window appears whole in the next.

python · try it yourself
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
doc = ("Return the bike at any station. Push it into a free dock until the light turns green and you hear "
       "a beep. If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.")
print("whole document:", len(tok(doc).input_ids), "tokens")
enc = tok(doc, max_length=24, truncation=True, stride=6, return_overflowing_tokens=True,
          return_offsets_mapping=True)
print("chunks:", len(enc.input_ids), "| from document:", enc.overflow_to_sample_mapping)
for ids, offs in zip(enc.input_ids, enc.offset_mapping):
    real = [o for o in offs if o != (0, 0)]       # special tokens have the offset (0, 0)
    start, end = real[0][0], real[-1][1]
    print(f"  {len(ids)} tokens, characters {start:3d}-{end:3d}: {doc[start:end][:40]!r}...")
first, second = enc.input_ids[0], enc.input_ids[1]
print("overlap:", tok.convert_ids_to_tokens(second[1:7]), "== end of chunk 1:",
      tok.convert_ids_to_tokens(first[-7:-1]) == tok.convert_ids_to_tokens(second[1:7]))

q = "What happens when the station is full?"
pair = tok(q, doc, max_length=32, truncation="only_second")
print("question + document, truncation='only_second':", len(pair.input_ids), "tokens, question kept whole:",
      tok.decode(pair.input_ids).startswith("[CLS] " + q.lower()))

# label alignment for NER: character spans -> one label per token
text = "Marek Berger fixed a derailleur at Norvik Cycles in Tampere."
entities = [(0, 12, "PER"), (35, 48, "ORG"), (52, 59, "LOC")]     # character spans from an annotator
print([text[s:e] for s, e, _ in entities])

enc = tok(text, return_offsets_mapping=True)
tokens = enc.tokens()
labels = []
for (s, e), w, prev_w in zip(enc.offset_mapping, enc.word_ids(), [None] + enc.word_ids()[:-1]):
    if w is None:
        labels.append("-100")                      # special token: ignored by the loss
        continue
    tag = "O"
    for es, ee, lab in entities:
        if s >= es and e <= ee:
            tag = ("B-" if s == es else "I-") + lab
    labels.append(tag if w != prev_w else "-100")  # only the first subword of a word is labelled
for t, o, w, l in zip(tokens, enc.offset_mapping, enc.word_ids(), labels):
    print(f"{t:12s} {str(o):9s} word {str(w):4s} {l}")
whole document: 48 tokens
chunks: 3 | from document: [0, 0, 0]
  24 tokens, characters   0- 99: 'Return the bike at any station. Push it '...
  24 tokens, characters  73-166: 'turns green and you hear a beep. If a st'...
  16 tokens, characters 132-203: 'app shows the nearest station with free '...
overlap: ['turns', 'green', 'and', 'you', 'hear', 'a'] == end of chunk 1: True
question + document, truncation='only_second': 32 tokens, question kept whole: True
['Marek Berger', 'Norvik Cycles', 'Tampere']
[CLS]        (0, 0)    word None -100
marek        (0, 5)    word 0    B-PER
berger       (6, 12)   word 1    I-PER
fixed        (13, 18)  word 2    O
a            (19, 20)  word 3    O
der          (21, 24)  word 4    O
##ail        (24, 27)  word 4    -100
##le         (27, 29)  word 4    -100
##ur         (29, 31)  word 4    -100
at           (32, 34)  word 5    O
nor          (35, 38)  word 6    B-ORG
##vik        (38, 41)  word 6    -100
cycles       (42, 48)  word 7    I-ORG
in           (49, 51)  word 8    O
tam          (52, 55)  word 9    B-LOC
##per        (55, 58)  word 9    -100
##e          (58, 59)  word 9    -100
.            (59, 60)  word 10   O
[SEP]        (0, 0)    word None -100

The 48-token document becomes 3 windows of at most 24 tokens (22 text tokens plus [CLS] and [SEP]), and 6 tokens are repeated at each boundary ("turns green and you hear a"). overflow_to_sample_mapping says which input each window came from, which matters when a batch of documents is split; offset_mapping gives each window's character range, so predictions on windows can be put back together on the original text. For a question and a document, truncation="only_second" cuts only the document and keeps the question whole. The windows used in RAG are usually cut by characters or sentences before tokenisation (Building a RAG Pipeline), but they must still be measured in tokens.

Offsets, word ids and label alignment

NER data comes as character spans or word-level tags, but the model predicts one label per subword token. offset_mapping and word_ids() connect the two. The standard recipe for training labels: the first subword of each word gets the word's tag, the other subwords and the special tokens get −100-100, the index that PyTorch's cross_entropy ignores. The second half of the example above applies it to a sentence with three annotated character spans.

"derailleur" is 4 tokens and "Tampere" 3; only the first token of each word carries a label. Special tokens have offset (0, 0) and word id None. At prediction time you reverse the mapping: take the prediction of each word's first token, then convert the BIO tags to character spans with the offsets, as in Named Entity Recognition. Token Classification: NER with BERT trains a model with exactly this alignment. (A variant labels every subword with I- continuation tags; either works if training and decoding agree.)

Decoding, adding tokens and counting tokens

The last example checks three things: whether decoding gives back the input, what adding a token to a vocabulary does to the model, and how many tokens a small RAG workload costs.

python · try it yourself
import torch
from transformers import AutoTokenizer, AutoModel
from transformers.utils import logging
logging.set_verbosity_error()

bert = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
gpt2 = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
s = "Naïve riders can't unlock Bike #42 (error E-17)."
for name, tok in [("BERT", bert), ("GPT-2", gpt2)]:
    back = tok.decode(tok(s, add_special_tokens=False).input_ids)
    print(f"{name:5s} decode: {back!r} | exact: {back == s}")

model = AutoModel.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
print("before:", bert.tokenize("the derailleur and the ebike"), "| embeddings", tuple(model.get_input_embeddings().weight.shape))
added = bert.add_tokens(["derailleur", "ebike"])
model.resize_token_embeddings(len(bert))
E = model.get_input_embeddings().weight.detach()
print("added", added, "->", bert.tokenize("the derailleur and the ebike"), "| embeddings", tuple(E.shape))
print("new ids:", bert.convert_tokens_to_ids(["derailleur", "ebike"]))
print("new rows identical:", torch.equal(E[30522], E[30523]),
      "| distance from the mean of the old rows:", round(float((E[30522] - E[:30522].mean(0)).norm()), 3),
      "| typical old row's distance:", round(float((E[:30522] - E[:30522].mean(0)).norm(dim=1).mean()), 3))

# counting tokens for cost: the 16 TAD Bikes help-centre documents
docs = [
    "Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
    "A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
    "To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
    "If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
    "Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
    "If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
    "Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
    "Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
    "Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
    "Helmets are not included in the rental, but we recommend wearing one on every ride.",
    "You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
    "Refunds for a ride that was charged twice are sent to the original card within five working days.",
    "A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
    "Our support team answers chat messages every day from 7 am to 10 pm.",
    "Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
    "Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
words = sum(len(d.split()) for d in docs)
n_gpt2 = sum(len(gpt2(d).input_ids) for d in docs)
n_bert = sum(len(bert(d, add_special_tokens=False).input_ids) for d in docs)
print(f"16 help-centre documents: {words} words, {n_gpt2} GPT-2 tokens, {n_bert} BERT tokens")
batch = gpt2(docs)                                 # a batch: one list of ids per document
print("longest:", max(len(x) for x in batch.input_ids), "tokens | shortest:", min(len(x) for x in batch.input_ids))

# a RAG prompt: instructions + 3 retrieved documents + question, answered in about 60 tokens
prompt = "Answer from the documents only.\n\n" + "\n".join(docs[4:7]) + "\n\nQuestion: where do I leave the bike?"
n_in, n_out = len(gpt2(prompt).input_ids), 60
price_in, price_out = 0.50, 1.50                   # hypothetical prices in dollars per million tokens
per_call = (n_in * price_in + n_out * price_out) / 1e6
print(f"one call: {n_in} input + {n_out} output tokens = ${per_call:.6f}; one million calls = ${per_call * 1e6:,.0f}")
BERT  decode: "naive riders can ' t unlock bike # 42 ( error e - 17 )." | exact: False
GPT-2 decode: "Naïve riders can't unlock Bike #42 (error E-17)." | exact: True
before: ['the', 'der', '##ail', '##le', '##ur', 'and', 'the', 'e', '##bi', '##ke'] | embeddings (30522, 128)
added 2 -> ['the', 'derailleur', 'and', 'the', 'ebike'] | embeddings (30524, 128)
new ids: [30522, 30523]
new rows identical: False | distance from the mean of the old rows: 0.0 | typical old row's distance: 0.594
16 help-centre documents: 292 words, 333 GPT-2 tokens, 332 BERT tokens
longest: 25 tokens | shortest: 15
one call: 89 input + 60 output tokens = $0.000134; one million calls = $134

Round trips. GPT-2's byte-level tokenizer gives back the exact input, accents, apostrophe and all. BERT's uncased tokenizer does not: lower-casing and accent stripping are lost, and its decoder cannot know where there were no spaces, so "can't" comes back as can ' t and "E-17" as e - 17. Never use BERT's decode output as text to show users; use the offsets to cut the original string instead.

Adding tokens. A domain word that the tokenizer splits into many pieces ("derailleur" was 4 WordPiece tokens) can be added with add_tokens, and resize_token_embeddings grows the embedding matrix from 30,522 to 30,524 rows. The new rows are not trained: Transformers initialises them at (almost exactly) the mean of the old embeddings (the distance from the mean is 0.0 here, while a typical existing row is 0.594 away), so the model sees an "average token" until fine-tuning teaches it the meaning. Adding tokens is worth it for frequent domain terms or new special tokens (chat roles, tool calls), and only together with fine-tuning. For a causal LM, remember that the output layer grows too (it is usually tied to the input embeddings).

Counting tokens for cost. API prices and context limits are in tokens, and every model family counts differently (Cost and Latency covers the user side), so count with the tokenizer of the model you will call. The 16 documents of the TAD Bikes help centre are 292 words, 333 GPT-2 tokens and 332 BERT tokens, about 1.14 tokens per word, typical for plain English. A RAG call with 3 retrieved documents and a short question is 89 input tokens; with 60 output tokens and the hypothetical prices of $0.50 and $1.50 per million input and output tokens, it costs $0.000134, or $134 per million calls. Real prompts with system instructions and chat history are often 10 to 50 times longer, and other languages need more tokens, so measure on real traffic.

For OpenAI models, tiktoken counts tokens locally. It downloads its encoding files on first use, so it is shown without running:

python
import tiktoken                                    # needs network access on first use; not run here

enc = tiktoken.get_encoding("o200k_base")          # the encoding of recent OpenAI models
print(len(enc.encode(prompt)))                     # count before sending; chat formats add a few tokens per message

Pitfalls

  • Loading the tokenizer of another checkpoint. Ids are only meaningful for the embedding matrix they were trained with. Always AutoTokenizer.from_pretrained the same name or folder as the model, and save both together.
  • No attention mask. Without it, padding takes part in attention. Pass the mask that the tokenizer returns, every time.
  • Right padding in batched generation. The model continues from a pad token. Use left padding and let generate build the positions from the mask.
  • Silent truncation. truncation=True cuts without warning. Log how many inputs were truncated, and use stride windows when the end of the document matters.
  • Labels on every subword, or none on special tokens. Mis-aligned labels train the model on the wrong targets without any error; check a few aligned examples by printing them as in the example.
  • Decoding to recover spans. Decoded text from a normalising tokenizer is not the original; use offset_mapping.
  • Adding tokens without fine-tuning. New tokens start as the average embedding and carry no meaning; the model also never saw them during pretraining.

Practice

  1. A BERT question-answering input has a 12-token question and a 600-token document. With max_length=384, truncation="only_second" and stride=128, roughly how many windows are produced?
  2. Why does GPT-2 need tok.pad_token = tok.eos_token before padding=True, and why is it harmless when the attention mask is passed?
  3. In the label alignment example, what would go wrong if every subword of "Tampere" were labelled B-LOC?
  4. A prompt is 1,500 tokens and the answer 300 tokens. At $3 per million input and $15 per million output tokens, what does one call cost?
  5. Write the condition that decides whether a token with offsets (s, e) lies inside an entity span (es, ee), and explain why the example uses s >= es and e <= ee rather than an overlap test.
Answers
  1. Each window holds 384−12−3=369384 - 12 - 3 = 369 document tokens (3 special tokens: [CLS] and two [SEP]) and advances by 369−128=241369 - 128 = 241. The first window covers document tokens 0 to 368, the second starts at 241 and reaches the end (600) within its 369 tokens. So 2 windows.
  2. Padding needs some id to fill with, and GPT-2 defines no pad token, so padding=True raises an error. With the attention mask at 0 on those positions, the model ignores them, so reusing <|endoftext|> does not matter. Without a mask (or in the loss, if labels are not masked) the padding would be read as real end-of-text tokens.
  3. The span conversion would read B-LOC B-LOC B-LOC as three one-token entities, "tam", "##per" and "##e", so the entity-level score would count 3 false positives and 1 false negative. If you label every subword, continuation subwords must get I-LOC.
  4. 1500⋅3/106+300⋅15/106=0.0045+0.0045=0.0091500 \cdot 3 / 10^6 + 300 \cdot 15 / 10^6 = 0.0045 + 0.0045 = 0.009 dollars, 0.9 cents per call.
  5. s >= es and e <= ee: the token lies completely inside the span. An overlap test (s < ee and e > es) would also label a token that only partly overlaps, which happens when the annotation boundary falls inside a token (for example an entity that ends in the middle of a word). Such cases should be reported, not silently labelled; they are a tokenisation and annotation mismatch.

Test yourself

How does BERT's tokenizer encode a pair of texts?

  1. a [SEP] b
  2. [CLS] a [SEP] b [SEP] with token_type_ids 0 for a and 1 for b
  3. <s> a </s> b </s>
  4. It concatenates them without special tokens

Why is left padding used for batched generation with a decoder-only model?

  1. It is faster
  2. The next token is predicted from the last position, which must be a real token in every row
  3. Right padding is not supported
  4. It saves memory

What does stride do together with return_overflowing_tokens=True?

  1. Skips every second token
  2. Repeats that many tokens between consecutive windows of a long input
  3. Sets the batch size
  4. Removes stop words

In the NER label alignment recipe, which label do the second and later subwords of a word get?

  1. The same B- tag
  2. O
  3. -100, ignored by the loss
  4. [PAD]

How are the embedding rows of newly added tokens initialised by resize_token_embeddings in the example?

  1. Copied from [UNK]
  2. At the mean of the existing embeddings
  3. As zeros
  4. From the subword pieces of the new word