%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px', 'lineColor':'#999999', 'transitionColor':'#999999'}}}%%
stateDiagram-v2
Fetch: Fetch the next instruction from RAM
Execute: Execute the instruction
Store: Store the result
[*] --> Fetch
Fetch --> Execute
Execute --> Store
Store --> Fetch
Lab 11: Server Resources and Scaling
How big does a server need to be? Three resources decide: CPU, RAM, and storage, plus a GPU for some modeling work. The examples come from the t3.micro we’ve been running since Lab 7; scaling it up when it runs short is covered in Instance Size.
How computers work (for data science)
Each comprehension question below asks which part of a computer we’d upgrade to fix a problem. To answer them, it helps to know what each part does. The chapter explains the parts from a system administrator’s point of view. The sections below add the R and Python side, with links to Wikipedia for more depth.
The CPU
The central processing unit (CPU) is the part of the computer that runs your code. Every program, from a Python script to the operating system, is a long list of small instructions. The CPU works through that list in a cycle:
Each trip around this cycle takes a tiny fraction of a second. The number of cycles per second is the clock speed, measured in gigahertz (GHz). A 3 GHz CPU runs about three billion cycles each second. A higher clock speed means each step of your code finishes sooner.
R and Python add a layer between our code and the CPU. Both are interpreted languages, so each line we write turns into many CPU instructions while it runs. Vectorized functions skip most of that work by handing the whole job to compiled C code. The two versions below give the same answer. On my laptop, with a vector of 10 million numbers, the vectorized one runs about 90 times faster in both R and Python:
x <- runif(1e7)
# loop: the interpreter handles every element
total <- 0
for (i in seq_along(x)) total <- total + x[i]
# vectorized: one call to compiled code
total <- sum(x)import numpy as np
x = np.random.rand(10_000_000)
# loop: the interpreter handles every element
total = 0.0
for value in x:
total += value
# vectorized: one call to compiled code
total = x.sum()Before paying for a faster CPU, it’s worth looking for loops like these. Rewriting a loop takes a few minutes; a bigger instance costs money every hour it runs.
Cores
A core is a complete processing unit inside the CPU. A CPU with more than one core is a multi-core processor. Each core runs its own list of instructions, so a four core CPU can work on four tasks at once. Extra cores only help when the work splits into independent pieces:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
flowchart TD
Job(["One job"])
Split{"Can the job split into<br>independent pieces?"}
subgraph Many["<strong>Four cores</strong>"]
C1("Core 1")
C2("Core 2")
C3("Core 3")
C4("Core 4")
end
One("One core does all the work<br>while the others sit idle")
Join(["Combine the results"])
Job --> Split
Split -->|"Yes"| C1 & C2 & C3 & C4
C1 & C2 & C3 & C4 --> Join
Split -->|"No"| One
Most R and Python code runs on a single core unless we tell it otherwise (with packages like {future} in R or multiprocessing in Python). If each step depends on the result of the step before it, the extra cores have nothing to do. This is why faster cores often help more than more cores.
We can check how many cores R and Python can see:
parallel::detectCores()import os
os.cpu_count()Both return 2 on the t3.micro, but that count is threads, not cores. AWS sells virtual CPUs (vCPUs), and each vCPU is one hardware thread. The t3.micro has one physical core running two threads, so it shows up as 2 vCPUs.
Some modeling packages use every core without being asked. In R, {ranger} grows random forest trees on all available cores by default. In Python, scikit-learn models with an n_jobs argument use every core when we set n_jobs=-1.
Parallel work has a RAM cost, too. Each worker process usually gets its own copy of the data, so four workers can need close to four times the memory of one.
RAM
Random access memory (RAM) holds the data and code the CPU is using right now. RAM is like the top of a desk: everything on it is within arm’s reach, but the space is limited. RAM is fast because the CPU can read any location in it directly. It’s also temporary, so everything in RAM disappears when the computer turns off.
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
flowchart TD
Load(["Load a dataset"])
Fit{"Does it fit<br>in RAM?"}
Work("The analysis runs")
Crash(["The session crashes"])
Load --> Fit
Fit -->|"Yes"| Work
Fit -->|"No"| Crash
When we load a dataset in R or Python, the whole thing is copied into RAM. If it doesn’t fit, the session doesn’t just slow down; it crashes. RAM is usually the first resource a data science workload runs out of. The t3.micro we’ve been using has only 1 GB.
A dataset can take up much more room in RAM than it does on disk. Text columns are the usual cause, along with the temporary copies R and Python make while transforming data. We can measure how much memory an object is using with lobstr::obj_size() or df.memory_usage():
lobstr::obj_size(penguins)df.memory_usage(deep=True).sum() # bytesComparing these numbers to the file size on disk shows how close a dataset is to the limit. The rule of thumb in the first comprehension question leaves room for this gap.
Storage
Storage (a hard drive or solid state drive) keeps files for the long term. If RAM is the desk, storage is the filing cabinet across the room. It holds far more, and it keeps everything when the power is off. The trade off is speed: reading from even a fast solid state drive takes about a thousand times longer than reading from RAM.
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
flowchart TD
subgraph Proc["<strong>Runs the code</strong>"]
Cpu("CPU")
end
subgraph Mem["<strong>Fast, small, temporary</strong>"]
Ram[("RAM")]
end
subgraph Disk["<strong>Slower, large, permanent</strong>"]
Store[("Storage")]
end
Proc <--> Mem <--> Disk
Because storage is slower, the computer copies data into RAM before the CPU works on it. On an EC2 instance, storage is an Elastic Block Store (EBS) volume attached to the server. We can make the volume bigger without changing the instance type.
Data science projects fill storage faster than we might expect. Package libraries, virtual environments, saved models, and data files all live there. A single deep learning package like PyTorch can take up several gigabytes on its own. We can see how much room the renv and uv package caches are using with du:
du -sh ~/.cache/R ~/.cache/uvFile format matters, too. A Parquet file is usually much smaller than the same data saved as a CSV. R ({arrow}) and Python (pyarrow) also read it faster, because the data is compressed and stored by column.
GPUs
A graphics processing unit (GPU) is a processor built from thousands of small, simple cores. GPUs were designed to draw graphics, which means running the same calculation on millions of pixels at once. Training a deep learning model involves the same kind of math (large matrix multiplications). A GPU’s thousands of cores can finish that work in hours instead of days.
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
flowchart TD
subgraph Cpu["<strong>CPU: a few strong cores</strong>"]
direction LR
c1("core") ~~~ c2("core") ~~~ c3("core") ~~~ c4("core")
end
subgraph Gpu["<strong>GPU: many small cores</strong>"]
direction LR
g0("core") ~~~ g1("core") ~~~ g2("core") ~~~ g3("core") ~~~ g4("core") ~~~ g5("core")
g6("core") ~~~ g7("core") ~~~ g8("core") ~~~ g9("core") ~~~ g10("core") ~~~ g11("core")
g12("core") ~~~ g13("core") ~~~ g14("core") ~~~ g15("core") ~~~ g16("core") ~~~ g17("core")
end
Cpu ~~~ Gpu
classDef big font-size:18px
classDef small font-size:12px
class c1,c2,c3,c4 big
class g0,g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15,g16,g17 small
GPUs come with three catches:
- They’re expensive.
- Our code has to be written (or configured) to use one.
- Code that runs one step at a time gets nothing from a GPU.
Most of the data science toolkit never touches a GPU. {dplyr}, {pandas}, and most of {tidymodels} and scikit-learn run on the CPU. GPUs matter for deep learning frameworks like PyTorch and TensorFlow (and their R interfaces, {torch} and {keras3}), and for a few model libraries like XGBoost. In each case we check that the GPU is visible, then move the work onto it:
import torch
torch.cuda.is_available()
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)- 1
-
TrueifPyTorchcan see a GPU - 2
- Move the model’s weights onto the GPU
library(torch)
cuda_is_available()- 1
-
TRUEiftorchcan see a GPU
A GPU also has its own memory (VRAM), separate from the server’s RAM. The model and each batch of data have to fit in VRAM, which brings back the same “does it fit?” question from the RAM section.
How the parts work together
The diagram below follows data through a typical analysis:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
sequenceDiagram
participant S as Storage
participant R as RAM
participant C as CPU or GPU
S->>R: Loads the data
R->>C: Reads the data
C->>C: Runs the computation
C->>R: Writes the results
R->>S: Saves the results
Data starts in storage, gets copied into RAM, and is processed by the CPU (or GPU). The results go back into RAM, and we save them to storage when we want to keep them. Each comprehension question below describes a bottleneck at one of these steps.
In a typical R or Python script, each step maps to a familiar function call:
| Step | R | Python |
|---|---|---|
| Storage to RAM | readr::read_csv() |
pd.read_csv() |
| CPU work | dplyr::mutate(), lm() |
df.assign(), model.fit() |
| RAM to storage | arrow::write_parquet(), saveRDS() |
df.to_parquet(), joblib.dump() |
Comprehension questions
“Think about the scenarios below. Which part of your computer would you want to upgrade to solve the problem?”
“1. You try to load a
.csvfile into{pandas}in Python. It churns for a while and then crashes.”
RAM. {pandas} loads the whole file into memory, and transformations make temporary copies on top of that. When the data doesn’t fit, the session crashes instead of slowing down. The chapter’s rule of thumb is to have at least three times as much RAM as the largest dataset:
\[\text{Amount of RAM} \ge 3 \times \text{max amount of data}\]
Before buying more, it’s worth asking whether the whole file needs to be in memory at once. Reading only some columns, or switching to a database or Parquet file, can load far less.
With a 400 MB file as an example, the 3x rule already asks for more memory than a t3.micro has:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'xyChart': {'plotColorPalette': '#2A6F77'}}}}%%
xychart-beta
title "Loading a 400 MB CSV on a t3.micro"
x-axis ["CSV on disk", "RAM needed (3x)", "t3.micro RAM"]
y-axis "Gigabytes" 0 --> 1.5
bar [0.4, 1.2, 1.0]
“2. You go to build a new ML model on your data. You’d like to re-train the model once a day, but training this model takes 26 hours on your laptop.”
A faster CPU (or a GPU). A 26 hour job can’t run once a day no matter how much RAM or storage the machine has. If the model is parallel (deep learning or tree based models like XGBoost), a GPU is the upgrade that turns days into hours. The chapter’s advice is to try faster CPU cores first.
The order to try things in looks like this:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
flowchart TD
Job(["<strong>Training takes 26 hours</strong>"])
Fast("Faster CPU cores<br/><em>C family instance</em>")
Check{"Fits in a day?"}
Par{"Highly parallel model?<br/><em>deep learning, trees</em>"}
GPU("GPU instance<br/><em>P family, set in the code</em>")
Done(["<strong>Retrain daily</strong>"])
Rethink("Rethink the job<br/><em>less data, fewer features</em>")
Job --> Fast --> Check
Check --"yes"--> Done
Check --"no"--> Par
Par --"yes"--> GPU --> Done
Par --"no"--> Rethink
style Job fill:#D2562B,stroke:#fff,stroke-width:2px,color:#fff
style Fast fill:#2A6F77,stroke:#fff,stroke-width:1px,color:#fff
style Check fill:#E8A33D,stroke:#000,stroke-width:1px,color:#000
style Par fill:#E8A33D,stroke:#000,stroke-width:1px,color:#000
style GPU fill:#5B8C5A,stroke:#fff,stroke-width:1px,color:#fff
style Rethink fill:#666,stroke:#999,stroke-width:1px,color:#fff
style Done fill:#1B2A41,stroke:#fff,stroke-width:2px,color:#fff
“3. You design a visualization using the
{matplotlib}package and want to create one version of the visualization for each US state. You could do it in a loop, but it would be faster to parallelize the plot creation. Right now, you’re running on at2.smallwith 1 CPU.”
More CPU cores. Parallelizing means running several plots at the same time, one per core, and a single core can only run one at a time. Fifty plots on one core is still a loop. A GPU doesn’t help here because {matplotlib} draws on the CPU.
Assume each plot takes one minute. With the same total work, four cores finish in about a quarter of the time:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px', 'taskBkgColor':'#2A6F77', 'taskBorderColor':'#2A6F77', 'taskTextColor':'#ffffff', 'taskTextLightColor':'#ffffff', 'taskTextOutsideColor':'#E8A33D', 'sectionBkgColor':'#E8E8E8', 'altSectionBkgColor':'#F5F5F5', 'gridColor':'#999999'}}}%%
gantt
title 50 plots, one core vs. four
dateFormat HH:mm
axisFormat %H:%M
section 1 core
1 to 13 :a1, 00:00, 13m
14 to 26 :a2, after a1, 13m
27 to 38 :a3, after a2, 12m
39 to 50 :a4, after a3, 12m
section 4 cores
1 to 13 :b1, 00:00, 13m
14 to 26 :b2, 00:00, 13m
27 to 38 :b3, 00:00, 12m
39 to 50 :b4, 00:00, 12m
“Draw a mind map of the following: CPU, RAM, Storage, Operations Per Second, Parallel Operations, GPU, Machine Learning.”
The chapter’s analogy is a factory that does addition problems. The CPU is the assembly line, RAM is the space next to the line where work waits, and storage is the warehouse next door. The mind map groups the other terms under the resource they describe:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
mindmap
root((Server resources))
CPU
Few fast cores
Operations Per Second
GPU
Many slow cores
Parallel Operations
Machine Learning
RAM
Data being worked on
Wiped on restart
Storage
Saved files and packages
Slow but permanent
“What are the architectural differences between a CPU and a GPU? Why does this make a GPU particularly good for Machine Learning?”
A CPU has a handful of fast cores, usually 4 to 16 on a laptop. A GPU has hundreds or thousands of slow ones: 700 to 4,000 on a mid range card, each running at 1 to 10 percent of a CPU core’s speed. The CPU is built to finish one problem quickly. The GPU is built to work on thousands of small problems at once.
Training most machine learning models is that kind of work. The same arithmetic repeats over many rows, weights, or trees, and each piece is independent of the others. When work splits that way, the number of cores matters more than the speed of any one core. A GPU can then train in hours what a CPU trains in days.
Step by step R and Python code is the opposite case, so it runs better on fewer, faster CPU cores.
Placing each chip by core count and core speed shows why they suit different work:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px', 'quadrant1Fill':'#1B2A41', 'quadrant2Fill':'#2A6F77', 'quadrant3Fill':'#1B2A41', 'quadrant4Fill':'#5B8C5A', 'quadrant1TextFill':'#ffffff', 'quadrant2TextFill':'#ffffff', 'quadrant3TextFill':'#ffffff', 'quadrant4TextFill':'#ffffff', 'quadrantPointFill':'#E8A33D', 'quadrantPointTextFill':'#ffffff', 'quadrantInternalBorderStrokeFill':'#ffffff', 'quadrantExternalBorderStrokeFill':'#999999'}}}%%
quadrantChart
title Core count vs. core speed
x-axis Few cores --> Many cores
y-axis Slow cores --> Fast cores
quadrant-1 Many and fast
quadrant-2 CPU territory
quadrant-3 Few and slow
quadrant-4 GPU territory
t3.micro CPU: [0.12, 0.62]
Laptop CPU: [0.15, 0.82]
Mid range GPU: [0.85, 0.18]
“How would you do the following?”
“1. Find all running JupyterHub processes that belong to the user
alexkgold.”
ps aux lists every process with its owner, and grep narrows it down:
ps aux | grep jupyterhub | grep alexkgoldEach | passes one command’s output to the next, and each grep keeps fewer lines:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
flowchart TD
Ps("<code>ps aux</code><br/><em>every process, one per line</em>")
G1("<code>grep jupyterhub</code><br/><em>only lines mentioning jupyterhub</em>")
G2("<code>grep alexkgold</code><br/><em>only lines owned by alexkgold</em>")
Out[/"JupyterHub processes owned by alexkgold"/]
Ps -->|"pipe"| G1 -->|"pipe"| G2 --> Out
style Ps fill:#2A6F77,stroke:#fff,stroke-width:1px,color:#fff
style G1 fill:#2A6F77,stroke:#fff,stroke-width:1px,color:#fff
style G2 fill:#2A6F77,stroke:#fff,stroke-width:1px,color:#fff
style Out fill:#E8A33D,stroke:#000,stroke-width:1px,color:#000
ps -u alexkgold lists only that user’s processes, so ps -u alexkgold | grep jupyterhub gets to the same place. Our instance doesn’t run JupyterHub, but the same pattern finds the app from Installing a Real Application, which runs as its service account:
ps -u baseball-trajectory -o pid,%cpu,%mem,cmdIf one of these processes is running away with the CPU, its PID goes to kill. For a systemd service, sudo systemctl restart is the better tool.
“2. Find the different disks attached to your server and see how full each one is.”
lsblk lists the disks and partitions, and df -h shows how full each mounted filesystem is:
lsblk
df -hOn an EC2 instance the root EBS volume usually shows up as nvme0n1, mounted at /. -h prints sizes in K, M, and G instead of blocks.
lsblk shows the whole tree, including partitions that aren’t mounted; df -h reports only the mounted ones. On an AL2023 instance the tree usually looks like this:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
block-beta
columns 3
disk["nvme0n1: EBS root volume"]:3
space:3
p1["partition: nvme0n1p1"] p127["partition: nvme0n1p127"] p128["partition: nvme0n1p128"]
m1["mounted at /"] b1["BIOS boot, not mounted"] m128["mounted at /boot/efi"]
disk --> p1
disk --> p127
disk --> p128
style disk fill:#1B2A41,stroke:#fff,color:#fff
style m1 fill:#2A6F77,stroke:#fff,color:#fff
style m128 fill:#2A6F77,stroke:#fff,color:#fff
style b1 fill:#666,stroke:#999,color:#fff
“3. Find the biggest files in each user’s home directory.”
du measures sizes, sort -rh puts the biggest first, and head keeps the top of the list. Home directories belong to other users, so this needs sudo:
sudo du -ah /home | sort -rh | head -n 20-a includes files, not just directories. To get a short list per user instead of one combined list, loop over the home directories:
for d in /home/*; do
echo "== $d"
sudo du -ah "$d" | sort -rh | head -n 5
doneEach stage of the pipeline narrows the list:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
flowchart TD
Home[("<strong>/home</strong>")]
Du("<code>sudo du -ah</code><br/><em>size of every file and folder</em>")
Sort("<code>sort -rh</code><br/><em>biggest first, reads K, M, G</em>")
Head("<code>head -n 20</code><br/><em>keep the top 20</em>")
Out[/"Top 20 files and folders"/]
Home --> Du --> Sort --> Head --> Out
style Home fill:#666,stroke:#999,stroke-width:1px,color:#fff
style Du fill:#2A6F77,stroke:#fff,stroke-width:1px,color:#fff
style Sort fill:#2A6F77,stroke:#fff,stroke-width:1px,color:#fff
style Head fill:#2A6F77,stroke:#fff,stroke-width:1px,color:#fff
style Out fill:#E8A33D,stroke:#000,stroke-width:1px,color:#000
Recap
CPU speed, core count, RAM, and storage each limit a different kind of work. A GPU helps only with parallel work that the code is told to send to it.
RAM runs out first for most data science work. Data takes more room in memory than on disk, so plan for about three times the largest dataset.
Extra cores help only when a job splits into independent pieces, and most R and Python code has to be told to use them.
ps,lsblk,df -h, anddushow what a server is running and where its storage went. Resizing the instance is covered in Instance Size.