Expert⏱ 30 min⚡ 140 XP🧩 5-question quiz

The Economics of AI

Estimate training and inference cost from first principles: 6ND and 2N FLOPs, memory-bandwidth-bound decoding, GPU-hour math, token pricing, and total cost of ownership.


AI looks like magic until the invoice arrives. A prototype that costs a few dollars a day can cost tens of thousands a month at scale, and a research idea that looks cheap on paper can burn a quarter's budget on failed runs. In Module 07 (Transformers & LLMs) you learned how these models compute, and in Module 11 (MLOps & Deployment) you learned to put them into production. This module asks what that computation costs and how to make it cheaper, so that more people and organizations can afford to use AI at all.

The good news is that AI cost is not mysterious. It follows from a handful of quantities you can estimate on a napkin: parameters, tokens, FLOPs, memory bandwidth, utilization, and price per hour. Every technique in the rest of the module, from quantization to model routing, is a way of changing one of those numbers.

Note: All prices and hardware figures in this lesson are illustrative, chosen to make the arithmetic easy to follow. Cloud and API prices change often and vary by provider, region, and contract. Check current price sheets and vendor spec sheets before making real decisions.

Two very different bills

Training is a large, mostly one-time capital expense. You rent or buy a lot of compute for days to months, and at the end you have a set of weights.

Inference is an ongoing operating expense. Every request costs a little, forever. For a popular product, cumulative inference spending can exceed the training bill within months, which is why most cost work happens on the inference side.

Keep this asymmetry in mind: a technique that makes training 2× cheaper pays off once; a technique that makes inference 2× cheaper pays off on every request for the life of the product.

The diagram below maps the main cost drivers to the lessons in this module where you will learn to reduce them.

Rendering diagram…

Parameters drive both compute and bytes moved; tokens multiply everything; utilization decides how many paid GPU-hours each useful FLOP actually costs.

Training compute: why 6·N·D

For a dense transformer with NN parameters trained on DD tokens, the standard approximation (Kaplan et al., 2020) is:

Ctrain≈6 N D FLOPsC_{\text{train}} \approx 6\,N\,D \ \text{FLOPs}

Here is where the 6 comes from. Almost all compute is in matrix multiplications. Multiplying an input vector by a weight matrix costs one multiply and one add per weight, so the forward pass costs about 2 FLOPs per parameter per token. The backward pass must compute two things for each layer: gradients with respect to the layer's inputs (to keep backpropagating) and gradients with respect to its weights (to update them). Each is another matrix multiplication of the same size, so the backward pass costs about 4 FLOPs per parameter per token. Total: 2 + 4 = 6. The approximation ignores the attention score computation, which grows with context length; it is a modest correction at typical context lengths and a bigger one for very long contexts.

Two refinements matter in practice. First, for a Mixture-of-Experts model, NN means the parameters active per token, not the total: a model with many experts but few active per token trains with far fewer FLOPs than its headline size suggests, while still needing memory for every expert. Second, if you use gradient checkpointing (lesson 5), part of the forward pass is recomputed, so the hardware does roughly 8ND8ND FLOPs even though the useful work is still 6ND6ND. MFU, defined next, counts only the useful 6ND6ND.

To turn FLOPs into time you need the accelerator's peak throughput and your model FLOPs utilization (MFU), the fraction of peak you actually achieve:

GPU-seconds=Ctrainpeak FLOP/s×MFU\text{GPU-seconds} = \frac{C_{\text{train}}}{\text{peak FLOP/s} \times \text{MFU}}

Large, well-tuned training jobs often report MFU somewhere around 30–50%; communication between GPUs, data loading, and imperfect kernels eat the rest. Small or poorly configured jobs can be far lower.

Worked example

Train an illustrative 7B model on 2 trillion tokens:

Ctrain=6×(7×109)×(2×1012)=8.4×1022 FLOPsC_{\text{train}} = 6 \times (7\times10^{9}) \times (2\times10^{12}) = 8.4\times10^{22} \ \text{FLOPs} 8.4×1022(1×1015)×0.4=2.1×108 GPU-s≈58,300 GPU-hours\frac{8.4\times10^{22}}{(1\times10^{15}) \times 0.4} = 2.1\times10^{8} \ \text{GPU-s} \approx 58{,}300 \ \text{GPU-hours}
  • The accelerator is an illustrative 1×10¹⁵ FLOP/s (dense BF16) part running at 40% MFU.
  • At an illustrative $2.50 per GPU-hour: about $146,000 for one successful run.

That figure covers one run. Real projects add hyperparameter sweeps, crashed runs, ablations, and evaluation, which commonly multiply compute several times.

Compute-optimal versus inference-optimal

Hoffmann et al. (2022, the "Chinchilla" paper) found that for a fixed training budget, loss is minimized with roughly 20 tokens per parameter; many earlier models were too big and undertrained. But Chinchilla optimizes training cost only. If a model will serve trillions of tokens, it is cheaper overall to train a smaller model on many more tokens than Chinchilla suggests: you pay more once, and save on every request. This is why many widely used open-weight models are trained far beyond 20 tokens per parameter, a direct trade of capital expense for operating expense.

Inference compute and the memory wall

Generating one token with a dense model costs about 2N2N FLOPs (a forward pass only). A 7B model needs about 14 GFLOPs per token, which sounds like a lot until you compare it with an accelerator that does hundreds of TFLOP/s. More precisely, Kaplan et al. give the forward cost per token as

Cforward≈2N+2 nlayer nctx dmodelC_{\text{forward}} \approx 2N + 2\, n_{\text{layer}}\, n_{\text{ctx}}\, d_{\text{model}}

where the second term is attention over the nctxn_{\text{ctx}} tokens already in context. For an 8B-class model (32 layers, dmodel=4096d_{\text{model}} = 4096) at 32k tokens of context, that term is about 8.6 GFLOPs per token, more than half of the 2N2N term, so long contexts make every generated token noticeably more expensive.

So why is decoding not instant? Because to produce each token the GPU must read every weight from high-bandwidth memory (HBM). A 7B model in 16-bit precision is 14 GB. With an illustrative bandwidth of 3 TB/s:

  • Reading the weights once: 14 GB / 3,000 GB/s ≈ 4.7 ms
  • Upper bound at batch size 1: about 214 tokens/s (and less in practice, since the KV cache must be read too)
  • Compute actually used: 14 GFLOPs / 4.7 ms ≈ 3 TFLOP/s, about 0.3% of the illustrative 1,000 TFLOP/s peak

Arithmetic intensity and the roofline

The clean way to reason about this is arithmetic intensity II: FLOPs performed per byte moved. The roofline model (Williams et al., 2009) says the throughput you can attain is capped by whichever runs out first, compute or memory:

attainable FLOP/s=min⁡(peak FLOP/s,  I×bandwidth)\text{attainable FLOP/s} = \min\big(\text{peak FLOP/s},\; I \times \text{bandwidth}\big)

The two limits cross at the ridge point:

Iridge=peak FLOP/smemory bandwidthI_{\text{ridge}} = \frac{\text{peak FLOP/s}}{\text{memory bandwidth}}

With 1×10¹⁵ FLOP/s and 3×10¹² B/s the ridge is about 330 FLOPs per byte. Decoding with 16-bit weights does 2 FLOPs per parameter per sequence and reads 2 bytes per parameter, shared by every sequence in the batch. So at batch size BB, intensity is roughly I≈BI \approx B FLOPs per byte. Below a batch of a few hundred, the chip is starved for data. (This counts weight traffic only; each sequence's KV cache is read separately and is not shared, so at long contexts real intensity is lower still.)

Three big consequences follow:

  1. Batching is nearly free throughput. If 64 requests share one read of the weights, you get roughly 64 tokens for the price of one read, until you hit the compute roof or run out of memory for the KV cache (lesson 3).
  2. Fewer bytes means faster decoding. Quantizing weights to 4 bits cuts bytes read per token about 4×, so quantization speeds up inference, not just storage (lesson 2).
  3. Prefill is different. Processing a prompt handles all its tokens in parallel, so one read of the weights serves hundreds or thousands of tokens. Prefill is usually compute-bound and efficient.

Why output tokens cost more than input tokens

Point 3 explains a pattern you will see on nearly every API price sheet: output tokens cost several times more than input tokens. Three reasons stack up:

  • Utilization. Input tokens are processed in a highly parallel, compute-bound prefill. Each output token needs its own sequential decoding step that is bandwidth-bound unless batched heavily.
  • Memory-time. While a sequence is generating, its KV cache occupies scarce GPU memory. Long outputs hold that memory for many steps, limiting how many other users fit.
  • Latency. Output tokens come out one at a time, so they set how long a request occupies the system.

This has a practical corollary: a verbose answer or a long hidden reasoning trace is the most expensive part of most requests. Reasoning models that "think" before answering bill those thinking tokens as output. Controlling output length (lesson 4) is often the cheapest win available.

Tokens are the unit of every bill, so it pays to build an intuition for how text turns into them. Try a few sentences, some code, and a non-English sentence in the widget below.

As a rough guide, English prose averages around three-quarters of a word per token for common tokenizers, but code, numbers, and many non-English languages use noticeably more tokens for the same content, which you will revisit in the FinOps lesson.

Token economics when you self-host

If you run your own GPUs, you can derive your own price per token:

cost per 1M tokens=GPU price per hourtokens/s×3600×u / 106\text{cost per 1M tokens} = \frac{\text{GPU price per hour}}{\text{tokens/s} \times 3600 \times u \,/\, 10^{6}}

where uu is the fraction of paid hours the GPU spends doing useful work. The decisive variable is utilization. A GPU that serves 2,000 tokens/s at peak but sits idle 70% of the day costs more than three times as much per useful token. API providers achieve high utilization by pooling many customers' traffic; that pooling, plus engineering you do not have to do, is much of what you pay for.

The calculator below models an API-based product. Change traffic, tokens per request, prices, cache hit rate, and the share of traffic routed to a cheaper model, and notice which inputs move the monthly bill most.

You should find that output tokens and traffic dominate, and that caching and routing (lesson 4) can matter as much as the headline price.

A napkin calculator in code

The script below turns the rules of thumb into numbers. Change the inputs and watch how sensitive the results are.

# Illustrative numbers only: check current hardware specs and prices.
def training_cost(params, tokens, peak_flops=1e15, mfu=0.4, gpu_hour_usd=2.50):
    flops = 6 * params * tokens
    gpu_hours = flops / (peak_flops * mfu) / 3600
    return flops, gpu_hours, gpu_hours * gpu_hour_usd

def decode_ceiling(params, bytes_per_param=2, bandwidth=3e12):
    weight_bytes = params * bytes_per_param
    return weight_bytes / 1e9, bandwidth / weight_bytes  # GB, tokens/s at batch 1

def ridge_batch(peak_flops=1e15, bandwidth=3e12, bytes_per_param=2):
    # Intensity at batch B is about 2*B / bytes_per_param FLOPs per byte.
    return (peak_flops / bandwidth) * bytes_per_param / 2

def cost_per_million(gpu_hour_usd, tokens_per_sec, utilization=1.0):
    tokens_per_hour = tokens_per_sec * 3600 * utilization
    return gpu_hour_usd / (tokens_per_hour / 1e6)

flops, hours, usd = training_cost(params=7e9, tokens=2e12)
print(f"Train 7B on 2T tokens: {flops:.1e} FLOPs, {hours:,.0f} GPU-hours, ~${usd:,.0f}")

for bpp, label in [(2, "BF16"), (1, "INT8"), (0.5, "INT4")]:
    gb, tps = decode_ceiling(7e9, bytes_per_param=bpp)
    print(f"{label}: weights {gb:.1f} GB, batch-1 ceiling ~{tps:.0f} tok/s, "
          f"compute-bound above batch ~{ridge_batch(bytes_per_param=bpp):.0f}")

for util in (1.0, 0.5, 0.2):
    c = cost_per_million(2.50, tokens_per_sec=2000, utilization=util)
    print(f"Utilization {util:.0%}: ${c:.2f} per 1M tokens")

With these inputs, training lands near 58,000 GPU-hours; the batch-1 decoding ceiling rises from about 214 to 857 tokens/s as weights shrink from 16 to 4 bits; and the self-hosted price per million tokens climbs from about $0.35 to $1.74 as utilization falls from 100% to 20%. Notice that quantization lowers the batch size at which you become compute-bound, because each byte now carries more parameters.

Total cost of ownership

Compute is only the visible part of the bill. A realistic total cost of ownership (TCO) includes:

CategoryExamples
ComputeGPU-hours, API tokens, CPU for pre- and post-processing
Idle capacityReserved GPUs at night, headroom for traffic peaks
Storage and networkingCheckpoints, datasets, vector databases, egress fees
ExperimentationSweeps, failed runs, evaluation suites
PeopleEngineering, data labeling, on-call, security review
Risk and complianceMonitoring, audits, incident response

Buying hardware swaps hourly rent for an upfront cost plus power, cooling, space, and staff; it tends to pay off only with sustained high utilization. APIs and on-demand rental are usually cheaper for spiky or uncertain workloads. The honest answer to "build or buy?" is "it depends on utilization," and now you can calculate it.

Common misconceptions

  • "A bigger GPU is always faster." Not at batch size 1 if both are bandwidth-bound; compare bandwidth and memory, not just peak FLOP/s.
  • "Training is the expensive part." For a successful product, inference usually overtakes training.
  • "The API price is the cost." Retries, long system prompts, verbose outputs, and failed requests can multiply the effective price per useful answer.

Hands-on exercise

  1. Pick an open-weight model whose parameter count and training-token count are stated in its model card. Use training_cost to estimate its training compute and GPU-hours at 40% MFU on an accelerator whose peak dense BF16 throughput you look up.
  2. Compute its weight size in BF16 and INT4, and the batch-1 decoding ceiling on a GPU whose memory bandwidth you look up on the vendor's spec sheet.
  3. Look up a current API price per million output tokens for a model of similar size. Find the utilization at which your self-hosted cost per million tokens equals the API price (solve cost_per_million(...) == api_price for utilization).
  4. Write two sentences on which costs your estimate left out.

Expected outcome: a short table with training GPU-hours, weight sizes, decoding ceilings, and a break-even utilization, plus a list of omitted costs. Most learners find the break-even utilization surprisingly high.

Key takeaways

  • Training ≈ 6·N·D FLOPs (2 forward + 4 backward per parameter per token); inference ≈ 2·N FLOPs per token.
  • Divide FLOPs by peak FLOP/s × MFU to get GPU-time, then multiply by price, and by the number of runs you really need.
  • Decoding is memory-bandwidth-bound at small batches: arithmetic intensity ≈ batch size, so batching and smaller weights increase throughput.
  • Output tokens cost more than input tokens because decoding is sequential, bandwidth-bound, and holds KV-cache memory.
  • Self-hosted cost per token depends on utilization at least as much as on the hourly price.
  • TCO includes idle capacity, experiments, storage, and people; treat every price as illustrative and re-check it.

Next, in lesson 2, you will attack the "bytes per parameter" term directly with model compression: quantization, pruning, and distillation.

Further reading

  • Kaplan et al. (2020), "Scaling Laws for Neural Language Models": https://arxiv.org/abs/2001.08361
  • Hoffmann et al. (2022), "Training Compute-Optimal Large Language Models" (Chinchilla): https://arxiv.org/abs/2203.15556
  • Pope et al. (2022), "Efficiently Scaling Transformer Inference": https://arxiv.org/abs/2211.05102
  • Austin et al. (Google DeepMind, 2025), "How to Scale Your Model", a free online book on rooflines, sharding, and inference math.
  • Williams, Waterman & Patterson (2009), "Roofline: An Insightful Visual Performance Model for Multicore Architectures", Communications of the ACM.

Save your progress and earn XP

Create a free account to take the quiz, track progress and unlock badges.