Skip to main content

08 - Cost optimization techniques: 30-50% saving per layer, model selection, inference

How to cut AI spend layer by layer: batch, model choice with a non-inferiority test, request batching and quantisation, and why savings do not add up.

What do you think about this article?

08 - Cost optimization techniques: 30-50% saving per layer, model selection, inference
AI Cost OptimizationPhoto:Tara WinsteadPexels

At a Glance

How to cut AI spend layer by layer: batch, model choice with a non-inferiority test, request batching and quantisation, and why savings do not add up.

Cutting AI spend layer by layer: batch, model choice, serving and memory, and why the savings do not add up

You have the cost log and you know which feature weighs most: now you have to decide where to intervene. The answer of this article is that the levers sit on different layers (application, API, serving, hardware), that each one acts only on a share of the spend, and that the per-layer saving percentages in circulation do not add up. Here you find the levers not covered in the piece on caching, compression and routing: batch processing, model choice with a quality test, grouping requests on your own server, and the memory of quantised models. Five executed listings, with invented and declared numbers.

The title of this article cites a saving of 30-50% per layer. I did not find a primary source that measures it, and I do not use it: every percentage you read here comes from an executed example, with the parameters visible in the code, or is attributed to an official page. What matters to you is the percentage on your own workload, and the method to obtain it is in the listings.

Four layers, four different questions

A token goes through four points where you can decide how much it costs, and each one corresponds to a different question.

  • Application: how many tokens you send and ask for, and to which model. Levers: length of prompts and responses, model choice, context reuse.
  • Provider API: how you pay for those tokens. Levers: batch processing, prompt cache, price tier.
  • Serving, if you have your own server: how many requests a machine processes. Levers: grouping of requests, management of the token cache.
  • Hardware: on which memory and with which precision the weights sit. Levers: quantisation, choice of accelerator.

Not all readers have all the layers: whoever uses only an API works on the first two, whoever has their own server works on all of them. The FinOps Foundation, in its AI document, describes the same map with one more idea: those who buy APIs act mostly on the upper layers, those who run the infrastructure act on the lower ones too. Before choosing a lever, then, ask yourself which layer it belongs to and what share of spend it touches, because the answer to the second question limits the possible saving.

Savings do not add up: each lever acts on a share

A lever that "saves 50%" does so on the part of the spend it touches. If batch applies to 40% of the spend and halves that part, the saving on the total is 20%. Later levers act on what remains, so the savings compose by multiplying the factors "one minus saving on the share", not by adding the percentages. The listing applies three invented levers in sequence, in the two possible orders.

"""Why 'saving 30-50% per layer' does not add up. Three INVENTED levers: each acts on a SHARE of the spend
and saves a percentage of that share. Levers are applied in sequence: the second acts on what is left."""
SPESA = 1000.0
# (name, share of the current spend it acts on, saving on that share)
LEVE = [
    ("batch on non-urgent jobs", 0.40, 0.50),
    ("small model where it is enough", 0.50, 0.60),
    ("cap on response length", 0.30, 0.25),
]

def applica(spesa, leve):
    for nome, quota, risparmio in leve:
        risparmiato = spesa * quota * risparmio
        spesa -= risparmiato
        print(f"  {nome:34s} -{risparmiato:7.1f} EUR  ->  {spesa:7.1f} EUR")
    return spesa

for titolo, ordine in (("order A", LEVE), ("order B", LEVE[::-1])):
    print(titolo)
    fine = applica(SPESA, ordine)
    print(f"  total saving {1 - fine / SPESA:.1%}\n")

somma_ingenua = sum(q * r for _, q, r in LEVE)
print(f"naive sum of shares x savings: {somma_ingenua:.1%}")

# Output:
# order A
#   batch on non-urgent jobs           -  200.0 EUR  ->    800.0 EUR
#   small model where it is enough     -  240.0 EUR  ->    560.0 EUR
#   cap on response length             -   42.0 EUR  ->    518.0 EUR
#   total saving 48.2%
#
# order B
#   cap on response length             -   75.0 EUR  ->    925.0 EUR
#   small model where it is enough     -  277.5 EUR  ->    647.5 EUR
#   batch on non-urgent jobs           -  129.5 EUR  ->    518.0 EUR
#   total saving 48.2%
#
# naive sum of shares x savings: 57.5%

The total saving is 48.2% in both orders, while the naive sum of the percentages per share would give 57.5%, and adding the three "lever" percentages (50, 60 and 25) would give 135%, which is impossible. What changes is how much is attributed to each lever: batch is worth 200 euros if it comes first and 129.50 if it comes last, because it acts on an already reduced spend. So the comparison between levers must be made on the same order, and the attribution of a saving to a team or a project is a convention, not a fact. The model has a declared limit: it assumes the shares are independent. If the jobs sent to batch are the same ones that move to the small model, the shares overlap and the combined saving is different from the one computed.

Batch: the discount depends on the deadline, not on the type of job

Anthropic and OpenAI offer a batch interface with a 50% discount compared with synchronous calls, in exchange for deferred delivery: in Anthropic's documentation most batches finish in less than an hour, but can take up to 24 hours and a batch expires if it is not completed within 24 hours; in OpenAI's the completion window is 24 hours. The discount can be combined with prompt caching, but the documentation warns that with concurrent, asynchronous requests cache hits are "best effort", with typical rates stated between 30% and 98% depending on traffic.

The eligibility criterion is the job's deadline. The listing takes forty invented jobs, each with a deadline in hours and a synchronous cost, and classifies them: a job goes to batch only if its deadline exceeds the 24-hour window plus a margin, which serves to rerun it synchronously if the batch does not finish in time. The margin is a parameter of the example and the listing varies it.

"""Which jobs can move from the synchronous API to the batch one? It depends on the DEADLINE, not on the type of job.
Forty INVENTED jobs (name, deadline in hours, synchronous cost in EUR). The 50% discount and the 24-hour window
are those stated in the Anthropic and OpenAI documentation; the safety margin is a parameter of the example."""
SCONTO_BATCH = 0.50
FINESTRA_ORE = 24

LAVORI = (
    [("chat", 0, 18.0)] * 10                     # answers to a user: deadline of seconds
    + [("morning-summary", 6, 9.0)] * 8          # ready by 8 am: 6-hour deadline
    + [("indexing", 30, 6.0)] * 10               # by tomorrow: 30 hours
    + [("nightly-evaluation", 48, 12.0)] * 6     # within two days
    + [("backfill", 168, 25.0)] * 6              # within a week
)

def idoneo(scadenza_ore, margine_ore):
    """A job can go to batch if even in the worst case (whole window) the margin is left
    to rerun it synchronously before the deadline."""
    return scadenza_ore >= FINESTRA_ORE + margine_ore

totale = sum(c for _, _, c in LAVORI)
print(f"synchronous cost of the {len(LAVORI)} jobs: {totale:.1f} EUR")
for margine in (0, 6, 12, 30):
    e = [(n, c) for n, s, c in LAVORI if idoneo(s, margine)]
    risparmio = sum(c for _, c in e) * SCONTO_BATCH
    print(f"margin {margine:2d} h: eligible jobs {len(e):2d}, share of spend {sum(c for _, c in e) / totale:6.1%}, "
          f"saving {risparmio:6.1f} EUR = {risparmio / totale:5.1%} of the total")

# Output:
# synchronous cost of the 40 jobs: 534.0 EUR
# margin  0 h: eligible jobs 22, share of spend  52.8%, saving  141.0 EUR = 26.4% of the total
# margin  6 h: eligible jobs 22, share of spend  52.8%, saving  141.0 EUR = 26.4% of the total
# margin 12 h: eligible jobs 12, share of spend  41.6%, saving  111.0 EUR = 20.8% of the total
# margin 30 h: eligible jobs  6, share of spend  28.1%, saving   75.0 EUR = 14.0% of the total

With a 6-hour margin, 22 jobs are eligible, 52.8% of the spend, and the saving on the total is 26.4%, that is half of the eligible share. With a 12-hour margin the jobs with a 30-hour deadline leave the group and the saving falls to 20.8%, and with 30 hours to 14.0%. The number that matters is not the discount, which is fixed, but the share of spend with a wide deadline: two teams with the same volume and different deadlines save very differently. The case where batch does not pay is the one in which no job has a deadline close to or beyond 24 hours, and the one in which the synchronous rerun of expired jobs costs more than the discount: in the documentation I did not find how expired jobs are billed, so the estimate must be checked on your account before you rely on the saving.

Choosing the model with a test, not with a feeling

The FinOps document on AI recommends choosing, for each use case, the least expensive model that meets the required accuracy, latency and reliability, and re-checking the choice when new models come out. "Meets" has to be turned into a rule. A simple rule is the non-inferiority test: the small model is acceptable if, on a set of examples with a known answer, the quality difference from the large one does not fall below a tolerance you fixed beforehand, and this with a confidence margin and not only on the observed mean. The paired bootstrap method obtains it without assumptions on the distribution: you resample the list of differences example by example many times and look at the lower end of the 95% interval.

In the listing the two models are fake: they return 0 or 1 for each example, with a dependence on difficulty and a shared "chance", so that they often err on the same examples, as happens in reality. The true difference is 3 points in favour of the large model, the tolerance is 5, and the code checks it with 50, 200 and 1,000 examples.

"""Choosing the cheapest model that does not worsen quality beyond a tolerance: non-inferiority test
with a paired bootstrap. The two models are FAKE: 0/1 scores on N examples generated with a fixed seed
(the small one errs more and the two often err on the same examples). No model calls."""
import random

TOLLERANZA = -0.05          # the small model may be worth at most 5 points less than the large one
def esempi(n, seme):
    rng = random.Random(seme)
    out = []
    for _ in range(n):
        difficolta = rng.random()
        u = rng.random()                                   # the same 'chance' for both: the errors are correlated
        grande = u < 0.97 - 0.30 * difficolta
        piccolo = u < 0.94 - 0.30 * difficolta               # the small one is worth 3 points less on average: -0.03
        out.append((grande, piccolo))
    return out

def limite_inferiore(dati, ripetizioni=2000, seme=99):
    """Lower end of the 95% interval (2.5th percentile) of the mean difference small - large."""
    rng = random.Random(seme)
    diff = [int(p) - int(g) for g, p in dati]
    medie = sorted(sum(rng.choices(diff, k=len(diff))) / len(diff) for _ in range(ripetizioni))
    return sum(diff) / len(diff), medie[int(0.025 * ripetizioni)]

for n in (50, 200, 1000):
    d = esempi(n, seme=7)
    media, lim = limite_inferiore(d)
    verdetto = "acceptable" if lim >= TOLLERANZA else "NOT shown"
    print(f"N={n:5d}  observed difference {media:+.3f}  95% lower bound {lim:+.3f}  -> {verdetto}")

# Output:
# N=   50  observed difference -0.020  95% lower bound -0.060  -> NOT shown
# N=  200  observed difference -0.045  95% lower bound -0.075  -> NOT shown
# N= 1000  observed difference -0.029  95% lower bound -0.040  -> acceptable

With 50 examples the lower bound is -0.060, below the tolerance of -0.05, and nothing can be concluded; with 200 examples the observed mean is -0.045, apparently within the tolerance, but the bound is -0.075 and the verdict stays "not shown"; only with 1,000 examples does the bound fall to -0.040 and the small model turns out to be acceptable. That is why a comparison on twenty hand-picked questions is not enough: the uncertainty of a mean over few examples is wider than the tolerance you want to verify. The listing does not tell you how much you save by changing model, which depends on the price list of the moment, and it does not tell you whether your quality metric captures what matters to users: it is a statistical check on a score you must have chosen well.

Your own serving: grouping requests raises capacity, and lengthens the wait

If you run the models on a machine of your own, one generation step for a single sequence leaves much of the machine idle, and serving several sequences together costs little more than one. Serving systems exploit this with request batching. The vLLM paper, devoted to managing the token cache, describes the problem: serving at high throughput requires batching enough requests at a time, but the cache memory of each one is large and variable, and if it is badly managed it is wasted by fragmentation and duplication, limiting the batch size. The authors state an improvement of 2-4 times in throughput, at the same latency, over the baseline systems they chose.

The listing simulates a server with an invented timing model: a batch of n requests lasts L * (A + B * n) seconds, with a fixed cost per step A and a small cost B for each added sequence. Given a load of 2 requests per second, for each maximum batch size it computes how many servers are needed (with a maximum utilisation of 70%), the monthly cost at 400 euros per server (invented) and the mean and 95th-percentile latency simulated over an hour with a fixed seed. The simula function starts the batch when it is full or when the maximum wait of one second has expired.

"""Grouping requests (dynamic batching) raises a server's capacity, but you pay for it in latency.
Event simulation of ONE server with an INVENTED timing model: a batch of n requests lasts
L * (A + B * n) seconds, with L generated tokens, A = fixed cost of a step, B = cost per extra sequence.
No real model: it is only the mechanism. Fixed seed."""
import heapq, math, random
from statistics import mean

L, A, B = 200, 0.05, 0.004          # tokens per response, s per step, s per added sequence
ATTESA_MAX = 1.0                    # s: the server waits at most this long to fill the batch
LAMBDA = 2.0                        # requests/s to serve in total
COSTO_SERVER = 400.0                # EUR/month per server (invented)
UTILIZZO_MAX = 0.7

def durata(n):
    return L * (A + B * n)

def simula(rate, n_max, durata_s=3600, seme=3):
    rng = random.Random(seme)
    t, arrivi = 0.0, []
    while t < durata_s:
        t += rng.expovariate(rate)
        arrivi.append(t)
    liberi_alle, i, lat = 0.0, 0, []
    while i < len(arrivi):
        inizio = max(liberi_alle, arrivi[i])
        scade = inizio + ATTESA_MAX                          # the batch leaves when it is full or when the wait expires
        lotto = [a for a in arrivi[i:i + n_max] if a <= scade]
        if n_max == 1 or len(lotto) == n_max:
            parte = max(inizio, lotto[-1])                   # full: leaves as soon as the last one arrives
        else:
            parte = scade                                    # not full: it waited the whole window
        fine = parte + durata(len(lotto))
        lat += [fine - a for a in lotto]
        liberi_alle, i = fine, i + len(lotto)
    lat.sort()
    return mean(lat), lat[int(len(lat) * 0.95)]

print(f"{'n max':>5s} {'capacity':>9s} {'servers':>7s} {'EUR/month':>10s} {'mean lat.':>11s} {'p95 lat.':>9s}")
for n_max in (1, 4, 8, 16, 32):
    cap = n_max / durata(n_max)                              # requests/s with always-full batches
    server = math.ceil(LAMBDA / (UTILIZZO_MAX * cap))
    m, p95 = simula(LAMBDA / server, n_max)
    print(f"{n_max:5d} {cap:9.3f} {server:7d} {server * COSTO_SERVER:10.0f} {m:9.1f} s {p95:7.1f} s")

# Output:
# n max  capacity servers  EUR/month   mean lat.  p95 lat.
#     1     0.093      31      12400      19.5 s    38.1 s
#     4     0.303      10       4000      21.1 s    34.9 s
#     8     0.488       6       2400      22.9 s    32.5 s
#    16     0.702       5       2000      24.8 s    34.8 s
#    32     0.899       4       1600      28.0 s    40.1 s

With batches of one request you need 31 servers, with batches of 32 you need 4: the monthly cost of the fleet falls from 12,400 to 1,600 euros, a factor of about 8, while the mean latency goes from 19.5 to 28.0 seconds. The gain is not linear: from 16 to 32 the cost falls from 2,000 to 1,600 euros and the p95 latency rises from 34.8 to 40.1 seconds, diminishing returns. The numbers depend entirely on the timing model I invented, and a real server behaves differently: they are not a measurement of your system, but they show the shape of the trade-off. With a low load, batching brings no capacity you need and you pay the maximum wait for nothing.

Quantisation: the memory of the weights goes down, that of the contexts does not

Quantising a model means representing its weights with fewer bits, for example 8 or 4 instead of 16. The documentation of llama.cpp's quantisation tool says it in the right terms: it reduces the model size and may speed up inference, but it may introduce a loss of accuracy, usually measured with perplexity or with the Kullback-Leibler divergence, which can be contained with an importance matrix. How much you lose depends on the model and the task, and has to be measured with a test like the one in the previous section, not assumed.

The listing does only the memory arithmetic, on an invented architecture of 7 billion parameters. It shows two facts: the weights take up 14, 7 and 3.5 GB at 16, 8 and 4 nominal bits (real formats add scale bits, so the values are approximate), and the token cache, per layer, per head and per dimension, weighs 128 KiB per token at 16 bits, regardless of the quantisation of the weights.

"""Quantisation and memory: the weights shrink with the bits, the token cache does not (unless it is quantised separately).
INVENTED architecture of 'medium' size (7 billion parameters, 32 layers, 8 KV heads of 128). Arithmetic only.
Real formats have extra scale bits: the values are nominal."""
PARAMETRI = 7e9
STRATI, TESTE_KV, DIM_TESTA = 32, 8, 128
MEMORIA_GB = 24.0           # memory available on the accelerator (example)
RISERVA_GB = 2.0            # activations, buffers, system: rough estimate of the example

def gb(byte):
    return byte / 1e9

def kv_per_token(byte_valore=2):
    """Key+value cache: 2 tensors, per layer, per KV head, per dimension."""
    return 2 * STRATI * TESTE_KV * DIM_TESTA * byte_valore

print(f"KV cache per token (16 bit): {kv_per_token() / 1024:.0f} KiB")
for contesto in (4_000, 32_000):
    print(f"  for a sequence of {contesto:6d} tokens: {gb(kv_per_token() * contesto):5.2f} GB")

print(f"\n{'weights':>8s} {'weights GB':>10s} {'4k sequences':>13s} {'32k sequences':>14s}")
for bit in (16, 8, 4):
    pesi = gb(PARAMETRI * bit / 8)
    libero = MEMORIA_GB - RISERVA_GB - pesi
    n4 = int(libero // gb(kv_per_token() * 4_000)) if libero > 0 else 0
    n32 = int(libero // gb(kv_per_token() * 32_000)) if libero > 0 else 0
    print(f"{bit:5d} bit {pesi:10.1f} {n4:13d} {n32:14d}")

# Output:
# KV cache per token (16 bit): 128 KiB
#   for a sequence of   4000 tokens:  0.52 GB
#   for a sequence of  32000 tokens:  4.19 GB
#
#  weights weights GB  4k sequences  32k sequences
#    16 bit       14.0            15              1
#     8 bit        7.0            28              3
#     4 bit        3.5            35              4

On 24 GB, with 2 GB of reserve, 16-bit weights leave room for 15 sequences of 4,000 tokens, 4-bit weights for 35: concurrency more than doubles. With sequences of 32,000 tokens the advantage almost disappears (1 sequence against 4), because each one takes up more than 4 GB of cache, and at that point the limit is the token cache, not the weights. Quantising the cache is possible as a separate choice, with its own loss of quality, and I did not measure it here. The operational conclusion is that quantisation pays when contexts are short and memory is the bottleneck; with long contexts the lever is a different one.

Frequently asked questions

Can I add up the savings of several techniques?

No: each technique acts on a share of the spend and the later ones act on what remains, so the factors multiply. In the article's example three levers that save 50%, 60% and 25% on their respective shares lead to 48.2% on the total, not to 135%.

How many examples do I need to replace a model with a smaller one?

It depends on the tolerance and the variability, but the article's example shows the order of magnitude: with a tolerance of 5 points and a true difference of 3, 1,000 examples are enough to show it and 200 are not. Compute the confidence interval on your own set before deciding.

Is batch processing always worth it?

It pays for jobs with a deadline that exceeds the 24-hour delivery window plus a margin. It is not applicable to anything that must answer immediately, and the eligible share of spend decides how much you save.

What you can do now

You can place a saving lever on a layer and estimate its effect on the total as share times saving, and you know why the per-layer percentages do not add up. You can say which jobs go to batch from their deadline, you can verify with a non-inferiority test whether a smaller model holds up, and you can read the trade-off between capacity and latency of request batching. You also know that quantisation reduces the memory of the weights but not that of long contexts. The parameters in the listings are invented: use your own. The next step, if you have accelerators, is to plan their use in the article on GPU planning; to decide between your own server and an API see the comparison of the two, and to control spend within the month the article on the monthly cost.

Sources

  • Batch processing (Claude documentation) - 50% discount, most batches in under an hour, 24-hour expiry, cache and batch combinable with best-effort hits between 30% and 98%; consulted on 2026-11-13
  • Batch API (OpenAI documentation) - 50% discount, 24-hour completion window; consulted on 2026-11-13
  • FinOps for AI Overview (FinOps Foundation) - choosing the least expensive model that meets the requirements, optimisation layers from hardware to demand; consulted on 2026-11-13
  • Efficient Memory Management for Large Language Model Serving with PagedAttention (Kwon et al., SOSP 2023, abstract) - token cache memory as the limit of the batch, 2-4 times improvement stated by the authors; consulted on 2026-11-12
  • llama.cpp: quantize (project README) - quantisation reduces size and may speed up inference, with possible loss of accuracy measured in perplexity or KL divergence; consulted on 2026-11-13
  • Local runs: python3 -I on the five listings (standard library), each twice with identical output; jobs, models, costs and times invented for the example. No model was run

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects