1. Why Pre-train From Scratch?

Pre-training means training a model on a large corpus of unlabeled data so it learns general patterns — syntactic structure, common idioms, token relationships — before being specialized on a downstream task. For code, this means learning what well-formed code looks like before learning to fix bugs, summarize functions, or detect vulnerabilities.

Models like CodeT5 already come pre-trained. So why do it yourself? Because understanding the full pipeline — choosing a tokenizer, defining the architecture, implementing span corruption, managing checkpoints — is how you build the intuition to use, debug, and improve these systems.

The pipeline we walk through in this guide:

  1. Train or load a tokenizer
  2. Define a T5-small model from scratch
  3. Pre-train with span corruption on code
  4. Save the best checkpoint for downstream fine-tuning

Each step involves design decisions. This guide explains the reasoning behind each one.

2. What is a Tokenizer and Why Does It Matter?

A tokenizer converts raw text into token IDs the model can process. It determines how code is broken into pieces — and those pieces determine what patterns the model can learn.

Subword tokenizers (BPE, Unigram) split text into a mix of whole words and subword pieces. Common tokens stay whole, rare ones get split:

"IOException" in a code-trained tokenizer → ["IOException"] (1 token) "IOException" in an English-trained tokenizer → ["IO", "Ex", "ception"] (3 tokens)

The tokenizer's vocabulary is the set of all tokens it knows. You set the vocabulary size before training — the algorithm then picks the best N subword pieces from your data.

Key Insight

The tokenizer is independent from the model architecture. T5 doesn't care which tokenizer you use — it just needs a vocabulary size to set the embedding layer shape, and token IDs for pad, eos, and bos. You can pair any tokenizer with the T5 architecture.

Two tokenizer families you should know:

SentencePiece is a library by Google that trains tokenizers directly on raw text. It supports two algorithms: BPE (merge frequent pairs) and Unigram (start large, remove least useful tokens). The original T5 used SentencePiece with the Unigram algorithm, trained on the C4 English corpus (32K vocab).

RoBERTa's tokenizer uses Byte-Pair Encoding. When trained on code (as in CodeBERT/CodeT5), it learns merge rules specific to programming constructs — String, return, public stay as single tokens because they appeared millions of times in the training data.

Here's how the same code gets tokenized differently:

code = "def sort(arr): return sorted(arr)"

# SentencePiece (Unigram, trained on your code corpus)
sp_tokens = sp_tokenizer.tokenize(code)
# → ['▁def', '▁sort', '(', 'arr', '):', '▁return', '▁sorted', '(', 'arr', ')']

# RoBERTa (BPE, from microsoft/codebert-base)
rob_tokens = rob_tokenizer.tokenize(code)
# → ['def', 'Ġsort', '(', 'arr', '):', 'Ġreturn', 'Ġsorted', '(', 'arr', ')']

The ▁ (SentencePiece) and Ġ (RoBERTa) characters mark word boundaries — they indicate “this token starts a new word.” Different notation, same concept.

3. Training Your Own Tokenizer

To train your own tokenizer, you need: (1) a corpus, (2) a target vocabulary size, and (3) an algorithm choice. SentencePiece handles all three:

import sentencepiece as spm

sentinel_tokens = [f"<extra_id_{i}>" for i in range(100)]
user_defined_symbols = ",".join(sentinel_tokens)

spm.SentencePieceTrainer.train(
    input=corpus_file,            # one function per line
    model_prefix=model_prefix,    # output file prefix
    vocab_size=16384,             # target vocabulary size
    hard_vocab_limit=False,       # allow slight deviation
    model_type="unigram",         # Unigram algorithm
    pad_id=0,                     # <pad> = ID 0
    eos_id=1,                     # </s>  = ID 1
    unk_id=2,                     # <unk> = ID 2
    bos_id=-1,                    # T5 doesn't use BOS
    user_defined_symbols=user_defined_symbols,
    character_coverage=1.0,
)

This outputs two files: sp_code.model (the tokenizer) and sp_code.vocab (the vocabulary).

Warning

The user_defined_symbols parameter is critical. T5's span corruption uses sentinel tokens <extra_id_0> through <extra_id_99> to mark masked spans. If you forget to include them, the tokenizer won't recognize them and span corruption will silently break.

How to choose vocabulary size. Vocabulary size controls how many unique tokens the tokenizer can represent. The tradeoff: bigger vocab means shorter sequences (fewer token splits) but more rare tokens whose embeddings never get learned well. Smaller vocab means longer sequences but every token appears often enough to get a meaningful embedding.

For a corpus of ~50K functions, 16K is a reasonable vocabulary size. At 50K+ vocabulary, you'd have thousands of tokens the model barely sees — their embeddings stay random noise even after training. At 8K, common constructs get split into too many pieces, making sequences unnecessarily long. 16K–32K is the sweet spot for corpora of this size.

For reference: T5 used 32K (trained on 750GB of English text), RoBERTa/CodeBERT uses 50K (trained on billions of tokens). They can afford larger vocabularies because their training data is orders of magnitude bigger.

Loading a trained SentencePiece model as a HuggingFace tokenizer requires converting through the tokenizers library:

import sentencepiece as spm
from tokenizers import Tokenizer
from tokenizers.models import Unigram
from tokenizers.pre_tokenizers import Metaspace
from tokenizers.decoders import Metaspace as MetaspaceDecoder
from transformers import PreTrainedTokenizerFast

sp = spm.SentencePieceProcessor()
sp.Load(model_path)

vocab = [(sp.IdToPiece(i), sp.GetScore(i)) for i in range(sp.GetPieceSize())]

tokenizer_obj = Tokenizer(Unigram(vocab, unk_id=2))
tokenizer_obj.pre_tokenizer = Metaspace()
tokenizer_obj.decoder = MetaspaceDecoder()

sentinel_tokens = [f"<extra_id_{i}>" for i in range(100)]

tokenizer = PreTrainedTokenizerFast(
    tokenizer_object=tokenizer_obj,
    eos_token="</s>",
    unk_token="<unk>",
    pad_token="<pad>",
    additional_special_tokens=sentinel_tokens,
)

Using a pre-trained RoBERTa tokenizer is simpler — it's already in HuggingFace format. You just need to add sentinel tokens:

from transformers import RobertaTokenizer

tokenizer = RobertaTokenizer.from_pretrained("microsoft/codebert-base")
sentinel_tokens = [f"<extra_id_{i}>" for i in range(100)]
tokenizer.add_tokens(sentinel_tokens, special_tokens=True)
# Vocab grows from 50,265 → 50,365

4. Defining the Model Architecture

We use T5-small (~60M parameters). Here are the T5 sizes for reference:

Modeld_modelLayers (enc+dec)HeadsParameters
T5-small5126+68~60M
T5-base76812+1212~220M
T5-large102424+2416~770M

We define the config manually rather than borrowing from a checkpoint. This follows the approach in Mastropaolo et al. (ASE 2023), where each architectural parameter is set explicitly:

from transformers import T5Config, T5ForConditionalGeneration

t5_config = T5Config(
    decoder_start_token_id=tokenizer.convert_tokens_to_ids(["<pad>"])[0]
    if "<pad>" in tokenizer.get_vocab() else 0
)
t5_config.d_model = 512          # embedding and hidden state dimension
t5_config.d_ff = 2048            # feed-forward layer dimension
t5_config.d_kv = 64              # key/value projection dimension
t5_config.num_heads = 8          # attention heads
t5_config.num_layers = 6         # encoder layers
t5_config.num_decoder_layers = 6 # decoder layers
t5_config.vocab_size = len(tokenizer)

model = T5ForConditionalGeneration(config=t5_config)
model.resize_token_embeddings(len(tokenizer))

Why manual config instead of AutoConfig.from_pretrained()? Both produce a model from scratch — neither loads pre-trained weights. But AutoConfig borrows the shape from an existing checkpoint, which can be confusing. Manual config makes every decision visible and intentional.

Key Detail

resize_token_embeddings(len(tokenizer)) ensures the embedding matrix has exactly one row per token. Without this call, the model will crash when it encounters token IDs beyond the default vocabulary size.

The embedding layer's shape depends on your tokenizer:

print(model.shared.weight.shape)
# SentencePiece: torch.Size([16384, 512])  — 16K tokens × 512 dims
# RoBERTa:      torch.Size([50365, 512])  — ~50K tokens × 512 dims

Same architecture, different embedding sizes. The rest of the model is identical.

5. Embedding Initialization: Why Random?

The embedding layer starts with random values. During pre-training, the model updates these values to capture meaningful token relationships. After enough training, the embeddings encode syntactic and semantic patterns.

You might wonder: why not initialize with pre-trained embeddings from RoBERTa or Word2Vec?

Dimension mismatch. RoBERTa uses 768-dimensional embeddings. T5-small uses 512. You'd need a linear projection (768 → 512), which loses information:

from transformers import RobertaModel
roberta = RobertaModel.from_pretrained("microsoft/codebert-base")
print(roberta.embeddings.word_embeddings.weight.shape)  # torch.Size([50265, 768])
# Projecting 768 → 512 = lossy

Vocabulary mismatch. If you train your own tokenizer (e.g., SentencePiece), its vocabulary is completely different from RoBERTa's. Token ID 42 in SentencePiece means a different token than ID 42 in RoBERTa. You can't map embeddings across incompatible vocabularies.

Pre-training overwrites them anyway. Modern transformer models learn embeddings end-to-end during training. The initial values get overwritten within the first few epochs. What matters is the training data and objective — not the starting point. This is why T5, CodeT5, GPT, and most modern models all start with random embeddings.

Critical Rule

Whatever embedding the model learns during pre-training carries into fine-tuning automatically. When you save a checkpoint, the embedding is inside it. When you load that checkpoint for fine-tuning, the embedding comes with it. Do NOT reinitialize or swap embeddings between stages — doing so would destroy everything the model learned.

6. Span Corruption: How T5 Learns

Span corruption is T5's pre-training objective. You randomly mask chunks (spans) of the input and make the model predict what was masked.

Here's a concrete example:

Original: "def sort(arr): return sorted(arr)" Token IDs: [def, sort, (, arr, ), :, return, sorted, (, arr, )] 15% of tokens selected → positions [1, 2, 7] Consecutive positions [1, 2] grouped into one span Corrupted input: [def, <extra_id_0>, arr, ), :, return, <extra_id_1>, (, arr, )] Target (what the model must predict): [<extra_id_0>, sort, (, <extra_id_1>, sorted]

Key points:

  • Each span is replaced by a unique sentinel token (<extra_id_0>, <extra_id_1>, ...) — NOT <mask> as in BERT
  • The target contains ONLY the masked content, prefixed by the sentinel that replaced it
  • This makes the target much shorter than the input — more efficient than predicting the full sequence
  • Corruption is dynamic — a fresh random mask every time the model sees an example across epochs

The metric during pre-training is just loss — cross-entropy between the model's predictions and the actual masked tokens:

outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
loss = outputs.loss  # cross-entropy, computed internally by T5

No fancy metrics during pre-training. Loss goes down, the model is learning. That's it.

Building the corruption in code. First, select random positions and group consecutive ones into spans:

n_mask = max(1, int(n_tokens * self.corruption_rate))  # 15%
mask_indices = sorted(random.sample(range(n_tokens), n_mask))

spans = []
current_span = [mask_indices[0]]
for i in range(1, len(mask_indices)):
    if mask_indices[i] == mask_indices[i - 1] + 1:
        current_span.append(mask_indices[i])
    else:
        spans.append(current_span)
        current_span = [mask_indices[i]]
spans.append(current_span)

Then build the corrupted input (sentinel replaces each span) and the target (sentinel followed by original tokens):

# Input: replace each span with its sentinel token
input_ids = []
prev_span_idx = -1
for pos, tid in enumerate(token_ids):
    if pos in mask_set:
        s_idx = span_map[pos]
        if s_idx != prev_span_idx:
            input_ids.append(self.sentinel_ids[s_idx])
            prev_span_idx = s_idx
    else:
        input_ids.append(tid)
        prev_span_idx = -1

# Target: sentinel followed by the span's original tokens
target_ids = []
for span_idx, span in enumerate(spans):
    target_ids.append(self.sentinel_ids[span_idx])
    for pos in span:
        target_ids.append(token_ids[pos])

7. The Training Loop: Save Best, No Early Stopping

The standard approach for pre-training is to run all epochs and save the best checkpoint by validation loss. We do NOT use early stopping.

Why not early stopping? Loss can temporarily increase and come back down. Early stopping quits and misses the recovery:

Save best checkpoint approach: Epoch 1: loss=5.2 → save Epoch 2: loss=4.1 → save Epoch 3: loss=3.8 → save (best so far) Epoch 4: loss=4.0 → skip Epoch 5: loss=3.7 → save (new best!) ← would have been missed with early stopping Early stopping (patience=1): Epoch 1: loss=5.2 → save Epoch 2: loss=4.1 → save Epoch 3: loss=3.8 → save Epoch 4: loss=4.0 → STOP ← missed epoch 5's improvement

This pattern — run all epochs, keep the best — is used in Mastropaolo et al.'s t5-no-pt.py (ASE 2023) and the T5 pre-training repo by manueldeprada.

The full training loop:

best_loss = float("inf")

for epoch in range(args.epochs):
    model.train()
    tr_loss, tr_steps = 0.0, 0

    for step, batch in enumerate(train_dataloader):
        input_ids, attention_mask, labels = [x.to(args.device) for x in batch]

        outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
        loss = outputs.loss

        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)

        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()

        tr_loss += loss.item()
        tr_steps += 1

    train_loss = round(tr_loss / tr_steps, 5)
    eval_loss = evaluate_model(model, eval_dataloader, args.device)

After each epoch, save if validation loss improved:

    if eval_loss < best_loss:
        best_loss = eval_loss
        model_to_save = model.module if hasattr(model, "module") else model
        model_to_save.save_pretrained(output_dir)
        tokenizer.save_pretrained(output_dir)
    # No break — training continues through all epochs

Evaluation is just average loss:

def evaluate_model(model, eval_dataloader, device):
    model.eval()
    eval_loss, num_batches = 0.0, 0
    with torch.no_grad():
        for batch in eval_dataloader:
            input_ids, attention_mask, labels = [x.to(device) for x in batch]
            outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
            eval_loss += outputs.loss.item()
            num_batches += 1
    return round(eval_loss / num_batches, 5)

8. What Happens Next: Fine-tuning

After pre-training, you have a model that understands code structure but has never seen a specific task. Fine-tuning adapts it — whether for bug fixing, code summarization, vulnerability detection, or any other downstream task.

Loading is straightforward — everything carries over from the checkpoint:

# Load the pre-trained model — weights, embeddings, config all inside
model = T5ForConditionalGeneration.from_pretrained("checkpoints/checkpoint-best-loss")

# Load the SAME tokenizer used during pre-training
tokenizer = PreTrainedTokenizerFast.from_pretrained("checkpoints/checkpoint-best-loss")
# or RobertaTokenizer.from_pretrained(...) if you used RoBERTa
Warning

Do NOT swap tokenizers between pre-training and fine-tuning. The tokenizer defines the vocabulary. The vocabulary defines the embedding. Swapping the tokenizer means every token ID maps to the wrong embedding row — the model's learned knowledge becomes garbage.

The fine-tuning objective is different from pre-training:

  • Pre-training: span corruption (fill in masked spans)
  • Fine-tuning: task-specific (e.g., buggy code → fixed code)

But the model architecture and the loss function remain the same — encoder-decoder T5 with cross-entropy. Only the data and the task change. That's the beauty of pre-training: one model, many downstream applications.