Skip to content
Start here Foundation 19 min read

Your workbench: Python, notebooks, PyTorch, MLX

Everything on this site runs on an Apple-silicon Mac with 18 GB of memory: NumPy for the maths, PyTorch on the GPU through Metal, Apple's MLX, and quantised LLMs through llama.cpp or Ollama. This page sets it up, explains what fits in that memory and why, and tells you when to rent a GPU instead.

10,000 ft

Learning AI is an experimental subject: you understand an idea when you have run it, broken it and fixed it. That needs a workbench you trust. A modern Mac is a surprisingly good one, because Apple silicon shares one pool of fast memory between CPU and GPU, so a laptop can hold and run models that would need a dedicated graphics card elsewhere. The limits are memory capacity (what fits) and memory bandwidth (how fast it generates), and both can be computed on a napkin. For anything bigger, such as training a model with more than a few hundred million parameters or fine-tuning beyond LoRA, you rent a GPU by the hour, or use a free one in Colab or Kaggle.

2,000 ft

One tool manages Python (uv), one project holds your work, and four engines run it: NumPy on the CPU for every Build it on this site, PyTorch on the mps device for neural networks, MLX for Apple-native training and LLM inference, and llama.cpp or Ollama for running quantised open-weight models. Notebooks are for exploring; scripts are for anything you will rerun. Cloud GPUs are the escape hatch.

The workbench
The workbench. uv Python 3.12 · project · lockfile, Jupyter / VS Code notebooks, NumPy every Build it, PyTorch device = mps, MLX · mlx-lm Apple-native, llama.cpp · Ollama quantised GGUF models, Cloud GPU Colab · Kaggle · rented, when it outgrows 18 GBThe workbench. uv Python 3.12 · project · lockfile, Jupyter / VS Code notebooks, NumPy every Build it, PyTorch device = mps, MLX · mlx-lm Apple-native, llama.cpp · Ollama quantised GGUF models, Cloud GPU Colab · Kaggle · rented, when it outgrows 18 GB

Ground level

What 18 GB of unified memory means

On a PC, a GPU has its own memory (VRAM) and data is copied across a bus to reach it. On Apple silicon, CPU and GPU share one pool of memory, so a model loaded once is visible to both and there is no separate VRAM limit. There is still a limit: macOS reserves part of memory for itself, and Metal reports a recommended maximum working set for the GPU. On the 18 GB M3 Pro this site was written on, that value is 14.3 GB, 74% of physical memory (queried with MTLCreateSystemDefaultDevice().recommendedMaxWorkingSetSize). Treat about 14 GB as your GPU budget, minus whatever your browser and editor are using.

Two numbers decide what you can do with that budget:

  • Capacity. A model's weights take \(N \times b/8\) bytes for \(N\) parameters at \(b\) bits each. An 8-billion-parameter model is 16 GB in 16-bit precision (does not fit), 8 GB in 8-bit, about 5 GB in the 4-bit formats used in practice (fits comfortably). Ollama's qwen3:8b download, for example, is 5.2 GB.
  • Bandwidth. Generating one token reads every weight once. The M3 Pro's memory bandwidth is 150 GB/s (Apple's specification), so a 5 GB model can produce at most about 30 tokens per second, whatever the GPU's arithmetic speed. This is why quantisation makes models faster on a laptop, not just smaller (Quantisation, On-device AI).

Try the trade-off: quantising weights from 16 to 8 to 4 bits halves memory each time, at a growing cost in error.

Step 1: Python 3.12 with uv

uv installs Python itself, creates virtual environments, resolves and locks dependencies, and runs commands inside the project environment. It replaces pyenv, venv, pip and pip-tools with one fast tool, and its lockfile makes your environment reproducible.

brew install uv                       # or: curl -LsSf https://astral.sh/uv/install.sh | sh
uv python install 3.12                # a managed, native arm64 Python 3.12
uv init learn-ai --python 3.12        # a project folder with pyproject.toml
cd learn-ai
uv add numpy matplotlib pandas scikit-learn
uv add torch                          # macOS arm64 wheels include the MPS backend
uv add mlx mlx-lm                     # Apple's array framework and its LLM tools
uv add --dev ipykernel jupyterlab
uv run python -c "import platform, numpy; print(platform.machine(), numpy.__version__)"

The last line should print arm64. If it prints x86_64, your Python is running under Rosetta emulation: it will be slow and MLX will not install. MLX needs macOS 14 or later, Apple silicon and a native Python 3.10 or newer (MLX install guide).

If you prefer the standard library's tools, the equivalent is python3.12 -m venv .venv && source .venv/bin/activate && pip install numpy torch mlx mlx-lm jupyterlab. Either way, keep one environment per project, never install into the system Python, and commit the lockfile (uv.lock) with your code.

Step 2: notebooks, and when not to use them

Notebooks are the right tool for exploration: run a cell, look at a plot, change a number. They are the wrong tool for anything you will run twice, because hidden state (cells run out of order, variables left over from deleted cells) makes results irreproducible.

uv run jupyter lab                    # serves at http://localhost:8888/lab

Or open the folder in VS Code, create a notebook, and pick the project's .venv as the kernel (uv's Jupyter guide, VS Code notebooks). marimo is a reactive alternative in which cells re-run when their inputs change, which removes the hidden-state problem by design.

Three habits keep notebooks honest:

  1. Restart and run all before you trust a result or share a notebook.
  2. Move code that works into a .py module and import it; keep the notebook for calling and plotting.
  3. Fix the seed (np.random.default_rng(0), torch.manual_seed(0)) whenever you compare runs.

When you are finished, shut the kernel down (or stop the server with Ctrl-C). A forgotten kernel holding a model in memory is the most common reason a Mac with 18 GB starts swapping.

Step 3: PyTorch on the GPU with MPS

PyTorch reaches the Apple GPU through the MPS (Metal Performance Shaders) backend, which needs macOS 14 or later. You use it exactly like a CUDA device, with the device name "mps":

# PyTorch on Apple silicon: pick the best available device (not run in this site's build).
import torch

device = ("cuda" if torch.cuda.is_available()
          else "mps" if torch.backends.mps.is_available()
          else "cpu")
print("device:", device)

x = torch.randn(4096, 4096, device=device)
y = x @ x                       # runs on the GPU when device == "mps"
if device == "mps":
    torch.mps.synchronize()     # GPU work is asynchronous; synchronise before timing
print(y.shape, y.dtype)

Writing device once and passing it everywhere means the same script runs on your Mac, on a cloud NVIDIA GPU and on a CPU-only machine. Four things differ from CUDA in practice:

  • No float64 on the GPU. MPS does not support double precision; keep tensors in float32, float16 or bfloat16.
  • Missing operations. A few operations are not implemented for MPS. Setting PYTORCH_ENABLE_MPS_FALLBACK=1 runs them on the CPU instead of failing, at a speed cost (MPS environment variables).
  • Memory limits. The MPS allocator stops at a high-watermark ratio of the recommended working set (PYTORCH_MPS_HIGH_WATERMARK_RATIO, default 1.7). Raising it past the default risks the whole system running out of memory; reduce batch size instead.
  • Asynchrony. As on CUDA, GPU calls return before the work finishes; call torch.mps.synchronize() before reading a timer.

Step 4: MLX, Apple's own framework

MLX is an array framework from Apple's machine learning research team, with a NumPy-like API, automatic differentiation, and two design choices that suit the Mac: arrays live in unified memory (there is no .to(device); operations choose CPU or GPU), and computation is lazy (nothing runs until you call mx.eval or need a value).

# MLX: NumPy-like arrays, lazy evaluation, gradients.
import mlx.core as mx

a = mx.random.normal((2048, 2048))
b = a @ a.T                              # builds a graph; nothing computed yet
mx.eval(b)                               # now it runs, on the GPU by default
loss = lambda w: mx.mean((a @ w) ** 2)
grad = mx.grad(loss)(mx.ones((2048,)))   # automatic differentiation, as in JAX
print(b.shape, grad.shape, mx.default_device())

Output (MLX 0.32.4 on an M3 Pro):

(2048, 2048) (2048,) Device(gpu, 0)

Its companion mlx-lm runs and fine-tunes LLMs from the command line. The mlx-community organisation on Hugging Face hosts thousands of pre-converted, pre-quantised models.

uv run mlx_lm.generate --prompt "Explain attention in two sentences."   # default: Llama-3.2-3B-Instruct-4bit
uv run mlx_lm.chat                                                     # an interactive chat REPL
uv run mlx_lm.lora --model <hf-model> --train --data <folder with train.jsonl, valid.jsonl>

mlx_lm.lora on a quantised model is QLoRA, which is how you fine-tune a 7–8B model on an 18 GB laptop (LoRA, the LoRA project, MLX-LM LoRA guide). For models that nearly fill memory, mlx-lm's README suggests raising the GPU's wired-memory limit with sudo sysctl iogpu.wired_limit_mb=N, with N above the model's size and below total memory; leave headroom for the operating system, and note it resets on reboot.

Step 5: run open-weight models with llama.cpp or Ollama

llama.cpp is a dependency-free C/C++ inference engine that treats Apple silicon as a first-class target (Metal, Accelerate and ARM NEON) and supports 1.5- to 8-bit quantisation. It reads models in the GGUF format, a single file holding weights, tokenizer and metadata. As of October 2026 its README's quick start is:

# Install (or: brew install llama.cpp), then download and run a model from Hugging Face:
curl -LsSf https://llama.app/install.sh | sh
llama cli   -hf ggml-org/Qwen3.5-0.8B-GGUF      # chat in the terminal
llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF      # an OpenAI-compatible API server

Older builds name these binaries llama-cli and llama-server. Ollama wraps the same engine in a model manager and a background service with a local HTTP API:

brew install ollama          # or download the app from ollama.com
ollama run qwen3:8b          # pulls a 5.2 GB 4-bit model, then chats
ollama list                  # what you have downloaded

LM Studio does the same with a graphical interface. All three expose an OpenAI-compatible endpoint, so the code you write against a local model also works against a hosted one, which is useful for the applied track.

Step 6: when the Mac is not enough

Use the Mac for everything on this site, for inference of models up to about 14B parameters at 4 bits, for LoRA fine-tuning of models up to about 8B, and for training small models from scratch (the tiny GPT project). Move to a cloud GPU when you need CUDA-only software (Triton kernels, FlashAttention, vLLM), full fine-tuning, or simply more throughput.

Free options.

  • Google Colab: notebooks with free, but limited and fluctuating, GPU access. Google's FAQ says free sessions can last at most 12 hours and that the GPU types and usage limits change over time and are not published.
  • Kaggle notebooks: a weekly GPU quota (commonly reported as about 30 hours; your account settings show the current figure) on an NVIDIA P100 or two T4s. See Kaggle's GPU usage tips.

Paid, by the hour. Lambda, RunPod, Modal and Lightning AI rent single GPUs to multi-GPU nodes by the hour or second. Prices change often, so check them on the day; the method for estimating a job's cost does not change (The maths, below). Two rules save money: develop and debug on your Mac or a free notebook and rent only for the final run, and set an automatic shutdown, since an idle rented GPU costs exactly as much as a busy one.

Step 7: the rest of the bench

  • git, with one repository for your learning projects and one commit per working step.
  • A lab notebook: one Markdown file, dated entries (How to study).
  • Anki, for the flashcards that keep this site in your head (How to study).
  • A Hugging Face account, for downloading gated models and datasets (Hub CLI).
  • Experiment tracking: a CSV file and matplotlib are enough for this site's projects; tools such as Weights & Biases help once you run many experiments (MLOps).

One heavy job at a time

An 18 GB machine shared between a browser, an editor, a notebook kernel and a model server runs out of memory quickly, and macOS responds by swapping to disk, which makes everything slow at once. Run one heavy job (a training run, a model server, a large notebook) at a time, watch Memory Pressure in Activity Monitor, and stop servers and kernels when you finish.

First principles

Why is the laptop limited by memory rather than by arithmetic, and why does that make Apple silicon unusually good for local LLMs?

Generating text is memory-bound. To produce one token, a model multiplies a single vector by every weight matrix: about 2 FLOPs per parameter, but every parameter must be read from memory. The arithmetic intensity (FLOPs per byte moved) of batch-1 decoding at 4-bit weights is about \(2 / 0.5 = 4\) FLOPs per byte. The M3 Pro moves 150 GB/s and computes well over a trillion FLOP/s, so it can do hundreds of FLOPs in the time it fetches each byte. Decoding uses a small fraction of the arithmetic and all of the bandwidth. The roofline model makes this precise.

Unified memory removes the capacity cliff. A discrete laptop GPU might have 8 GB of VRAM; a model that needs 9 GB must be split across the slow PCIe bus. On Apple silicon the GPU can address most of system memory directly, so capacity degrades gracefully.

Training is different. Training processes many tokens per weight read (large batches), so it is compute-bound, and it needs memory for gradients and optimiser state, not only weights. This is where datacentre GPUs, with far more arithmetic throughput and memory, are irreplaceable.

The maths

Memory for inference

For \(N\) parameters at \(b\) bits:

\[ M_{\text{weights}} = \frac{N\,b}{8}\ \text{bytes}. \]

The KV cache stores a key and a value vector per layer, per KV head, per token. For \(L\) layers, \(H_{kv}\) KV heads of size \(d_h\), \(T\) cached tokens and \(s\) bytes per number:

\[ M_{\text{KV}} = 2\,L\,H_{kv}\,d_h\,s\,T. \]

Worked example (Llama 3.1 8B). The Llama 3 paper gives 32 layers and 8 KV heads; with model width 4,096 and 32 attention heads, \(d_h = 128\). In 16-bit, each token costs \(2 \times 32 \times 8 \times 128 \times 2 = 131{,}072\) bytes \(= 128\) KiB, so an 8,192-token context needs \(1.07\) GB. Grouped-query attention is why this is small: with 32 KV heads instead of 8 it would be four times larger (KV cache and efficient attention).

A ceiling on generation speed

If decoding reads all weights once per token, then

\[ \text{tokens per second} \;\le\; \frac{\text{memory bandwidth}}{M_{\text{weights}}}. \]

At 150 GB/s: an 8B model at 4 bits (4 GB of weights) is capped near 38 tokens per second; at 16 bits (16 GB) it would be capped near 9, if it fitted. Real speeds are lower because of the KV cache reads, the overheads and the fact that 4-bit formats store scales alongside the weights (about 5 bits per weight on average for typical 4-bit GGUF files).

Memory for training

Full training with Adam in mixed precision needs, per parameter, roughly 2 bytes for 16-bit weights, 2 for gradients, 4 for an FP32 master copy and 8 for Adam's two moment estimates:

\[ M_{\text{train}} \approx 16N\ \text{bytes} + \text{activations}. \]

A 1B-parameter model therefore needs about 16 GB before activations: too much for this laptop. LoRA trains only small low-rank adapters and keeps the base frozen (and, with QLoRA, quantised), which is why it fits (LoRA).

Cost of a cloud run

With training compute \(C \approx 6ND\) (The map of AI), a GPU of peak throughput \(P\) FLOP/s at model FLOPs utilisation \(u\) (typically 0.3–0.5 for well-tuned training), and a price \(c\) per GPU-hour:

\[ \text{cost} \approx \frac{6ND}{u\,P \times 3600}\; c. \]

A 125M-parameter model on 2.5B tokens is \(1.9\times10^{18}\) FLOPs; at \(u P = 4\times10^{14}\) FLOP/s that is 1.3 GPU-hours, so a few hours of a rented GPU covers a GPT-2-small-scale experiment.

Build it

Two programs you can run on any machine. The first answers "what fits?" for your budget. It assumes an 8B-shaped KV cache for every model, which is a simplification (larger models have larger caches).

# What fits in 18 GB? Weights, KV cache, and a decode-speed ceiling from memory bandwidth.
GPU_BUDGET_GB = 14.3      # Metal's recommended working set measured on an 18 GB M3 Pro
BANDWIDTH_GBs = 150       # M3 Pro unified-memory bandwidth (Apple spec)

def weights_gb(params_b, bits):
    return params_b * 1e9 * bits / 8 / 1e9

def kv_cache_gb(layers, kv_heads, head_dim, tokens, bytes_per=2):
    return 2 * layers * kv_heads * head_dim * bytes_per * tokens / 1e9   # K and V

kv = kv_cache_gb(layers=32, kv_heads=8, head_dim=128, tokens=8192)       # Llama 3.1 8B shape
print(f"KV cache, Llama-3.1-8B shape, 8,192 tokens, FP16: {kv:.2f} GB "
      f"({2*32*8*128*2/1024:.0f} KiB per token)\n")

print(f"{'model':>6s} {'bits':>4s} {'weights GB':>10s} {'+KV 8k':>7s}  fits?  max tok/s")
for params in (1, 3, 8, 14, 32, 70):
    for bits in (16, 8, 4):
        w = weights_gb(params, bits)
        total = w + kv
        fits = "yes" if total < GPU_BUDGET_GB else "no"
        print(f"{params:5d}B {bits:4d} {w:10.1f} {total:7.1f}  {fits:5s}  {BANDWIDTH_GBs / w:8.0f}")

Output:

KV cache, Llama-3.1-8B shape, 8,192 tokens, FP16: 1.07 GB (128 KiB per token)

 model bits weights GB  +KV 8k  fits?  max tok/s
    1B   16        2.0     3.1  yes          75
    1B    8        1.0     2.1  yes         150
    1B    4        0.5     1.6  yes         300
    3B   16        6.0     7.1  yes          25
    3B    8        3.0     4.1  yes          50
    3B    4        1.5     2.6  yes         100
    8B   16       16.0    17.1  no            9
    8B    8        8.0     9.1  yes          19
    8B    4        4.0     5.1  yes          38
   14B   16       28.0    29.1  no            5
   14B    8       14.0    15.1  no           11
   14B    4        7.0     8.1  yes          21
   32B   16       64.0    65.1  no            2
   32B    8       32.0    33.1  no            5
   32B    4       16.0    17.1  no            9
   70B   16      140.0   141.1  no            1
   70B    8       70.0    71.1  no            2
   70B    4       35.0    36.1  no            4

The second measures your own machine. NumPy hands matrix multiplication to the system's BLAS library (Apple's Accelerate on a Mac), so this is the CPU's real dense-maths throughput.

# Measure your machine: matrix-multiply throughput in NumPy (CPU, via the BLAS NumPy links).
import time
import numpy as np

def matmul_gflops(n, dtype, reps=5):
    a = np.random.default_rng(0).standard_normal((n, n)).astype(dtype)
    b = np.random.default_rng(1).standard_normal((n, n)).astype(dtype)
    a @ b                                            # warm-up
    t = time.perf_counter()
    for _ in range(reps):
        a @ b
    dt = (time.perf_counter() - t) / reps
    return 2 * n**3 / dt / 1e9                       # an n×n matmul is 2n³ FLOPs

for n in (256, 1024, 2048):
    for dtype in (np.float64, np.float32):
        print(f"n={n:5d} {np.dtype(dtype).name:8s} {matmul_gflops(n, dtype):8.1f} GFLOP/s")

# What would C = 6ND cost at the best rate above? A 10M-parameter model on 100M tokens:
C = 6 * 10e6 * 100e6
best = matmul_gflops(2048, np.float32) * 1e9
print(f"\n6ND for 10M params x 100M tokens = {C:.1e} FLOPs -> {C / best / 3600:.1f} h at that rate")

Output on an 18 GB M3 Pro (your numbers will differ):

n=  256 float64     367.4 GFLOP/s
n=  256 float32     773.1 GFLOP/s
n= 1024 float64     282.9 GFLOP/s
n= 1024 float32    1130.3 GFLOP/s
n= 2048 float64     278.4 GFLOP/s
n= 2048 float32    1144.8 GFLOP/s

6ND for 10M params x 100M tokens = 6.0e+15 FLOPs -> 1.5 h at that rate

Three lessons are in that output. Single precision is about four times faster than double, which is why deep learning never uses float64. Small matrices run below peak because there is too little work to hide overheads. And the 1.5-hour estimate is a floor: a real training run reaches a fraction of peak matmul throughput, which is the gap that kernels and mixed precision exist to close.

Things to try

  • Run the PyTorch snippet with device = "cpu" and "mps" at sizes 512, 2048 and 8192, and find the size at which the GPU starts to win.
  • Download a 4-bit 3B model with mlx-lm and a 4-bit 8B model with Ollama; compare their measured tokens per second with the bandwidth ceilings in the table.
  • Change GPU_BUDGET_GB to your own machine's value and find the largest model you can run at 8k context.
  • Estimate the cost of training the tiny GPT on a rented GPU with the cost formula, then compare with how long it takes on your Mac.

Check yourself

Why does an 8B model at 4 bits generate faster than the same model at 16 bits on a Mac, if the arithmetic is the same?

Decoding is memory-bound: each token reads every weight once. At 4 bits there are a quarter as many bytes to read, so the bandwidth ceiling on tokens per second is four times higher.

How much KV cache does a 32-layer model with 8 KV heads of size 128 need for 32,768 tokens in FP16?

\(2 \times 32 \times 8 \times 128 \times 2 \times 32{,}768 = 4.29\) GB (128 KiB per token).

Your PyTorch script fails on MPS with an error about float64. What do you change?

Create tensors in float32 (or lower), for example by converting NumPy arrays with torch.from_numpy(x).float(), since MPS has no float64 support.

Why is a 1B-parameter model too big to fully fine-tune with Adam on an 18 GB laptop, but fine to run?

Running it needs about 2 GB in 16-bit. Full training with mixed-precision Adam needs about 16 bytes per parameter (weights, gradients, FP32 master weights, two Adam moments), about 16 GB before activations. LoRA avoids most of that by training only small adapters.

Why use uv's lockfile and fixed seeds?

So that a result can be reproduced: the lockfile pins every package version; the seed fixes the random numbers. Without both, a change in a result might come from the environment rather than from your change.

When should you move from your Mac to a cloud GPU?

When you need CUDA-only software (Triton, FlashAttention, vLLM), full fine-tuning or training beyond a few hundred million parameters, or more throughput than the laptop gives; develop and debug locally first, then rent for the final run with an automatic shutdown.

Go deeper

Official documentation

  • uv documentation — Astral. Projects, Python versions, lockfiles; read "Projects" and the Jupyter integration guide.
  • MPS backend — PyTorch. The official note on using the Apple GPU from PyTorch.
  • Accelerated PyTorch training on Mac — Apple. Apple's own setup page for PyTorch on Metal.
  • MLX documentation — Apple machine learning research. Start with "Unified memory" and "Lazy evaluation".
  • Colab FAQ — Google. What the free tier does and does not promise.

Code

  • ml-explore/mlx — The framework and its examples.
  • ml-explore/mlx-lm — Generate, chat, convert, quantise and LoRA-fine-tune LLMs on a Mac.
  • ggml-org/llama.cpp — The local inference engine underneath most desktop LLM tools.
  • karpathy/nanoGPT — The smallest serious GPT training code; runs on MPS for small configurations.

Articles and specifications

Videos

  • Let's reproduce GPT-2 (124M) — Andrej Karpathy, 2024. Four hours on what it takes to train a real model, including the move from laptop to rented GPUs.

Where this leads