AWS: Zero to Hero — Week 13: Why Cloud and AI Are Really the Same Story
Week 13 of learning AWS from zero, with Claude as my research partner. Why cloud and AI are really one story: scarce, lumpy GPU compute, UltraClusters, custom Trainium chips, data gravity, and the honest counterpoints. Hands-on: why a new account can’t launch a GPU, napkin math that reproduces Llama 2 7B’s training cost, and an Athena pipeline showing Parquet scans far fewer bytes than CSV.
Series: AWS: Zero to Hero (14 articles)
- …
- 13AWS: Zero to Hero — Week 13: Why Cloud and AI Are Really the Same Story This article
AWS: Zero to Hero — Week 13: Why Cloud and AI Are Really the Same Story
This series started with a question: how are cloud and AI related, and why does it seem like the two grew up together? Twelve weeks later I finally have enough pieces to answer it properly. The short version is that AI isn't something that happens to run on cloud by coincidence. It's close to the ideal workload for the economics cloud computing was built around. The longer version has some real mechanics in it, plus some honest caveats, because the relationship isn't all upside.
The Deep Dive
The claim, stated plainly
Modern AI needs three scarce things: enormous amounts of compute, enormous amounts of data, and the operational skill to run both at scale. Cloud's basic model (rent instead of buy, elastic instead of fixed, shared instead of dedicated, managed instead of hand-built) happens to be a good fit for each one. Let me take them in turn.
Compute: expensive, scarce, and needed in bursts
The hardware that trains and serves large models is a poor thing to own. Accelerators are very expensive, they're in short supply, and they age fast. Worse, your need for them is lumpy: training a model might need thousands of accelerators for a few weeks, then nothing. Owning that capacity means paying for it while it sits idle.
Cloud flips this into the model from Week 1: capital expense becomes operating expense, and you pay for the hours you use. A point made in a well-known 2009 Berkeley paper on cloud computing captures why this matters so much for AI: using 1,000 servers for one hour costs about the same as using one server for 1,000 hours. That's called cost associativity, and it means that if you can rent enough machines, you can finish a huge job fast without paying a premium for speed. We'll put numbers on this in the lab.
It comes with an honest caveat: renting scarce hardware means competing for it. Today's AWS lineup for this work includes P-series GPU instances (P5 with H100 GPUs, and newer P6 instances with Blackwell GPUs) and AWS's own Trainium chips (Trn instances). The newest Trainium3 UltraServers became generally available in December 2025, and AWS says one can combine up to 144 chips into a single system. For GPU instances you can't count on simply launching them on demand: availability is constrained, and AWS offers EC2 Capacity Blocks for ML, which let you reserve accelerator capacity for a fixed window in advance. Their prices are set by supply and demand and updated periodically, and by reports they've gone up during 2026. That's what scarcity looks like in a price list. Discount plans like Savings Plans lower your rate but don't reserve capacity, which is a different thing.
Scale: when one machine isn't enough
A frontier model doesn't fit on one GPU, and the training run doesn't finish on one server. The model and data have to be split across many accelerators that work as one, which is called distributed training. The main ideas are splitting the data across machines (data parallelism), splitting the model's layers across machines (pipeline parallelism), and splitting individual operations across machines (tensor parallelism).
What this changes is the role of the network. When thousands of accelerators constantly exchange results, the interconnect becomes the bottleneck, so AWS builds clusters where instances are placed close together in UltraClusters with very high-bandwidth, low-latency networking (the docs describe it as petabit-scale and non-blocking), and UltraServers that tie many chips into one tightly connected system. This is Week 2's Nitro story continuing: offloading networking and virtualization onto dedicated hardware is part of what makes this possible. And at this scale, hardware fails constantly, so the software has to checkpoint progress and recover automatically instead of restarting a month-long run from zero.
Nobody can economically build and operate this for a single training run, which is the whole argument for renting it.
Custom silicon: owning the whole stack
A cloud provider running enormous AI workloads can justify designing its own chips. That's Trainium for training and Inferentia for inference, from the same Annapurna Labs team behind Nitro and Graviton. The reasoning is price-performance: when you control the chip, the server, the network, and the data center, you can optimize all of it together. AWS says Amazon Bedrock is already serving production workloads on Trainium3. The trade-off for customers is a different software stack than the NVIDIA ecosystem most people know, which is a real switching cost to weigh.
Data gravity: compute goes where the data already is
Training data and inference logs are big, and they already live in cloud storage and databases (Week 5). Moving petabytes is slow, and it can cost money to move data out. So compute tends to move to the data, not the other way around. Managed data services (S3 for storage, Glue and Athena for preparation and querying, and others) mean the unglamorous data-wrangling that consumes most of an ML project's time can also be done without running any servers. We'll do a small version of that in the lab, on inference logs.
Inference: sharing is the economics
Training is a burst; inference, serving the trained model to users, is the long-running cost. A serverless service like Bedrock (Week 11) packs many customers' bursty requests onto shared, expensive hardware, which is why it can charge per token with no idle cost. Running your own model on dedicated instances only wins when your usage is high and steady enough to keep the hardware busy. That's the same utilization logic as everything else in this article.
The honest counterpoints
A fair version of this story includes the downsides:
- Scarcity pricing is real. Renting something everyone wants means paying scarcity prices, and quotas and waits are normal.
- Costs can run away. A single mistaken GPU instance left running costs more per hour than most of the services in this entire series.
- Lock-in is real. Custom chips and managed services are efficient partly because they're integrated, and integrated means harder to leave.
- Steady heavy users have alternatives. If you run accelerators near-continuously for years, long-term commitments, other providers, specialist GPU clouds, or owning hardware can come out ahead. Cloud wins on flexibility; it's not automatically cheapest at constant high utilization.
The one-line summary
AI is a workload with enormous, lumpy, short-lived compute needs, huge data, and demanding operations, and cloud is a business model built to rent exactly that kind of capacity to many customers at once. Neither would look the way it does without the other.
Cost Reality Check for This Week
All three labs are cheap or free. The first two use read-only AWS calls and a local script. The third uses Athena, which bills per amount of data scanned (roughly $5 per terabyte at the time of writing, with a small minimum per query), and the dataset here is a few megabytes. Expect cents.
The warning is about what I didn't include: don't launch a GPU instance to see what happens. A
p5.48xlarge lists at roughly $55 an hour on-demand (about $6.88 per GPU per hour, per a third-party price summary, so check AWS's pricing page), and Capacity Blocks are paid up front. New accounts also usually can't launch these instances at all until they request a quota increase, which Part 1 will show you directly. This week is about understanding the economics, not spending them.Hands-On
Part 1 — What's on offer, and why you can't just click "launch"
First, what accelerated instances exist in your region. Types that aren't offered in your region won't appear in the output:
aws ec2 describe-instance-types \ --filters "Name=instance-type,Values=p5.48xlarge,p6-b200.48xlarge,trn2.48xlarge,inf2.xlarge,g6.xlarge" \ --query 'InstanceTypes[].[InstanceType,VCpuInfo.DefaultVCpus,MemoryInfo.SizeInMiB,GpuInfo.Gpus[0].Name,NeuronInfo.NeuronDevices[0].Name]' \ --output tableYou'll see GPU models for the P and G families and Neuron devices (AWS's own chips) for the Trn and Inf families. Compare the memory sizes to a normal general-purpose instance from Week 4.
Next, the part that surprises people: your account's quota for running these instances.
aws service-quotas list-service-quotas --service-code ec2 \ --query "Quotas[?contains(QuotaName, 'G and VT') || contains(QuotaName, 'Running On-Demand P')].[QuotaName,Value]" \ --output tableOn a new account, these values are commonly zero or very low, meaning a launch request would be rejected until you ask AWS to raise the limit. That's the practical face of scarcity: GPU access is something you request, not something you click.
Now see how reserved GPU capacity is offered, without buying anything. This is a read-only search for a Capacity Block:
START=$(python3 -c "from datetime import datetime,timedelta,timezone;print((datetime.now(timezone.utc)+timedelta(days=2)).strftime('%Y-%m-%dT%H:%M:%SZ'))")END=$(python3 -c "from datetime import datetime,timedelta,timezone;print((datetime.now(timezone.utc)+timedelta(days=30)).strftime('%Y-%m-%dT%H:%M:%SZ'))")
aws ec2 describe-capacity-block-offerings \ --instance-type p5.48xlarge --instance-count 1 \ --capacity-duration-hours 24 \ --start-date-range $START --end-date-range $ENDIf your region offers any, you'll get back specific start times and an up-front fee for a 24-hour reservation, like looking up flights. It may well return nothing in your region, which is itself informative. Don't run
purchase-capacity-block ; that's a separate command that spends real money, and I'd check the cancellation terms before ever using it.Finally, spot prices, which are free to look up, show the market-based side of the same story:
aws ec2 describe-spot-price-history \ --instance-types g6.xlarge --product-descriptions "Linux/UNIX" \ --max-items 5 --query 'SpotPriceHistory[].[AvailabilityZone,SpotPrice]' --output tablePart 2 — Napkin math: what does training actually cost?
A common rule of thumb says training a transformer takes about 6 × parameters × training tokens floating-point operations. Divide by the hardware's real (not peak) throughput and you get GPU-hours. This script does that arithmetic, and also shows cost associativity and the cost of owning versus renting:
cat > napkin.py <<'PY'import argparse
p = argparse.ArgumentParser()p.add_argument("--params", type=float, default=7e9, help="model parameters")p.add_argument("--tokens", type=float, default=2e12, help="training tokens")p.add_argument("--peak-tflops", type=float, default=312, help="accelerator peak TFLOPs (A100 BF16 = 312)")p.add_argument("--mfu", type=float, default=0.40, help="fraction of peak actually achieved")p.add_argument("--price-per-gpu-hour", type=float, default=None, help="rental price, USD")p.add_argument("--own-price", type=float, default=None, help="purchase price of one 8-GPU server, USD")a = p.parse_args()
flops = 6 * a.params * a.tokenseffective = a.peak_tflops * 1e12 * a.mfugpu_hours = flops / effective / 3600
print(f"Total compute: {flops:.2e} FLOPs")print(f"GPU-hours: {gpu_hours:,.0f}")
print("\nSame job, different amounts of hardware (assumes perfect scaling):")for n in (8, 64, 512, 4096): print(f" {n:>5} GPUs -> {gpu_hours / n / 24:8.1f} days")
if a.price_per_gpu_hour is not None: print(f"\nRental cost at ${a.price_per_gpu_hour}/GPU-hour: ${gpu_hours * a.price_per_gpu_hour:,.0f}") print(" (same cost whether it takes 1 GPU a very long time or thousands for a short time)")
if a.own_price is not None: life_hours = 4 * 8760 # assume a 4-year useful life print("\nEffective cost per GPU-hour if you OWN a server (hardware only, 4-year life):") for util in (0.10, 0.30, 0.60, 0.90): per_gpu_hour = a.own_price / (8 * life_hours * util) print(f" {int(util * 100):>3}% utilized -> ${per_gpu_hour:,.2f}")PY
python3 napkin.pyThe defaults reproduce Meta's published Llama 2 7B setup: 2 trillion tokens on A100 GPUs. You should get roughly 187,000 GPU-hours, which lands close to the roughly 184,000 reported in that model's paper. That agreement is the point: if a back-of-envelope formula comes within a few percent of a real training run, you can trust it for rough planning. Now try two variations:
# The same job on H100s (989 TFLOPs BF16 peak), at ~$6.88/GPU-hour# (p5.48xlarge on-demand is about $55 an hour for 8 GPUs; check the current AWS price)python3 napkin.py --peak-tflops 989 --price-per-gpu-hour 6.88
# A fine-tuning-sized job: 1 billion tokens on the same 7B modelpython3 napkin.py --tokens 1e9The first gives roughly 59,000 GPU-hours and a cost around $400,000, which is why pretraining a model like this is a company-scale decision, not a personal one. The second comes out around 90-odd GPU-hours, which is why fine-tuning is within reach of students and small teams. Read the "different amounts of hardware" table on either run: the cost doesn't change, only the calendar time does. (Real jobs scale less than perfectly because of communication overhead, so treat this as a best case.)
If you'd like to see the owning-vs-renting trade-off, pass
--own-price with a quote you've actually seen for a server. The utilization table shows the whole argument in four lines: owned hardware is only cheap per hour if you keep it busy.Part 3 — The data side: querying inference logs with Athena
Training gets the attention, but a large share of ML work is wrangling data. Here's a small, serverless version of that: generate fake inference logs, query them with SQL where they sit in S3, then see why columnar formats matter.
cat > gen_logs.py <<'PY'import csv, math, random, datetime
random.seed(42)models = {"nova-lite": (250, 0.5), "nova-pro": (600, 0.5), "llama-70b": (900, 0.6)}start = datetime.datetime(2026, 10, 1)
with open("inference_logs.csv", "w", newline="") as f: w = csv.writer(f, lineterminator="\n") w.writerow(["ts", "model", "latency_ms", "tokens_in", "tokens_out", "status"]) for i in range(300000): m = random.choice(list(models)) median, sigma = models[m] latency = int(random.lognormvariate(math.log(median), sigma)) status = random.choices([200, 429, 500], [0.97, 0.02, 0.01])[0] ts = (start + datetime.timedelta(seconds=i * 2)).strftime("%Y-%m-%d %H:%M:%S") w.writerow([ts, m, latency, random.randint(50, 1500), random.randint(20, 800), status])PY
python3 gen_logs.py
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)BUCKET=zth-ai-data-$ACCOUNT_IDaws s3 mb s3://$BUCKETaws s3 cp inference_logs.csv s3://$BUCKET/logs/inference_logs.csvAthena queries run asynchronously, so a small helper makes them easier to use from the CLI. It runs a query, waits for it to finish, then prints how many bytes it scanned (the thing you're billed for) and the results:
run_query () { QID=$(aws athena start-query-execution \ --query-string "$1" \ --result-configuration OutputLocation=s3://$BUCKET/athena-results/ \ --query QueryExecutionId --output text) while true; do STATE=$(aws athena get-query-execution --query-execution-id $QID \ --query 'QueryExecution.Status.State' --output text) [[ "$STATE" == "SUCCEEDED" || "$STATE" == "FAILED" || "$STATE" == "CANCELLED" ]] && break sleep 2 done SCANNED=$(aws athena get-query-execution --query-execution-id $QID \ --query 'QueryExecution.Statistics.DataScannedInBytes' --output text) echo "$STATE | scanned bytes: $SCANNED" if [[ "$STATE" == "SUCCEEDED" ]]; then aws athena get-query-results --query-execution-id $QID \ --query 'ResultSet.Rows[*].Data[*].VarCharValue' --output text else aws athena get-query-execution --query-execution-id $QID \ --query 'QueryExecution.Status.StateChangeReason' --output text fi}Create a database and point a table at the CSV file. Nothing is loaded or copied; Athena reads the file in place:
run_query "CREATE DATABASE IF NOT EXISTS zth_ai"
run_query "CREATE EXTERNAL TABLE IF NOT EXISTS zth_ai.inference_logs ( ts string, model string, latency_ms int, tokens_in int, tokens_out int, status int) ROW FORMAT DELIMITED FIELDS TERMINATED BY ','STORED AS TEXTFILELOCATION 's3://$BUCKET/logs/'TBLPROPERTIES ('skip.header.line.count'='1')"Now ask real questions about your fake AI service. Latency and error rate per model:
run_query "SELECT model, count(*) AS requests, round(avg(latency_ms), 1) AS avg_ms, approx_percentile(latency_ms, 0.95) AS p95_ms, round(100.0 * sum(CASE WHEN status <> 200 THEN 1 ELSE 0 END) / count(*), 2) AS error_pctFROM zth_ai.inference_logs GROUP BY model ORDER BY model"And an estimated token cost per model, tying back to Week 11's per-token billing. The prices here are made up for illustration, so don't treat them as real rates:
run_query "SELECT model, round(sum(tokens_in) / 1e6 * (CASE model WHEN 'nova-lite' THEN 0.06 WHEN 'nova-pro' THEN 0.80 ELSE 0.72 END) + sum(tokens_out) / 1e6 * (CASE model WHEN 'nova-lite' THEN 0.24 WHEN 'nova-pro' THEN 3.20 ELSE 0.72 END), 2) AS est_cost_usdFROM zth_ai.inference_logs GROUP BY model ORDER BY model"That's the beginning of an AI cost dashboard, built with nothing but SQL over a file in S3.
Now the lesson in the bytes-scanned numbers. Convert the same data to Parquet, a columnar format, and run the same query on both:
run_query "CREATE TABLE zth_ai.inference_logs_parquetWITH (format = 'PARQUET', external_location = 's3://$BUCKET/parquet/')AS SELECT * FROM zth_ai.inference_logs"
echo "--- CSV ---"run_query "SELECT model, avg(latency_ms) FROM zth_ai.inference_logs GROUP BY model"
echo "--- Parquet ---"run_query "SELECT model, avg(latency_ms) FROM zth_ai.inference_logs_parquet GROUP BY model"Compare the two "scanned bytes" lines. A row-oriented CSV forces Athena to read every column of every row even though this query only needs two of them. Parquet stores each column separately and compresses it, so the same query reads only what it needs, typically a small fraction of the bytes. Since you pay per byte scanned, the file format is a direct cost lever. This is one of the highest-value habits in data engineering, and it's a big part of why ML data pipelines at scale don't run on CSV.
Cleanup
run_query "DROP TABLE IF EXISTS zth_ai.inference_logs_parquet"run_query "DROP TABLE IF EXISTS zth_ai.inference_logs"run_query "DROP DATABASE IF EXISTS zth_ai"
aws s3 rm s3://$BUCKET --recursiveaws s3 rb s3://$BUCKETrm -f inference_logs.csv gen_logs.py napkin.pyDropping an external table doesn't delete the underlying files, which is why the bucket is emptied separately. Nothing in this week leaves a running resource behind.
My Take
This week connected the dots for me: cloud and AI aren't just complementary technologies; their economics are deeply connected. AI needs massive, flexible compute and scalable data infrastructure, while cloud makes both accessible without huge upfront investments. But the biggest takeaway is that scalability comes with responsibility i.e. understanding costs, utilization, and lock-in matters just as much as understanding the technology.
Next week — Part 14: Cost optimization and the Well-Architected Framework — the six pillars AWS grades architectures against, and the habits that keep a learning account from ever producing a surprise bill.
Series: AWS: Zero to Hero (14 articles)
- …
- 13AWS: Zero to Hero — Week 13: Why Cloud and AI Are Really the Same Story This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article