smartyfy.mrindigi.com

Python Master Course V2 — 179. AI Latency, Resource Use and Quality Trade-Offs

Lesson 179: AI Latency, Resource Use and Quality Trade-Offs

Performance work begins with a precise question: which request path is slow, under what workload, and what quality must remain unchanged? This lesson benchmarks a tiny local retrieval assistant with empty and populated application caches, then records latency distributions and Python allocation measurements. No paid API is called. There are no token charges to estimate, and a speedup on these local fixtures cannot establish savings or latency improvements for a remote model service.

Learning objectives

  • Benchmark complete request paths with controlled inputs
  • Report latency distributions and resource measurements accurately
  • Compare caching and batching with quality and privacy constraints

Prerequisites and setup

108: profiling; 172–178: AI applications

Use Python 3.11 or newer in a local project folder. This lesson uses only the standard library, works on a CPU, and needs no account, API key, network service, or downloaded model. Save the worked Python example as lesson179.py. Run the example before extending it; keep the original assertions as regression checks.

python lesson179.py

Measure the path users actually wait for

End-to-end latency can include input validation, permission checks, retrieval, answer construction, output validation, and serialization. Timing only a dictionary lookup says little about a larger request path. In a network service, queueing and transport add further costs. Define the start and stop boundaries in the report so another reader knows what was measured.

Use a monotonic high-resolution performance clock for elapsed durations. Repeat controlled inputs, record individual samples, and summarize the distribution rather than reporting one favorable run. Median describes the middle request; a high percentile highlights slower requests. With forty observations, the estimated tail is very coarse, and scheduler noise can dominate a microsecond-scale toy example. More decimal places do not create more reliable evidence.

Distinguish cache state from process startup

An empty application cache is not the same as a cold operating-system page cache, an uninitialized model, or a new process. This experiment clears only functools.lru_cache before each cold measurement. It does not reload Python or remove filesystem caches. The warm experiment primes the three known queries and then reuses them. These definitions belong beside the results.

Cache keys must capture everything that changes the answer or access decision: normalized query, corpus version, model or prompt version when relevant, and user or permission scope where data is restricted. Never reuse a private answer for another user merely because the question text matches. Cached results also need an invalidation or expiry policy when evidence changes.

Measure resources without overstating them

tracemalloc reports memory allocations traced by Python, not total process resident memory, device memory, or every native-library allocation. Measure it in a separate pass here because instrumentation adds overhead to the latency experiment. Label the quantity and unit exactly. For richer applications, use suitable operating-system and accelerator tools rather than extrapolating from Python allocation counts.

Batching can improve throughput by amortizing overhead, but it may increase individual waiting time and mix requests with different privacy scopes. Caching can improve repeated queries while leaving first-time queries unchanged. Compare quality and workload coverage alongside speed: a fast cache that returns stale or unauthorized evidence is not an optimization you can accept.

Worked example: build, inspect, and test

The benchmark uses immutable tuple results so callers cannot accidentally modify cached answers. The corpus version participates in the cache key. Forty requests per phase cycle through two supported questions and one unsupported question. Every result is compared with an explicit expected answer, while timings are summarized using a nearest-rank 95th percentile. Actual numeric measurements will vary on your computer.

from functools import lru_cache
from math import ceil
from statistics import median
from time import perf_counter_ns
import tracemalloc

CORPUS_VERSION = "handbook-1"
FACTS = {"opening hours": ("answered", "09:00", "hours-v1"),
         "safety glasses": ("answered", "required", "safety-v1")}
QUERIES = ["opening hours", "safety glasses", "parking"]
EXPECTED = [FACTS["opening hours"], FACTS["safety glasses"],
            ("abstain", None, None)]

@lru_cache(maxsize=32)
def lookup(corpus_version, normalized_question):
    if corpus_version != CORPUS_VERSION:
        raise ValueError("unknown corpus version")
    return FACTS.get(normalized_question, ("abstain", None, None))

def request(question):
    if not isinstance(question, str) or not 1 <= len(question.strip()) <= 200:
        raise ValueError("invalid question")
    return lookup(CORPUS_VERSION, " ".join(question.casefold().split()))

def benchmark(cold, n=40):
    lookup.cache_clear()
    if not cold:
        for query in QUERIES:
            request(query)
    samples = []
    correct = 0
    for i in range(n):
        if cold:
            lookup.cache_clear()  # Reset is outside the timed boundary.
        start = perf_counter_ns()
        result = request(QUERIES[i % len(QUERIES)])
        samples.append((perf_counter_ns() - start) / 1000)
        correct += result == EXPECTED[i % len(EXPECTED)]
    ordered = sorted(samples)
    return {"phase": "cold" if cold else "warm", "n": n,
            "median_us": median(samples),
            "p95_us": ordered[ceil(0.95 * n) - 1], "correct": correct}

measurements = [benchmark(True), benchmark(False)]
lookup.cache_clear()
tracemalloc.start()
for query in QUERIES:
    request(query)
current_bytes, peak_bytes = tracemalloc.get_traced_memory()
tracemalloc.stop()
for row in measurements:
    assert row["correct"] == row["n"]
    print(f'{row["phase"]}: n={row["n"]}, median_us={row["median_us"]:.3f}, '
          f'p95_us={row["p95_us"]:.3f}, correct={row["correct"]}/{row["n"]}')
print("separate-pass peak traced bytes:", peak_bytes)

Expected output

cold: n=40, median_us=<measured>, p95_us=<measured>, correct=40/40
warm: n=40, median_us=<measured>, p95_us=<measured>, correct=40/40
separate-pass peak traced bytes: <measured>
The placeholders are output fields, not fabricated benchmark values.

Failure modes worth testing

Do not warm only the optimized implementation and compare it with an uninitialized baseline. Do not include cache clearing in one timed phase while excluding equivalent setup from another without explanation. Avoid rounding tiny times to zero or claiming universal throughput from this serial benchmark. A cache hit-rate increase is not proof of better user experience if answers become stale, quality falls, or private results cross access boundaries.

Guided lab

Run the benchmark several times in a quiet local environment and save raw samples as well as summaries. Record Python version, operating system, request mix, sample count, cache definition, and timing boundaries. Then add a corpus-version change and verify that old cached results cannot be reused under the new version. Compare repeated-query and mostly-unique-query workloads. Your report should explain where caching helps, where it does not, and whether observed differences are larger than ordinary run-to-run noise.

Questions with explained answers

What does cold mean in this experiment?

It means the application’s lru_cache is empty immediately before the timed request. Python, the process, and the operating system are already running. This narrow definition makes the comparison reproducible, but it does not measure model loading, service startup, or cold disk access.

Why report median and a high percentile?

The median describes a typical sample, while a high percentile exposes slower observations that an average may hide. Both depend on sample size and workload. Forty requests provide only a rough tail estimate, so report the count and avoid interpreting tiny differences as stable performance guarantees.

Why include a corpus version in the cache key?

The same question can have a different correct answer after evidence changes. Versioning prevents accidental reuse across source snapshots, provided the application uses the correct version and clears obsolete entries as needed. Restricted data additionally requires permission or identity scope in the key.

Does tracemalloc measure all memory used by a model?

No. It measures traced Python allocations and can miss memory allocated by native libraries or accelerators. Its peak is not equivalent to process RSS. Use the appropriate measurement for the resource question, and disclose instrumentation overhead and scope instead of labeling every memory number simply RAM.

Can this benchmark estimate token-cost savings?

No. The code performs local deterministic lookup and uses no metered generation service. It can compare local request latency and traced allocations under its workload. Any API cost analysis would require actual service pricing, usage records, cache billing behavior, and a separate quality-preserving experiment.

Exercises and worked solutions

Exercise 1. Verify normalization creates a cache hit for equivalent whitespace and case.

Worked answer 1

Cache identity uses normalized input, while source version remains explicit. The test clears state, performs one request, and checks that the equivalent request reuses the entry.

lookup.cache_clear()
assert request("opening hours") == request(" OPENING   HOURS ")
assert lookup.cache_info().misses == 1
assert lookup.cache_info().hits == 1

Exercise 2. A warm-cache run is slower than a cold-cache run on this tiny example. Is the code necessarily wrong?

Worked answer 2

No. The lookup is so small that measurement overhead, cache bookkeeping, CPU scheduling, and noise may dominate. Repeat under controlled conditions, inspect raw samples, and test a realistic workload. Report an inconclusive result honestly rather than choosing only runs that match the expected story.

Recap and completion check

You now have a benchmark with explicit boundaries, cache-state definitions, measured distributions, and a quality check. Completion means every number is labeled by unit, sample count, and measurement scope. Optimize only after establishing a repeatable bottleneck, and retain correctness, source freshness, and privacy as acceptance criteria alongside speed.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.