smartyfy.mrindigi.com

AI & Machine Learning Master Course — 188. Capacity, latency, and inference optimization

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 188: Capacity, latency, and inference optimization

Prerequisites: Lesson 187. Learning outcome: Benchmark resource use and compare optimization trade-offs with measured evidence.

Optimize against a measured bottleneck

Inference optimization begins with a workload and a measurement contract. State input sizes, batch sizes, concurrency, hardware, dependencies, warm-up, and which parts of the request path are timed. A speedup that excludes feature retrieval may have little effect when retrieval dominates total response time.

Separate throughput, per-request response time, tail latency, memory, and cost. An optimization can improve one while worsening another. Larger batches may improve compute utilization but increase waiting time. More worker processes may reduce queueing until memory or another shared resource becomes the bottleneck.

Build a benchmark that can answer the question

Use representative inputs and compare implementations that perform equivalent work. Warm up where relevant, repeat measurements, and report variability. Use a monotonic high-resolution timer for short elapsed intervals. Avoid timing unrelated setup in one implementation while excluding it from the other.

For a local numerical kernel, isolate the kernel first to understand its cost. Then benchmark the full pipeline separately, including conversion, validation, data access, and serialization. Do not label a kernel-only timing as an end-to-end service latency.

Record the environment and avoid claiming a measured speed ratio is a universal property. CPU scheduling, numeric libraries, thread settings, cache state, and input size can change results. A benchmark should be reproducible enough to investigate, not expected to print identical microsecond values on every run.

CPU lab: compare equivalent dot-product implementations

Save example188.py and run it with NumPy. It creates a synthetic two-thousand-by-eight matrix and supplied weights, then compares a Python scalar loop with NumPy matrix–vector multiplication. Both compute the same linear scores; no model fitting or prediction-quality evaluation occurs.

The script checks numerical parity, performs a warm-up, and records seven elapsed times for each implementation. It prints the median milliseconds for each. Those timing lines are real local measurements and will vary. The accompanying execution record preserves the observed values; the lesson does not prescribe a universal expected speedup.

The stable outputs are shape [2000,8], input bytes 128000, and output parity True. This byte count is the NumPy input buffer alone: 2000 × 8 × 8 bytes for float64 values. It excludes Python objects, weights, output buffers, allocator overhead, and runtime memory. Peak process memory therefore requires a different measurement.

from time import perf_counter
from statistics import median
import numpy as np
rng = np.random.default_rng(188)
x = rng.normal(size=(2000, 8))
w = rng.normal(size=8)
def scalar():
    return np.array([sum(float(a)*float(b) for a,b in zip(row,w)) for row in x])
def vector():
    return x @ w
assert np.allclose(scalar(), vector(), rtol=1e-12, atol=1e-12)
for function in (scalar, vector):
    function()  # warm-up
    elapsed = []
    for _ in range(7):
        start = perf_counter(); function(); elapsed.append(perf_counter()-start)
    print('Timing', function.__name__, 'median_ms', round(1000*median(elapsed), 6))
print('shape', list(x.shape))
print('input bytes', x.nbytes)
print('output parity', True)

Understand why the implementation can matter

The scalar version repeatedly enters Python-level loops and converts values. The vectorized version delegates the matrix operation to optimized numerical code. That often reduces interpreter overhead, but the measured advantage depends on size and environment. Vectorization can also allocate large intermediates in other problems, increasing memory pressure.

For this matrix–vector product, a conventional approximate operation count is two times rows times columns, or thirty-two thousand floating-point operations. This counts a multiply and accumulation per feature and is an approximation, not a measured instruction count. It should not be confused with the total work of a serving application.

Check whether batching, avoiding redundant conversions, reusing validated structures, or reducing unnecessary feature retrieval addresses the actual bottleneck before changing the model architecture. Simple data-path fixes can matter more than a sophisticated numerical optimization.

Treat model compression as a quality change

Quantization reduces numeric precision. Pruning removes selected parameters or computation. Distillation trains a different model to approximate another model or task behavior. These approaches can alter predictions, supported operators, memory use, and hardware efficiency in different ways.

Evaluate compressed or converted artifacts under the same relevant protocol as the original. Include important slices, calibration, threshold decisions, and stress behavior when appropriate. Small average numerical differences can flip decisions near a boundary, so output parity alone may be too strict for some conversions and too weak for others.

The present script implements none of these compression methods. It compares two implementations of the same supplied linear calculation. Do not describe a faster matrix multiplication as a trained compressed model.

Interpret system-level limits

Suppose model computation takes twenty milliseconds in a hundred-millisecond request. Halving that computation saves ten milliseconds, reducing the total to ninety, assuming everything else stays fixed. The end-to-end speedup is about 1.11, not two. This is why bottleneck measurements should guide priorities.

Test behavior under realistic load and input-size distributions. Mean latency can hide slow requests, and a tail estimate from a tiny sample is unstable. Include failures and timeouts in the report rather than dropping them to produce a better latency number.

Choose an optimization only after checking its benefit, quality impact, implementation complexity, and rollback path. Preserve a benchmark script and environment record so later changes can be compared fairly instead of relying on remembered timing claims.

Four practice questions with worked answers

Practice 1

Verify the input buffer size.

Answer: There are 2000 × 8 = 16000 float64 values, each eight bytes. Their buffer occupies 128000 bytes. This is not total process memory or peak allocation.

Practice 2

A hundred-millisecond request spends twenty milliseconds in model compute. What if compute becomes twice as fast?

Answer: Compute falls to ten milliseconds, so total time becomes ninety if other costs stay fixed. Speedup is 100/90 ≈ 1.111, showing that a kernel speedup does not apply to the entire request.

Practice 3

Why are exact timing outputs not used as reproducibility assertions?

Answer: Elapsed time varies with scheduling, hardware, libraries, and other activity. Assert functional equivalence and valid measurement procedure, then report observed timing distributions rather than demanding identical durations.

Practice 4

Does the script demonstrate quantization?

Answer: No. Both paths use the same supplied double-precision inputs and weights. It compares implementation overhead and numerical computation, not reduced-precision model conversion or retraining.

Five multiple-choice questions

Question 1

What must a fair benchmark keep clear?

  • A. Only the fastest observed run from each implementation
  • B. Only the model’s parameter count regardless of the input workload
  • C. Which work is included and whether both implementations are equivalent

Correct: C. Comparable scope and workload are necessary to interpret timing differences.

Question 2

What does x.nbytes measure here?

  • A. Total peak process memory including every allocation
  • B. Compressed artifact size on disk
  • C. Bytes occupied by the NumPy input data buffer

Correct: C. The array buffer is a specific component of memory use, not a complete resource profile.

Question 3

Why warm up before repeated timings?

  • A. To reduce some initialization effects when measuring steady execution
  • B. To remove the need to record hardware and dependencies
  • C. To guarantee every later timing is identical

Correct: A. Warm-up can reduce initialization influence but does not eliminate variation or environmental dependence.

Question 4

Which claim is supported by the lab?

  • A. Both implementations produce numerically matching scores on the fixture
  • B. Every compressed model preserves the original decisions
  • C. The vectorized path is universally fastest at every input size

Correct: A. The parity assertion applies to the supplied inputs; timing and compression claims require their own evidence.

Question 5

What should follow a quantized-model conversion?

  • A. Assume unchanged decisions because file size decreased
  • B. Quality and operational evaluation of the converted artifact
  • C. Reuse all original metrics without checking conversion effects

Correct: B. Reduced precision may alter outputs and runtime behavior, so the converted artifact needs relevant evaluation.

Common pitfalls

Do not compare unequal work, discard slow runs without explanation, confuse buffer bytes with peak memory, or extend a local kernel speedup to every workload and service.

Summary

Optimization requires equivalent-work benchmarks and a system-level view of latency, throughput, memory, and quality. Real local timings are useful evidence when their scope and variability remain explicit.

Primary sources and further reading