Lab 5: Is a GPU Always Faster?

Due Wednesday, December 2, 2026.

Accept the Lab 5 assignment and get your starter repository.

Open your Lab 5 starter folder in VS Code. Follow the setup for your machine, then work through Parts 1–5 in order. Submit your answers and measurements to Gradescope.

Overview

In Lab 1, you investigated whether shorter C code necessarily means less machine work. Now you will measure how long a computation actually takes—and investigate why changing the hardware does not always produce the speedup we expect.

You will first benchmark matrix multiplication, then run a small language model locally. You will compare CPU and GPU measurements and decide which measurements matter for an interactive application versus processing many requests.

Our guiding question is:

When does a GPU make an application faster, and how can we measure that fairly?

No machine-learning background is required. The model and benchmark code are provided; your job is to predict, run experiments, interpret measurements, and support a performance claim with evidence. You will run inference—using an existing model—not train a model.

Record your predictions and answers in answers.md. Short explanations of 2–3 sentences are sufficient unless otherwise stated.

Learning goals

Setup and hardware paths

Choose the setup that matches your laptop. Everyone runs the CPU experiments; students with a supported GPU also run the GPU experiments locally. If GPU access is unavailable, use the supplied paired CPU/GPU measurements for the comparison.

Your laptop Where to run the lab CPU device GPU device
Apple Silicon Mac (M-series chip) Native macOS Python virtual environment cpu mps
Windows with a supported NVIDIA GPU Lab 5 CUDA dev container through Docker Desktop and WSL2 cpu cuda
Linux with a supported NVIDIA GPU Lab 5 CUDA dev container with NVIDIA Container Toolkit cpu cuda
Intel Mac or another configuration Native macOS CPU setup, or Lab 5 CPU dev container on Windows/Linux cpu Use reference results

Path A: Mac—run natively

Install native Python 3.11 if needed. Open the Lab 5 starter folder in VS Code on macOS, and open its terminal. Run these commands from the repository root:

python3.11 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-macos.txt
python scripts/check_environment.py --device mps

On an Intel Mac, use --device cpu for the check.

Select .venv/bin/python as the VS Code Python interpreter. In each new terminal, run source .venv/bin/activate before running lab commands.

On an Apple Silicon Mac, the checker should report an ARM64 Python environment and an available MPS backend. MPS lets PyTorch use the Mac’s GPU through Metal. Run both your CPU and GPU experiments in this native environment; the Linux dev container is not the Mac GPU path. An Intel Mac can use the CPU setup and the supplied GPU comparison data.

Path B: NVIDIA—use the CUDA dev container

Your host must have a supported NVIDIA GPU and a compatible driver. On Windows, use Docker Desktop with its WSL2 backend. On Linux, install/configure NVIDIA Container Toolkit for Docker. The container supplies the Python runtime and libraries, but the host must provide GPU access.

Open the Lab 5 repository in VS Code, select Dev Containers: Reopen in Container, and choose the Lab 5 CUDA configuration. Then run:

python scripts/check_environment.py --device cuda

The checker should report that CUDA is available and identify your GPU. Run both your CPU and CUDA experiments inside this same container. Use the separate Lab 5 CPU configuration if GPU access is unavailable. In the CPU container, run python scripts/check_environment.py --device cpu.

Check and record your environment

Save the environment report. Record the CPU model, benchmark thread count, available memory, runtime versions, and selected GPU/backend when available. The checker saves results/environment.json. Summarize it in one line. Example: Apple M4 Pro, 4 benchmark threads, about 14 GiB available, native macOS, Python 3.11.13, PyTorch 2.7.1, MPS. If a value is unavailable, say so.

The GPU commands below use GPU_DEVICE as a placeholder: replace it with mps on an Apple Silicon Mac or cuda in the NVIDIA container. CPU commands always use --device cpu. If a requested GPU run fails, keep the error and use the reference data; do not label a CPU fallback as a GPU measurement.

Keep comparisons fair: measure CPU and GPU on the same machine, in the same environment, with the same workload. Keep the laptop plugged in and close other demanding applications during experiments.

Label every result as your measurement or provided reference data, and identify the GPU backend. Use the reference CPU with the reference GPU when calculating reference speedup. Comparing your laptop CPU with a different machine’s GPU measures a change of systems, not just a change of processor.

No personal GPU or paid cloud time is required. The starter includes measurements from an Apple M4 Pro in reference-results/.

Part 1: Predict before measuring

Suppose we run the same computation on a CPU and a GPU.

Before running the benchmarks, answer:

  1. Do you expect the GPU to win for both a tiny input and a large input? Why?
  2. Would you choose the same performance metric for a chatbot answering one person and a service processing hundreds of requests? Name a metric for each.

Keep your predictions, even if the measurements disagree.

Optional refresher: performance metrics

Metric Meaning Calculation
Latency Time to complete one operation or request Elapsed time, in ms or seconds
Throughput Amount of completed work per second Completed items / elapsed seconds
GPU speedup over CPU How much faster the GPU run is for the same work CPU time / GPU time

A speedup of 2 means twice as fast. A speedup below 1 means the GPU run was slower. Always identify the workload and timing boundary.

Part 2: Start small—matrix multiplication

Many model computations involve multiplying matrices. You do not need to implement the multiplication: the provided code uses an optimized library on each device.

Run:

python scripts/bench_matmul.py --device cpu --sizes 64 256 1024 --output results/matmul-cpu.csv

The benchmark creates fixed inputs, checks the result, performs warm-up operations, and records repeated measurements. For very short operations, it times a group of operations and reports time per multiplication. Use the median, not the fastest trial.

Then inspect the supplied paired CPU/GPU results in reference-results/matmul.csv. If the environment check confirmed GPU access, also run (replace GPU_DEVICE as described in Setup):

python scripts/bench_matmul.py --device GPU_DEVICE --sizes 64 256 1024 --output results/matmul-gpu.csv

There are two timing boundaries:

Read median_ms for each size and boundary. On the CPU, both boundaries use CPU memory throughout and time essentially the same work. Small differences are timing noise. Record only CPU complete; record both GPU boundaries.

On Apple Silicon, the CPU and GPU share physical memory. These timing boundaries still apply, but the extra time can include copies, allocation, and synchronization; do not interpret it as a discrete GPU’s PCIe transfer cost.

GPU work may continue after a Python call returns. The supplied timer waits for the device to finish before stopping the clock.

Record and explain

Use either your paired measurements or the paired reference measurements for this table. Keep the two sources separate.

Matrix size CPU complete operation (ms) GPU resident (ms) GPU complete operation (ms) Complete-operation speedup
64 × 64
256 × 256
1024 × 1024
  1. Show one speedup calculation. Does the GPU advantage change with matrix size? Use two rows as evidence; your results need not show a crossover.
  2. Why might timing only GPU computation give a misleading prediction of application performance?

Keep your local CPU CSV even if you use the reference pair for the table.

Part 3: Run a small model on your CPU

We will use a small text-generation model, SmolLM2-135M-Instruct. A token is a unit of text processed by the model; it is not necessarily a whole word. You are measuring computation, not evaluating the model’s factual accuracy.

Download the course-pinned model once:

python scripts/fetch_model.py

Then try one short prompt:

python scripts/run_model.py --device cpu --prompt "Explain a CPU to a beginner in one sentence." --max-new-tokens 32

The model runs locally after downloading. The demo limits output length; it may stop early. The benchmark below uses a fixed amount of generation work so that an early stop does not make one device appear faster.

Run the fixed benchmark:

python scripts/bench_model.py --device cpu --batch-sizes 1 4 --new-tokens 32 --output results/model-cpu.csv

The script uses the same supplied prompt, model, precision, and generation settings in every comparison. It warms up the model and measures three trials for each batch size. A batch of four means four prompts processed together, rather than four separate launches. Each prompt produces exactly 32 new tokens during this benchmark.

Open results/model-cpu.csv and use the row with batch_size=1. Read model_load_seconds, median_seconds, median_ttft_ms, and tokens_per_second, respectively:

Measurement Your CPU result
Model load time (seconds; reported separately)
Median request time for 32 new tokens (seconds)
Median time to first generated token (ms)
Generated-token throughput (tokens/second)

Request time starts with the model loaded and the prompt already tokenized, and includes moving inputs to the selected device, generation, and returning generated token IDs to the CPU. It excludes download, loading, tokenization, text rendering, and any network service. Time to first token uses that same start point and ends when the first generated token ID is available on the CPU.

Answer:

  1. Why should the download and model load not be included in every repeated inference measurement? When would startup time still matter to a user?
  2. Why is “time to first token” different from the time needed to finish the response?

Part 4: CPU versus GPU—latency versus throughput

Inspect reference-results/model.csv, which contains paired CPU/GPU runs of the same model on the reference host. If you have GPU access, collect your own matched runs (replace GPU_DEVICE with mps or cuda):

python scripts/bench_model.py --device GPU_DEVICE --batch-sizes 1 4 --new-tokens 32 --output results/model-gpu.csv

For each batch size, calculate:

Generated tokens per batch = batch size × 32
Token throughput = generated tokens per batch / batch completion time
Request throughput = batch size / batch completion time
GPU speedup = CPU batch completion time / GPU batch completion time

Use median batch completion time for the calculations below. For one GPU row, also record min_seconds and max_seconds. If the CPU and GPU medians are close relative to the trial spread, qualify your claim. Three trials are sufficient. All requests in a batch are submitted together and returned when the batch completes; this is not a live server with arrivals and queueing.

Device Batch size Median batch completion time (s) Requests/second Generated tokens/second
CPU 1
GPU 1
CPU 4
GPU 4
  1. Show the CPU/GPU speedup calculation for batch size 1 and batch size 4. Which workload benefits more on your selected system?
  2. Does dividing the batch completion time by four tell you how long one person waited? Explain using the batch-size-4 measurement.
  3. Recommend a device and batch size for (a) one interactive user and (b) many independent requests already waiting to be processed. Support each recommendation with a measured value. Mention one tradeoff.

Larger batches provide more independent work, but each generated token in a single sequence still depends on earlier tokens. More GPU arithmetic capacity does not remove that dependency.

Part 5: Make a defensible performance claim

Write a short conclusion, about 150–200 words, responding to:

“We should move every computation to a GPU because GPUs are faster.”

Use at least one matrix result and one model result. State which metric matters for your example, one condition under which your conclusion might change, and one limitation of your experiment.

Connect your explanation to the class performance equation:

CPU execution time = instruction count × CPI × clock cycle time

Explain why comparing CPU and GPU clock rates alone cannot predict the measured speedup. You do not need to estimate CPI or instruction counts for the model.

Submission

Submit:

Identify the reference dataset used when applicable. Do not submit model weights or caches. Grading is based on sound measurement and reasoning, not on whose laptop is fastest or whether a GPU beats a CPU.

If a run exceeds your machine’s resources, save the error and environment report, use the corresponding provided results, and identify that substitution in your answers. You can complete the same analysis without a successful local GPU run.

Grading

Component Weight
Predictions and environment record 10%
Matrix measurements and explanation 25%
Local model experiment and timing boundaries 20%
CPU/GPU comparison and batching 30%
Final evidence-based recommendation 15%

Predict → Measure → Compare → Explain

Further reading