Lab 10: Building and Training a Transformer Language Model from Scratch
Overview & Start Here
In Lab 9, you loaded and inspected a pretrained language model. In this lab, you will work in the opposite direction: starting from raw text and randomly initialized parameters, you will build and train a small decoder-only Transformer language model yourself.
The model in this lab is intentionally tiny. It is not a large language model, and it is not expected to produce high-quality prose. Its purpose is to make the full training process small enough to inspect, understand, and run on a CPU during a lab session.
Dataset: Tiny Shakespeare, using the 1.06 MB distribution from Andrej Karpathy's char-rnn repository.
Environment: Google Colab or a local Jupyter environment. The required path is designed to run on CPU-only systems; CUDA or Apple MPS may make training faster but is not required.
Working format: Use one notebook throughout the lab. Keep the code, outputs, plots, and short written responses together.
Core idea: the model learns by predicting the next token at every position. The same basic causal language-model objective underlies the pretrained causal model that you inspected in Lab 9.
Learning objectives
By the end of this lab, you should be able to:
Convert raw text into discrete token IDs using a simple byte-level tokenizer.
Construct input/target training examples for causal next-token prediction.
Explain the roles of token embeddings and positional embeddings.
Explain and implement the essential operations in causal self-attention: scaling, causal masking, softmax, and weighted aggregation.
Trace tensor shapes through a small decoder-only Transformer and interpret its output logits.
Compute causal language-model cross-entropy loss and update model parameters with gradient descent.
Compare generation from a randomly initialized model with generation after training.
Connect the model built in this lab to the
AutoModelForCausalLMabstraction used in Lab 9.
Your route through the lab
Page | What you will do | Requirement |
|---|---|---|
Load Tiny Shakespeare, inspect byte tokens, construct shifted targets, and create mini-batches. | Core: both courses | |
Complete the causal-attention TODOs, trace tensor shapes, and generate from random initialization. | Core: both courses | |
Define cross-entropy, train the model, inspect learning curves, and compare generation before/after training. | Core: both courses | |
Use a random-token control to expose target leakage when future attention is allowed. | Required: CSCI 6509; optional: CSCI 4152 | |
Continue training, explore decoding/model choices, weight tying, hardware speed, and checkpointing. | Optional: both courses | |
Resolve common errors and consult sources/acknowledgements. | Use as needed |
CSCI 4152: Complete pages 01 → 02 → 03, then finish responses R1–R6 below.
CSCI 6509: Complete pages 01 → 02 → 03 → 04, then finish R1–R6 and G1.
The discussion checkpoints on the activity pages are for observation, partner discussion, and TA check-ins. You do not submit a separate written answer to every checkpoint.
Model used in this lab
The required lab uses the following fixed decoder-only Transformer configuration:
Vocabulary size: 256 byte tokens
Context length: 128
Embedding dimension: 128
Attention heads: 4
Transformer blocks: 2
MLP expansion: 4x
Trainable parameters: 477,696Page 03 uses 1,500 required optimization steps. Page 05 begins with an optional continuation to 2,000 total steps for students who want to inspect what additional optimization changes.
Execution environment
You may complete this lab in either of the following environments.
Option A — Google Colab
Use the course-provided notebook in a standard Colab runtime. The required lab is designed for a CPU runtime; do not request a GPU simply to complete the required steps.
PyTorch is normally available in Colab. Run the setup cell at the beginning of the course notebook to verify the required imports and display the selected device.
Option B — Local Jupyter environment
If you already have a working Python environment, you may run the same notebook on your own computer. A typical setup is:
python -m venv .venvActivate the environment, then install the packages used by the notebook:
python -m pip install torch matplotlib jupyterThe notebook automatically chooses CUDA, Apple MPS, or CPU when available. The core lab must remain feasible when the selected device is CPU.
The Colab and local versions use the same model and training code. The execution hardware changes; the learning algorithm does not.
Why a byte-level tokenizer?
Modern language models generally use subword tokenizers. You already inspected a production subword tokenizer in Lab 9. Here we deliberately use a simpler tokenizer so that the vocabulary remains small and the entire model can be trained from scratch during the lab.
UTF-8 bytes naturally map to integer values from 0 to 255, so Lab 10 uses exactly 256 token IDs. This gives us a compact vocabulary without unknown-token handling or a separate tokenizer-training stage. Lab 11 reuses this 256-byte vocabulary unchanged and encodes role markers such as User: and Assistant: as ordinary ASCII text.
Conceptual pipeline
Raw text
|
v
Byte-level tokenizer
|
v
Token IDs
|
+--> x: tokens [0 ... T-1]
|
+--> y: tokens [1 ... T]
|
v
Token + position embeddings
|
v
Causal self-attention
|
v
Transformer blocks
|
v
Logits [B, T, V]
|
v
Cross-entropy loss
|
v
Backpropagation
|
v
Updated parameters
|
v
Autoregressive generationA major goal of this lab is to recognize that the final tensor shape, [batch, sequence, vocabulary], is the same kind of output you inspected through outputs.logits in Lab 9.
Time and completion plan
Activity | Estimated time |
|---|---|
Page 01: corpus, byte tokens, shifted targets, mini-batches | 15–20 minutes |
Page 02: causal attention TODOs, model inspection, untrained generation | 30–40 minutes |
Page 03: loss, 1,500-step training, evaluation, before/after generation | 30–40 minutes |
Page 04: required CSCI 6509 leakage ablation | 20–30 minutes |
Written responses R1–R6; G1 for CSCI 6509 | Allow a further 30–40 minutes |
The core CSCI 4152 experiments are planned for approximately 75–100 minutes. Including the required CSCI 6509 extension gives approximately 95–130 minutes, before writing up responses. CPU speed varies across Colab allocations and personal computers; the training loops themselves are intentionally only a small part of the total activity time.
During class, prioritize running the required experiments, recording outputs, and saving the notebook. Written responses may be completed after class by the instructor's stated deadline.
Start your working notebook
Open the starter notebook supplied by your instructor or TA. If no starter notebook has been supplied, create a notebook in Google Colab or Jupyter and name it Lab10_TinyTransformer_YourName.
Use the same notebook for all required pages. Later pages depend on variables and class definitions created earlier. If the runtime restarts, rerun the notebook from the beginning.
Begin with 01 — Text, Tokens, and Next-Token Prediction.
Required written responses
The discussion checkpoints on Pages 01–04 are prompts for observation, partner discussion, and TA check-ins. Submit only the following responses; separate written answers to every discussion checkpoint are not required.
Unless your instructor specifies otherwise, aim for two to four sentences per core response, together with the requested code/output evidence.
Response | What to include |
|---|---|
R1 — Tokens and targets | Report how many of the 256 byte IDs actually occur in Tiny Shakespeare, show one encode/decode example, and use one short sequence to explain the one-token shift from |
R2 — Causal attention | Include your completed scale/mask/softmax lines from Page 02 and explain why the mask must prevent position |
R3 — Model shapes | Trace |
R4 — Loss and optimization | Report the initial loss and |
R5 — Learning evidence | Include your training/validation loss history or plot and the generation samples from before and after training. Describe concrete changes and identify any evidence of underfitting or overfitting. |
R6 — Lab 9 ↔ Lab 10 | Complete the Page 03 comparison between Hugging Face tokenizer/input IDs/model/logits/weights/generation and the corresponding objects you implemented in Lab 10. State the most important mechanism shared by the two causal language models. |
G1 — CSCI 6509: Include a table reporting causal train/validation loss, non-causal train/validation loss, and both models' last-position validation loss from Page 04. Then respond to the claim: "The non-causal model has a lower validation loss, so it is the better language model." Your analysis must distinguish ordinary overfitting from target leakage and explain why the last-position metric changes the interpretation.
Optional Page 05 activities are not required unless your instructor specifies otherwise.
Assessment and collaboration
Unless your instructor announces a different marking scheme, use the following rubric:
Component | Marks | Basis for credit |
|---|---|---|
R1–R6 | 2 each; 12 total | 2: correct explanation addressing the requested concept with observed evidence where requested. 1: partly correct or incomplete. 0: missing or does not demonstrate the requested understanding. |
G1: controlled results | 2 | Correct comparison table using the specified causal/non-causal experiment and last-position metric. |
G1: leakage analysis | 2 | Correct diagnosis of target leakage, validation mismatch, overfitting versus leakage, and deployment-time information constraints. |
CSCI 4152: 12 marks total. CSCI 6509: 16 marks total. The lab's contribution to the course grade follows the course syllabus.
Collaboration: Discussion with classmates is encouraged. Each student should run and retain their own notebook and independently write R1–R6 and, where required, G1 in their own words.
AI tools: Follow the course's published AI-use policy. Where that policy permits assistance, verify suggestions against your own experiment and submit your own explanations.
Submission / check-off
Unless your instructor specifies otherwise, prepare one completed notebook containing:
the code and outputs for the required activity pages,
responses R1–R6, clearly labelled,
the training/validation loss record and before/after generation samples,
CSCI 6509: response G1 and its comparison table.
Assessment focuses on your understanding of causal language modelling, model computation, and experimental interpretation. Fluent generated prose is not required for a successful lab.