Skip to content
mentoor

Topic 1 of 6 · 4 min read

Character tokenizer and training batches

Goal: Given a text corpus, write encode and decode functions and a batch function that returns inputs and next-token targets with the right tensor shapes.

A language model only sees integers, so the first job is a reversible map from text to ids, and the second is to cut that id stream into inputs and "next token" targets.

Check yourself · 1 of 3

A character tokenizer is built for a corpus that contains 65 different characters. What is vocab_size?

Choose one answer

Why it matters

Every bug in the later steps is harder to find if the data is wrong. A shifted target, a validation split that leaks into training, or a batch with the wrong shape will not crash. The model will train, and the loss will look plausible. You check the data pipeline first and by hand.

How to do it

Start with one text file, for example the complete works of Shakespeare (about 1 MB). A character tokenizer is the simplest vocabulary there is.

  1. Build the vocabulary. Take the sorted set of characters in the text. For Shakespeare that is 65 characters, so vocab_size = 65.
  2. Write encode and decode. encode maps a string to a list of ids. decode maps ids back. Test the round trip: decode(encode(s)) == s.
  3. Convert the whole text to one long tensor of ids, dtype torch.long.
  4. Split by position, not at random. Use the first 90% for training and the last 10% for validation. Validation text must be text the model never trained on.
  5. Cut random blocks. Pick batch_size random start offsets. For each, the input x is block_size ids and the target y is the same window moved one position to the right.

The shift is the whole idea. At every position the model is asked: given the tokens so far, what comes next? One block of length 8 therefore holds 8 training examples at once: from context of length 1 up to context of length 8.

Before and after

A weak version uses the same tensor for inputs and targets:

def get_batch(data, block_size, batch_size):
    ix = torch.randint(len(data) - block_size, (batch_size,))
    x = torch.stack([data[i:i + block_size] for i in ix])
    y = x.clone()  # bug: the target is the input
    return x, y

The model learns to copy its input, loss drops fast, and generation is garbage. The fixed version shifts by one:

    y = torch.stack([data[i + 1:i + block_size + 1] for i in ix])

Both x and y now have shape (batch_size, block_size). The - block_size in randint keeps the + 1 slice inside the data.

What goes wrong

  • Off-by-one targets. The copy bug above, or a shift in the wrong direction. Print one x row and its y row decoded back to text and read them side by side.
  • Leaky validation. Shuffling characters or random block picks across the whole file before splitting put the same text in both sets, so validation loss looks better than it should.
  • Wrong dtype. Float ids cannot index an embedding table. Use torch.long.
  • Unseen characters. A character in the prompt that is not in the vocabulary raises a KeyError. A character tokenizer has no fallback, which is one reason real models use byte-pair encoding.

Examples

Encode, decode and a batch

text = open("input.txt").read()
chars = sorted(set(text))
stoi = {c: i for i, c in enumerate(chars)}
itos = {i: c for c, i in stoi.items()}
encode = lambda s: [stoi[c] for c in s]
decode = lambda ids: "".join(itos[i] for i in ids)

data = torch.tensor(encode(text), dtype=torch.long)
n = int(0.9 * len(data))
train_data, val_data = data[:n], data[n:]

With block_size 8 and the text "First Ci", x is the first 8 ids and y is the ids of "irst Cit". Position 0 of y is the correct answer for context "F"; position 7 is the answer for the whole 8-character context.

Key points

  • A character tokenizer is a sorted list of the characters in the corpus, with encode and decode as lookups in both directions.
  • Always check the round trip: decoding the encoded text must return the original string exactly.
  • The target is the input window shifted one position to the right, so one block gives block_size training examples.
  • Split train and validation by position in the text so the model never trains on validation characters.
  • Print one decoded x and y pair before training; shape errors crash, but target errors only make bad models.

Common mistakes

  • Setting y equal to x, or shifting the wrong way, so the model learns to copy instead of predict.
  • Drawing validation blocks from the same region as training blocks, which hides overfitting.
  • Forgetting that block_size plus one characters are needed per example, and indexing past the end of the data.
  • Rebuilding the vocabulary at generation time from a different text, which changes every id.

Check yourself · 2 of 3

For an input window x = data[i : i+8], what is the matching target y in next-token training?

Choose one answer

Check yourself · 3 of 3

You want an honest validation loss for a model trained on one long text file. Which split should you use?

Choose one answer

Practice items, not counted towards your mastery.

Start here