v9.1.1
Menu

Chapter 4: Cloud & AWS Essentials

Master cloud infrastructure for ML — from EC2 GPU instances and S3 storage to IAM security, VPC networking, serverless inference, SageMaker training, and cost optimization strategies.

Topics
8
Videos
3
Min read
77

Chapter Overview

Cloud computing transformed ML from a discipline limited by hardware budgets to one limited only by ideas. Before the cloud, training a large model required purchasing expensive GPU servers and waiting weeks for delivery. Today, you can launch 8x A100 GPUs in under a minute, train for a few hours, and tear them down — paying only for what you used.

This chapter covers the AWS services that every ML engineer needs to know. You will learn to launch GPU instances (EC2) for training, store datasets and model artifacts (S3), secure access with IAM policies, build isolated networks (VPC), deploy serverless inference endpoints (Lambda), use managed training infrastructure (SageMaker), and keep costs under control with billing alerts and spot instances.

The goal is practical fluency: by the end of this chapter, you will be able to take any ML project from your laptop to the cloud — training on GPU instances, storing checkpoints in S3, and deploying models as scalable endpoints — while keeping costs predictable and infrastructure secure.

Chapter Roadmap

Click any topic to jump in

Explainer video
1
Cloud Concepts

Why cloud beats on-prem for ML — pay-per-use compute, elastic scaling, regions, AZs, and the shared responsibility model.

On-Prem vs CloudIaaS / PaaS / SaaSRegionsAvailability ZonesShared Responsibility ModelTerraformLocalStack
Compute and storage are the foundation

EC2 runs the GPUs, S3 stores the data and models

2
EC2 & Compute

GPU instance families (p3/p4/g5), AMIs, EBS volumes, spot vs on-demand, and how to right-size training nodes.

EC2 Instance TypesGPU Instance FamiliesSpot InstancesOn-Demand vs Reserved vs SpotAMIs (Amazon Machine Images)Key PairsSecurity Groupsboto3
3
S3 & Storage

Object storage for datasets and checkpoints — buckets, prefixes, storage classes, lifecycle rules, and 11-nines durability.

BucketsObjectsStorage ClassesLifecycle PoliciesVersioningaws s3 syncs3fs / s3fs-fuseboto3
Secure access and isolation

IAM controls who, VPC controls where

4
IAM & Security

Users, roles, policies, instance profiles — least-privilege access for training jobs and inference endpoints.

IAM UsersIAM RolesIAM PoliciesPrinciple of Least PrivilegeManaged PoliciesIAM Groupsaws-vaultMFA
5
VPC & Networking

Private subnets, security groups, NAT gateways, VPC endpoints — isolating training clusters from the public internet.

VPCSubnetsSecurity GroupsNACLs (Network ACLs)Internet GatewayNAT GatewayVPC EndpointsTerraform for VPC
Deploy models to production

Serverless for light traffic, SageMaker for managed ML

6
Lambda & Serverless

Event-driven inference, API Gateway, cold starts, container images — the cheapest path to production for low-traffic models.

Lambda FunctionsTriggersCold StartsLayersMemory/Timeout LimitsContainer Image SupportAWS SAMServerless Framework
7
ECR & SageMaker

Container registries for ML images, managed training jobs, hyperparameter tuning, and one-click model deployment.

Amazon ECRECR Lifecycle PoliciesSageMaker Training JobsSageMaker EndpointsSageMaker EstimatorBring Your Own Container (BYOC)SageMaker StudioSageMaker SDK
Keep costs predictable
8
Cost Management

Billing alerts, cost allocation tags, spot instances, and savings plans — keeping the AWS bill under control.

On-Demand PricingSpot InstancesReserved InstancesSavings PlansBilling AlertsAWS Cost ExplorerRight-SizingInfracost

Topics

8 topics in this chapter

Before cloud computing, training a model meant buying servers, racking them, installing GPUs and running the network yourself. An 8-GPU server costs hundreds of thousands of dollars up front, and then sits idle whenever nobody is training. This chapter starts from that problem: how can an ML team get large amounts of compute exactly when it needs it, and pay nothing when it does not?

Cloud computing answers it by renting. Eight A100 GPUs on an AWS p4d.24xlarge cost about 22 dollars an hour on demand, so a 4-hour run costs under 90 dollars instead of a purchase. AWS, Google Cloud and Azure each offer hundreds of services. For ML engineers the core ones are compute, storage, networking and managed ML platforms. This topic sets up the vocabulary the rest of the chapter uses: the service models (IaaS, PaaS, SaaS), the physical layout of regions and availability zones, the shared responsibility model for security, and the tools that make infrastructure reproducible. Terraform defines it as code, and LocalStack lets you test against an emulator before paying for the real thing.

Definition

Cloud computing, in NIST's definition, is on-demand network access to a shared pool of configurable computing resources (servers, storage, networks, services) that can be provisioned and released quickly with minimal management effort. You pay for what you use, and the provider runs the physical hardware in regions made up of isolated availability zones.

In this topic

  1. 1On-Prem vs Cloud
  2. 2IaaS / PaaS / SaaS
  3. 3Regions
  4. 4Availability Zones
  5. 5Shared Responsibility Model
  6. 6Terraform
  7. 7LocalStack
1 of 7
On-Prem vs Cloud

Own hardware (high upfront cost, full control) vs rent hardware (pay-per-use, managed infrastructure, elastic scaling). On-prem makes sense when you have consistent, predictable GPU demand and the engineering team to manage infrastructure. Cloud makes sense for variable workloads, rapid experimentation, and teams that want to focus on ML rather than hardware.

Many ML teams use a hybrid approach: on-prem for always-running inference endpoints and cloud for burst training jobs that need 8+ GPUs for a few hours.

Mathematical Intuition

Owning has a fixed yearly cost and renting a variable one. Spread over nn years, on-prem costs Ccapex/n+CopexC_{capex}/n + C_{opex} a year, while the cloud costs h⋅ph \cdot p for hh hours at hourly price pp. Break-even is h∗=(Ccapex/n+Copex)/ph^* = (C_{capex}/n + C_{opex}) / p. With the numbers above, h∗≈5,600h^* \approx 5{,}600 hours, or 64 percent of the year. That is why the rule of thumb is about utilization rather than price. Steady, high-utilization workloads favor owning. Bursty experimentation favors renting, and so do teams that cannot keep a server busy most of the day.

Example:

Your ML team trains 4 hours a day, 5 days a week, on an 8-GPU A100 node. Compare buying a server (assume about 250,000 dollars up front, 40,000 dollars a year to operate, and a 3-year life) with renting a p4d.24xlarge on demand at about 21.96 dollars an hour.

2 of 7
IaaS / PaaS / SaaS

The three service models differ in how much of the stack you run yourself. With IaaS (Infrastructure as a Service, such as EC2), the provider runs the hardware and virtualization. You manage the operating system, drivers, runtime and code. With PaaS (Platform as a Service, such as SageMaker or Lambda), the provider also runs the OS and runtime, so you bring code and data. With SaaS (Software as a Service, such as a hosted model API), you only call an endpoint. Each step up removes operational work but also removes control. Most ML teams train on IaaS or PaaS and consume SaaS APIs where they fit.

Mathematical Intuition

Each abstraction layer trades control cc for operational burden bb along an inverse curve c⋅b≈kc \cdot b \approx k. IaaS gives maximum cc (custom kernels, drivers, networking) at maximum bb. SaaS minimizes bb but constrains cc. The optimal layer for a given workload minimizes total cost C=b⋅eng-hours+(1/c)⋅opportunity-costC = b \cdot \text{eng-hours} + (1/c) \cdot \text{opportunity-cost} — most ML teams should use the highest layer their workload tolerates.

3 of 7
Regions

A region is a separate geographic area, such as us-east-1 in Northern Virginia or eu-west-1 in Ireland. Each region is independent, with its own services, prices and quotas. Four things drive the choice. Latency: light in fiber covers about 200 km per millisecond, so a user 6,000 km away pays at least 60 ms per round trip. Law: GDPR and similar rules can require personal data to stay in a jurisdiction. Price, which differs by region. And capacity: new GPU instance types often launch in only a few regions, so check availability before you choose. Data does not leave a region unless you copy it, and cross-region transfer is billed.

Mathematical Intuition

Cross-region latency follows the speed of light: tmin=d/c≈d/(2×108 m/s)t_{min} = d / c \approx d / (2 \times 10^8 \, \text{m/s}) in fiber. New York to Frankfurt (∼6000 km\sim 6000\,\text{km}) has a hard floor of ∼30 ms\sim 30\,\text{ms} one-way, so ∼60 ms\sim 60\,\text{ms} round-trip — before any processing. This is why placing inference endpoints near users matters more than CPU speed for latency-sensitive applications.

4 of 7
Availability Zones

Isolated data centers within a region — deploy across 2+ AZs for fault tolerance. Each AZ has independent power, cooling, and networking. AZs within a region are connected by low-latency links (< 2ms), but a failure in one AZ does not affect others.

For ML training, you typically run in a single AZ (training does not need multi-AZ redundancy). For ML inference endpoints, deploy across 2+ AZs so your API stays up even if one data center fails.

Mathematical Intuition

If each zone is unavailable a fraction pp of the time and failures are independent, a service in kk zones is down only when all are, with probability pkp^k. At p=0.005p = 0.005 (99.5 percent), two zones give p2=2.5×10−5p^2 = 2.5 \times 10^{-5}, about 13 minutes of downtime a year instead of 44 hours. The independence assumption is the weak point. Zones in a region share a control plane and software deployments, and regional incidents do happen, so the real figure is worse than pkp^k. That is why AWS's multi-zone SLA promises 99.99 percent, not 99.9975.

Example:

Your ML inference API runs in us-east-1a only. A power outage in that AZ takes your service offline. How would you architect for fault tolerance?

5 of 7
Shared Responsibility Model

AWS secures the cloud (hardware, network, facilities). You secure what is IN the cloud (data, IAM, encryption, app code). This means AWS ensures the physical servers are secure and patched, but you are responsible for who can access your S3 buckets, what IAM policies your training instances use, and whether your data is encrypted.

The most common security mistakes are: overly permissive IAM policies, public S3 buckets, and hardcoded credentials in code.

Mathematical Intuition

Security failures decompose into provider-controlled PP and customer-controlled CC: total breach probability Pr⁡(breach)=1−(1−P)(1−C)\Pr(\text{breach}) = 1 - (1 - P)(1 - C). AWS reduces PP to near zero via massive investment, so almost all real-world incidents come from CC — misconfigured S3 buckets, leaked IAM keys, overly permissive policies. The math says: spend your security effort on the customer side because that is where the residual risk lives.

6 of 7
Terraform

Terraform is an infrastructure-as-code tool: you describe resources such as VPCs, subnets, instances and buckets in .tf files, and Terraform makes the cloud match. terraform plan compares that desired state with its state file and the real cloud and prints a diff of what it would create, change or destroy. terraform apply then executes it. Because the configuration lives in Git, infrastructure changes get code review, history and rollback like any other code. The common failure modes are manual console edits, which cause drift that the next plan will try to undo, and a lost or shared-but-unlocked state file. Store state remotely with locking.

Mathematical Intuition

Infrastructure as code reduces drift by enforcing a declarative state SdesiredS_{desired} that the system reconciles toward via Δ=Sdesired−Sactual\Delta = S_{desired} - S_{actual}. Terraform's plan-then-apply model converts unplanned manual changes (entropy) into a Markov chain where SactualS_{actual} always converges back to SdesiredS_{desired} on the next apply — making infrastructure idempotent and reviewable rather than a snowflake.

7 of 7
LocalStack

LocalStack is an emulator that runs AWS APIs such as S3, Lambda, SQS and DynamoDB inside a Docker container on your machine, by default on localhost port 4566. Point boto3 or the AWS CLI at that endpoint (endpoint_url) and the same code runs without an AWS account, without credentials and without a bill. That makes it useful for unit and integration tests in CI, and for developing data pipelines offline. The emulation is not perfect. IAM policies are not enforced by default, some services and edge cases are missing, and performance tells you nothing about production. Treat LocalStack as a fast first check, then test against a real staging account.

Mathematical Intuition

Developer iteration speed is dominated by the slowest feedback loop in the cycle. A round-trip to real AWS adds ∼1-10 s\sim 1\text{-}10\,\text{s} per API call plus deployment overhead; LocalStack drops this to ∼10 ms\sim 10\,\text{ms}. Over 100 daily test cycles, this saves ∼1000 s\sim 1000\,\text{s} of developer time per engineer per day — equivalent to several extra hours of focused work per week.

Theory Exercise

Problem:

Your ML startup processes medical imaging data for European hospitals. You need to train models on GPU clusters and serve predictions with < 100ms latency. Discuss which AWS region(s) you would choose, whether to go single-AZ or multi-AZ for training vs. inference, and what GDPR implications affect your architecture.

Hints:
  • GDPR requires that EU citizen data stays within the EU unless specific legal mechanisms are in place
  • Consider the trade-off between GPU availability (us-east-1 has the most GPU types) and data residency requirements
  • Think about whether training and inference have different availability requirements