A Practical Guide to LLM Selection: Scenario Conditions, Resource Math, and Deployment Strategies

    Choosing the right large language model for local or self-hosted deployment is not about finding the "strongest" model, but the best fit for a specific task, hardware budget, and cost ceiling. This guide walks through the full selection process for engineers and technical decision-makers: how to estimate GPU memory and KV cache, how to interpret cold-start and warm-start latency, why decoding is memory-bandwidth-bound, how quantization and batching act as high-leverage knobs, and how service form, a decision tree, and a business-focused evaluation loop turn "which model is stronger" into a reproducible, data-backed decision.

    Introduction: Three Questions Every Selection Must Answer

    Asking “which model is stronger” rarely yields a useful answer, because “strong” only has meaning relative to a specific task, hardware constraints, and a cost ceiling. When engineers and business owners deploy a large model locally, they usually need to answer three questions:

    1. Is there enough VRAM and system memory?
    2. What latency can users and downstream systems tolerate?
    3. After switching to a lighter, more resource-efficient option, can output quality still hold the line?

    Selection is fundamentally about finding a feasible point across four dimensions: quality, latency, throughput, and cost. Parameter count is only a rough proxy for resource demand and the quality ceiling. Actual behavior also depends on quantization precision, context length, concurrency, and the inference implementation. Starting from resource estimation, the sections below break down the key variables involved in selection, layer by layer.

    1. Resource Profile: Estimate VRAM First, Talk Performance Later

    Whether VRAM is sufficient is the first gate that decides if a plan can work at all. Runtime VRAM is mainly composed of four parts:

    • Weights: determined jointly by parameter count and precision, usually the largest piece
    • KV Cache: the key-value cache grows with context length and concurrency, and is the most easily underestimated part in long-context scenarios
    • Activations and runtime buffers: affected by batch size, intermediate tensor size, and the compute implementation
    • Framework runtime overhead: compute graphs, communication buffers, memory fragmentation, and so on

    Weight VRAM can be estimated quickly from parameter count and precision. A 4B-parameter model takes roughly 8 GB in FP16, about 4 GB in INT8, and about 2 GB in INT4. Actual usage should add another 10%–20% for metadata and runtime overhead. The size of the KV Cache for a single sequence can be estimated with a general formula:

    1. KV bytes = 2 × num_layers × kv_heads × head_dim × seq_len × bytes_per_element

    Here the factor of 2 accounts for the key and value parts. Using 32 layers, 8 KV heads, head dimension 128, and FP16 as an example, each token takes about 128 KB, and a single sequence with an 8K context takes about 1 GB. At 32 concurrent sequences that becomes roughly 32 GB—enough to hold another full INT4-quantized 8B model. So when a “small model keeps overflowing VRAM,” the culprit is almost always the KV Cache accumulating with concurrency and context length.

    If the model uses grouped-query attention, where multiple query heads share fewer key-value heads, the KV Cache shrinks proportionally. If it uses only single-directional attention, no past key-values need to be cached at all. The following script estimates a VRAM lower bound from the configuration and gives capacity hints:

    1. import math
    2. def estimate_memory(num_params, num_layers, kv_heads, head_dim,
    3. bytes_per_elem=2, seq_len=8192, concurrency=1,
    4. weight_bytes=0.5, runtime_overhead=1.1):
    5. # 1. Weights: parameter count × bytes per parameter, times a runtime overhead factor
    6. weights = num_params * weight_bytes * runtime_overhead
    7. # 2. KV Cache: only bidirectional (autoregressive) models need to cache past key-values
    8. kv_per_token = 2 * num_layers * kv_heads * head_dim * bytes_per_elem
    9. kv_cache = kv_per_token * seq_len * concurrency
    10. # 3. Activations and runtime buffers: reserve ~15%-25% of weights + KV based on experience
    11. reserve = 0.2 * (weights + kv_cache)
    12. total_gb = (weights + kv_cache + reserve) / 1024 ** 3
    13. return {
    14. "weights_gb": weights / 1024 ** 3,
    15. "kv_cache_gb": kv_cache / 1024 ** 3,
    16. "total_gb": total_gb,
    17. "max_concurrency_24g": math.floor(24 * 1024 ** 3 /
    18. (kv_per_elem := (kv_per_token * seq_len + weights + 0.2 * weights))
    19. if seq_len > 0 else 0),
    20. }
    21. # Example parameters only illustrate the calculation; use the target model's actual configuration
    22. print(estimate_memory(num_params=4_000_000_000, num_layers=36,
    23. kv_heads=8, head_dim=128,
    24. bytes_per_elem=1, # e.g., INT8-quantized KV Cache
    25. weight_bytes=0.55, # INT4 weights ~0.5 bytes/param, including metadata
    26. seq_len=8192, concurrency=8))

    Two practical points deserve attention. First, the context window should reflect the business P95 requirement, not the maximum the model claims. Once the context is maxed out, most requests pay for history they never use. Second, leave a safety margin in VRAM usage. Running persistently near the ceiling makes it easy to hit an out-of-memory error due to fragmentation, a concurrency spike, or longer inputs. Paged memory management in continuous batching can ease fragmentation but cannot remove the capacity ceiling.

    2. Latency Structure: Cold Start, Warm Start, and Staged Metrics

    2.1 Cold Start: Focus on “Load + Warmup”

    Cold start is the entire process of a new process or instance loading from scratch to stable service. The time comes mainly from four stages:

    1. Weight loading: affected by storage bandwidth, network bandwidth, and file format. Pulling from a local high-speed disk, network storage, or remote object storage yields very different orders of magnitude.
    2. Weight conversion: shard assembly, quantized decoding, data type conversion, and layout rearrangement.
    3. Device memory copy and VRAM allocation: transfer and allocation time typically grow roughly linearly with weight size.
    4. Graph compilation and warmup: compute graph optimization, kernel auto-tuning or static graph capture, plus running typical inputs ahead of time so the memory pool and cache allocator reach steady state.

    Step 4 is often overlooked. Without warmup, the tail latency of the first few requests can be noticeably worse than the steady-state behavior. Mitigations include: converting weights into an inference-friendly format and caching them ahead of time on local high-speed storage; generating static graph configurations during the deployment warmup step; baking common models into the image; and setting persistent replicas and a minimum instance count so scaling always happens before requests arrive.

    2.2 Warm Start: Focus on “Queueing + First Token”

    Warm start usually refers to the process from receiving a request to starting to emit text when the process and weights are already resident in memory. The overhead is made up of request queueing time and first-token compute time. First-token latency is far more closely tied to perceived user experience than decoding speed: in conversational scenarios, a first-token wait exceeding one second is easily perceived as “sluggish.”

    2.3 Unifying the Metric Definitions

    Different models’ “generation speed” often varies wildly in test conditions, so the definitions should be aligned before comparing:

    • TTFT (Time To First Token): first-token latency, determined jointly by queueing, prefill, and scheduling
    • TPOT / ITL: average time per output token, i.e., the decode step length, which determines the smoothness of streaming output
    • End-to-end latency: TTFT plus the product of output length and ITL
    • Total throughput: the service’s total output tokens/s, which determines how many users a unit of cost can support
    • Input/output length: must be recorded, otherwise the numbers are not comparable
    • Percentiles: looking only at averages hides tail problems; P95/P99 are the basis for an SLA

    From this you can derive a practical capacity-planning formula. Let the target throughput be Q (requests/s), average output length L, and average ITL T. The concurrency the system must sustain is roughly N = Q × L × T. Then check whether a single instance’s maximum concurrency exceeds N. If not, you need to scale out the number of instances or tune the batching parameters.

    The following script measures cold start and warm start in a separate process and collects staged latency:

    1. import json
    2. import subprocess
    3. import time
    4. # The runtime command is a placeholder; replace it with an executable process launch command for your deployment
    5. RUNTIME_CMD = ["your_runtime", "serve", "--model", "/models/demo"]
    6. def bench_startup(prompt, output_tokens=64, timeout=120):
    7. # 1) Cold start: the subprocess loads weights and completes warmup; time roughly covers loading, allocation, and warmup
    8. t0 = time.perf_counter()
    9. proc = subprocess.Popen(
    10. RUNTIME_CMD,
    11. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
    12. stderr=subprocess.STDOUT, text=True,
    13. )
    14. proc.stdin.write(json.dumps({"prompt": "warmup", "max_tokens": 8}) + "\n")
    15. proc.stdin.flush()
    16. assert proc.stdout.readline().strip(), "warmup request returned nothing"
    17. cold_startup = time.perf_counter() - t0
    18. # 2) Warm start and staged latency: read the streaming output token by token
    19. t_start = time.perf_counter()
    20. proc.stdin.write(json.dumps({
    21. "prompt": prompt, "max_tokens": output_tokens, "stream": True,
    22. }) + "\n")
    23. proc.stdin.flush()
    24. ttft, t_prev, inter_token = None, t_start, []
    25. while True:
    26. line = proc.stdout.readline()
    27. if not line:
    28. break
    29. ev = json.loads(line)
    30. if ev.get("error"):
    31. raise RuntimeError(ev["error"])
    32. now = time.perf_counter()
    33. if ev.get("type") == "token":
    34. if ttft is None:
    35. ttft = now - t_start
    36. inter_token.append(now - t_prev)
    37. t_prev = now
    38. elif ev.get("type") == "done":
    39. break
    40. proc.terminate()
    41. proc.wait(timeout=10)
    42. inter_token.sort()
    43. p95_itl = (inter_token[min(len(inter_token) - 1,
    44. int(0.95 * len(inter_token)))]
    45. if inter_token else float("nan"))
    46. return {
    47. "cold_startup_s": round(cold_startup, 3),
    48. "ttft_s": round(ttft or float("nan"), 3),
    49. "mean_itl_ms": round(1000 * sum(inter_token) / len(inter_token), 1)
    50. if inter_token else None,
    51. "p95_itl_ms": round(1000 * p95_itl, 1),
    52. "output_tokens": len(inter_token),
    53. }
    54. print(bench_startup("Summarize the meeting notes below in three sentences..."))

    Two easily overlooked details here:

    • When measuring “cold start,” the system page cache may already hold the on-disk data, so what you measure is “cold process, warm cache.” If you care about the real experience of first-time scaling, take the first result across repeated runs.
    • When measuring “warm start,” each event in the streaming protocol does not necessarily correspond to exactly one token. For example, multiple tokens may be merged into a single incremental message, or accompanied by intermediate events. So the timing above is per event, and ITL should be understood as “the time interval per output event.” For strict measurement, have the runtime explicitly return token indices in the stream.

    3. Decoding Speed and Deployment Conditions: Reading the Hardware Constraints

    3.1 Why the Decode Phase Is “Bandwidth-Bound”

    Autoregressive inference has two phases, and their hardware bottlenecks are completely different:

    • Prefill: processes all input tokens in parallel, is compute-intensive, and is mainly limited by compute capacity
    • Decode: generates only one token per step but must re-read all the weights and the KV Cache of every sequence, and is memory-access-intensive

    The theoretical upper bound for a single decode step can be approximated as:

    1. Single-instance throughput ceiling ≈ effective memory bandwidth ÷ bytes of weights and KV read per step
    2. Single-instance max concurrency ≈ single-instance throughput ceiling ÷ per-request ITL

    The first formula shows that halving weight quantization can roughly double the decode speed ceiling in theory. Actual speedup is usually smaller than theoretical, due to dequantization overhead, memory access efficiency, operator implementation, and communication and scheduling overhead. The second formula shows that the total throughput gains from higher concurrency quickly diminish once the memory-bandwidth ceiling is reached.

    The following table is only meant to illustrate qualitative differences across deployment conditions, not measured data for any specific model or hardware:

    Deployment condition Typical constraint Better-suited scenario
    Small parameter scale + low-precision quantization + consumer or lightweight accelerator Limited VRAM capacity and memory bandwidth Edge devices, personal terminals, offline tools, lightweight summarization and classification
    Medium parameter scale + medium precision + single-card resident service A single card’s VRAM must hold both weights and KV Cache Everyday conversation, customer-support assistance, structured information extraction
    Medium-to-large parameter scale + multi-card tensor parallelism Constrained by cross-card communication overhead and parallel partitioning efficiency High-quality generation, long-document analysis, complex reasoning
    Large model + CPU/memory offloading Compute runs on general-purpose processors, limited by memory bandwidth and compute Low-interaction, offline batch-oriented tasks
    Cloud elastic instances + pre-warmed replicas Affected by cold start, network, and billing model Online services with pronounced traffic fluctuation

    When a single machine’s VRAM cannot hold all the weights and KV Cache, the common approach is tensor parallelism: split each layer’s weights by column or by row across multiple cards, and combine results via collective communication after each card computes. Tensor parallelism breaks through the single-card VRAM ceiling, but every decode step requires communication. So the gains are clearly higher in high-speed inter-card interconnect environments than over ordinary networks, and the more cards there are, the more the gains diminish. Pipeline parallelism splits by layer with less communication, but introduces pipeline bubbles.

    CPU and memory offloading suits scenarios with insufficient VRAM and low sensitivity to interaction latency. The cost is not just speed but memory capacity: weight size is several times the quantized VRAM footprint, so reserving roughly 1.5–2× the weight VRAM is a safe starting point for memory, while also estimating the CPU memory cost of concurrent requests.

    On cloud platforms such as Baidu AI Cloud, these conditions typically correspond to different instance types, containerized deployment, and general capabilities like object storage. The practical principle is a single one: match the model’s resource profile to the instance’s VRAM, memory, and network characteristics—avoid using a large instance for a small workload, or letting a model run persistently near the capacity ceiling.

    4. Quantization, Batching, and Attention: Three High-Leverage Knobs

    4.1 Quantization: The Most Direct Resource Knob

    Quantization is a general technique that maps floating-point weights and activations to low-bit integer representations. Dequantizing back to floating point at load time and executing in floating point during inference, while executing and accumulating in low-precision integers during inference, is “weight-only quantization.” Quantizing both weights and activations is full quantization. The main trade-offs are:

    • VRAM and loading: low-bit weights directly reduce VRAM and loading time
    • Decode speed: lower weight read volume, with the most obvious gains for bandwidth-bound decoding
    • Numerical precision: symmetric quantization is simple to implement, while asymmetric quantization better suits skewed weight distributions; per-channel or per-group quantization, plus keeping sensitive layers at high precision, can noticeably reduce error
    • Implementation dependency: some low-bit operators require specific hardware capabilities; on general accelerators they may fall back to a dequantization path, reducing the gains

    A quality regression on the quantized version is mandatory before launch. Errors usually concentrate in long-chain reasoning, numerical computation, and strict-format output tasks. A sound approach is to compare against the unquantized version, using a business evaluation set to check accuracy, format validity, and human ratings.

    4.2 Batching: The Trade-off Between Single-Request Speed and Total Throughput

    The decode phase is memory-access-intensive, and multiple sequences in the same batch share a single weight read, so increasing batch size can significantly raise the number of tokens produced per unit of VRAM bandwidth. This brings several points to weigh:

    • Static batching requires all requests in a batch to arrive and finish together; when long and short requests run mixed, short requests get “held back” by long ones
    • Continuous batching lets requests join and leave one by one, significantly improving GPU utilization, but requests within the batch contend for resources, so single-request ITL grows longer
    • Chunked prefill cuts long inputs into small chunks and schedules them mixed with decode requests, easing the problem of long-input requests blocking decode and causing stutter in emitted text

    So batch size, the maximum wait window, and chunk size should all be tuned with the SLA as a constraint. A typical parameterized configuration and pseudocode:

    1. SERVING_CONFIG = {
    2. "max_batch_size": 16, # max concurrent sequences per batch
    3. "max_num_seqs": 64, # upper limit of sequences allowed to reside in the engine simultaneously
    4. "batch_timeout_ms": 5, # batching wait window: larger = higher throughput, slower first token
    5. "chunked_prefill_tokens": 2048, # max prefill tokens per step
    6. "max_model_len": 8192, # context limit: must cover the business P95 input length
    7. "gpu_memory_utilization": 0.85, # VRAM watermark: leave headroom for fragmentation and bursts
    8. }
    9. def scheduler_loop(runtime, pending_requests, config, deadline_fn):
    10. # continuous batching scheduler skeleton
    11. while True:
    12. # 1) Form a batch within the timeout window: wait at most batch_timeout_ms after a request arrives
    13. batch = runtime.form_batch(pending_requests,
    14. timeout_ms=config["batch_timeout_ms"])
    15. # 2) Chunk the prefill of long inputs and mix it with decode requests
    16. runtime.mix_chunked_prefill(batch,
    17. chunk_size=config["chunked_prefill_tokens"])
    18. # 3) Single step: every sequence in the batch advances one token
    19. runtime.step()
    20. # 4) Retire requests that generated an end token, exceeded the length limit, or were canceled by the client
    21. runtime.retire_finished()
    22. # 5) Actively end expired requests to avoid one request dragging down the whole batch
    23. runtime.cancel_expired(deadline_fn)

    This set of parameters has no global optimum. Interactive assistants should prioritize compressing first-token latency; offline batch processing can instead increase batch size as much as possible within an acceptable time window.

    4.3 Attention and Context: Controlling the Cost of “Long”

    Standard attention’s compute and memory cost grows quadratically with context length. Common mitigations include: sliding-window or hierarchical sparse attention (attending only to local or a few global positions), KV Cache quantization, and on-demand per-layer cache offloading. Some models use single-directional attention, where historical state is passed through recurrent or gating mechanisms and no full cache needs to be kept; such designs suit streaming, long-horizon scenarios.

    In engineering terms this boils down to three points:

    • Sliding-window approaches keep a single sequence’s KV usage roughly constant, making capacity more controllable for long context and high concurrency
    • Full-attention approaches are usually more robust for precise localization and global consistency, but the VRAM cost for long context stacks linearly with length and concurrency
    • Hybrid approaches try to get the best of both, suiting businesses that mix long documents with multi-turn conversation

    Specific capabilities are design trade-offs and should be validated on the business evaluation set, not trusted from the claims in a spec sheet.

    5. Service Form: Resident, Elastic, and On-Demand

    The choice of service form directly determines whether cold start becomes part of the user experience.

    • Resident process: weights stay in VRAM with almost no cold start, suiting stable-traffic core paths. The cost is that VRAM is occupied long-term, and the more models there are, the greater the VRAM pressure.
    • Elastic instances: paired with monitoring alerts and auto-scaling, using pre-warmed replicas, a minimum instance count, and local weight caching to offset cold start; suited to scenarios with pronounced traffic fluctuation.
    • On-demand tasks: the model is loaded on demand, suited to offline batch processing, scheduled jobs, and low-frequency calls; cold start is acceptable, but timeouts and retries must be set.

    When multiple models coexist, two kinds of trade-offs are possible: time-sliced switching on a shared instance based on available VRAM, or keeping resident replicas for high-frequency models while loading long-tail models on demand. Whether auto-scaling is needed can be decided by queueing latency:

    1. # Pseudocode: sample rules for metric-based scaling; specific fields depend on your monitoring/scheduling system
    2. autoscaling:
    3. metric: queue_wait_ms # can also use GPU utilization or VRAM watermark
    4. target_p95: 50
    5. scale_out_when: metric_p95 > target_p95 * 1.5 for 60s
    6. scale_in_when: metric_p95 < target_p95 * 0.5 for 10min
    7. cooldown_sec: 300 # cooldown period to avoid scaling flapping
    8. min_replicas: 1 # resident replicas to offset cold start

    Two more points belong in the design. First, both queueing latency and the VRAM watermark should be monitored. Platforms that offer metrics-computation and model-serving services usually provide general capabilities like metrics collection, logging, alerting, auto-scaling, and load balancing, but parameters such as scaling cooldown time and probe configuration must be set by the business according to its own SLA. Second, load testing should use input lengths and output lengths close to the real distribution. A QPS that looks impressive from synthetic short requests will quickly degrade in P99 and queueing latency once real long requests arrive.

    6. Selection Decision Tree and Deployment-Condition Matching

    Combining the four dimensions of quality, latency, throughput, and cost, you can form the following decision path:

    1. Can you call a general-purpose large-model API in the cloud?
      • Yes, and data compliance and latency are satisfied: prefer it, since the operational burden of self-hosting far outweighs the benefit.
      • No (data cannot leave the domain, offline availability is required, or per-call cost is too high): take the self-hosted deployment route.
    2. Is deployment on-device or server-side?
      • On-device: prefer small parameter scale, INT4 quantization, and sliding-window attention, keep context length restrained, and offload complex reasoning to the cloud.
      • Server-side: proceed to the next step.
    3. Can a single machine’s VRAM hold the target model (weights + KV Cache + margin)?
      • Yes: single-card resident.
      • No, but with high-speed interconnect: multi-card tensor parallelism.
      • No, and hardware is constrained: a large model with CPU offloading, accepting lower speed.
    4. Interactive or batch processing?
      • Interactive: prioritize TTFT and P95 ITL, use a smaller batch wait window, enable chunked prefill, and add pre-warmed replicas.
      • Batch processing: prioritize total throughput and unit cost, increase batch size and the wait window, and consider low-bit quantization and KV Cache quantization.
    5. Can quality hold up?
      • Yes: freeze the configuration and establish baselines and regression evaluation.
      • No: increase parameter scale or precision, tighten the quantization strategy, or bring in external capabilities such as retrieval augmentation or tool calling to compensate.

    Deployment conditions can be summarized as four matching principles:

    • VRAM capacity ↔ parameter count × precision + estimated KV Cache
    • Memory bandwidth ↔ decode speed and quantization gains
    • Inter-card interconnect ↔ choice of parallel strategy
    • Storage and network ↔ cold-start time

    If any pair is mismatched, it shows up as “it runs but it’s not usable”: the model loads, but the first token is slow, text emission stutters, and VRAM overflows as soon as concurrency rises.

    7. Evaluation and Observability: Making Selection Verifiable and Iterative

    7.1 Building a Business-Relevant Evaluation Set

    Public leaderboards can only be used for coarse screening, because task distribution, prompt wording, and evaluation criteria often differ greatly from a given business. It is recommended to sample 200–500 real requests from production, cover them in layers by task type, and keep a holdout set that does not participate in tuning, for final acceptance.

    For generative tasks, a mix of three evaluation approaches is recommended:

    • Automatically determinable metrics: field accuracy for structured extraction, unit-test pass rate for code tasks, macro-averaged F1 for classification, retrieval hit and citation coverage, JSON parse success rate
    • Rule- and model-assisted scoring: format compliance, factual consistency, key-point coverage
    • Blind evaluation and pairwise comparison: hide the model source, have reviewers compare candidate solutions two at a time, and tally win rate and consistency

    7.2 Length-Stratified Testing

    Measure TTFT and ITL separately for short-input, long-input, and long-output scenarios. Long input mainly affects prefill, long output mainly affects decode, and when the two appear mixed, also observe the degree of intra-batch interference.

    7.3 Failure-Scenario Load Testing

    The following scenarios must be covered: maximum context; concurrency gradients (e.g., 1, 8, 32, 128); long-tailed input length distribution; many requests canceled midway; and the VRAM watermark approaching the ceiling. Record timeout rate, cancellation rate, number of VRAM overflows, and P99 latency.

    7.4 Observability

    It is recommended to fix the selection metrics directly into monitoring dashboards and alert rules:

    • Latency: P50/P95/P99 of TTFT, ITL, and end-to-end latency
    • Throughput: output tokens/s, concurrency, queue length, and queueing latency
    • Resources: VRAM utilization, VRAM watermark, memory utilization
    • Quality: format error rate, human ratings, negative-feedback rate in user feedback
    • Cost: cost per thousand tokens, average cost per request, resource utilization

    The following pseudocode gives a lightweight metrics collector; the specific collection method for each metric depends on the runtime and monitoring system:

    1. import time
    2. from collections import deque
    3. class LatencyTracker:
    4. """Sliding-window stats, to align with the P95/P99 definitions in monitoring dashboards"""
    5. def __init__(self, window=1024):
    6. self.ttft = deque(maxlen=window)
    7. self.itl = deque(maxlen=window)
    8. self.total = deque(maxlen=window)
    9. def record(self, ttft_s, itl_s, total_s):
    10. self.ttft.append(ttft_s)
    11. self.itl.append(itl_s)
    12. self.total.append(total_s)
    13. def snapshot(self):
    14. def pct(seq, p):
    15. if not seq:
    16. return None
    17. s = sorted(seq)
    18. return s[min(len(s) - 1, int(p * len(s)))]
    19. return {
    20. "ttft_p50": pct(self.ttft, 0.50),
    21. "ttft_p95": pct(self.ttft, 0.95),
    22. "ttft_p99": pct(self.ttft, 0.99),
    23. "itl_p95": pct(self.itl, 0.95),
    24. "e2e_p99": pct(self.total, 0.99),
    25. "sample": len(self.ttft),
    26. }
    27. def timed_request(client, request):
    28. t0 = time.perf_counter()
    29. resp = client.stream(request) # returns an iterable streaming response
    30. it = iter(resp)
    31. first = next(it)
    32. ttft = time.perf_counter() - t0
    33. t_prev, count = time.perf_counter(), 1
    34. for _ in it: # measure the intervals of the remaining tokens
    35. now = time.perf_counter()
    36. count += 1
    37. t_prev = now
    38. total = time.perf_counter() - t0
    39. # average ITL = (total time - first-token time) / number of subsequent tokens
    40. return ttft, (total - ttft) / max(count - 1, 1), total

    8. Common Pitfalls

    1. Looking only at parameter count: at the same parameter count, differences in attention design, data quality, and training approach can produce clear gaps in task performance.
    2. Treating “single-request speed” as “service throughput”: under continuous batching, total throughput and single-request ITL move in opposite directions.
    3. Ignoring cold start and warmup: a model that finishes loading without warmup makes the first batch of users endure noticeably longer tail latency.
    4. Maxing out the context: the vast majority of business requests never need the maximum window, yet the KV Cache is paid for at the ceiling.
    5. Looking only at averages: P99 determines the “worst experience” and whether scaling is needed.
    6. Skipping quality regression: after quantization or an implementation change without a business regression, offline metrics look normal while online output goes wrong.
    7. Ignoring operational burden: the version combination of models, runtimes, drivers, and acceleration libraries needs long-term maintenance; this cost should be counted at selection time.

    9. Launch Checklist

    • VRAM estimation: weights + KV Cache + reserved margin, and verify the maximum concurrency under the business P95 context.
    • Latency definitions: validate TTFT, ITL, and end-to-end at P95/P99, with a load-test distribution close to real traffic.
    • Cold-start governance: warmup steps, weights baked into the image or a local cache, minimum instance count or pre-warmed replicas.
    • Quantization regression: complete a business-evaluation-set regression against the unquantized version, covering structured output and long-chain reasoning.
    • Batching parameters: tune batch size, wait window, and chunked prefill against the SLA, and run concurrency-gradient load tests.
    • Observability: wire the five metric categories—latency, throughput, VRAM, quality, and cost—into monitoring and alerting, with alert thresholds and scaling rules based on actual load-test data.
    • Capacity and elasticity: estimate concurrency with N = Q × L × T, and configure the scaling cooldown and fallback replicas.
    • Compliance and licensing: confirm the license scope of the model weights used, and put content-safety and data-desensitization policies ahead of the inference pipeline.

    Conclusion: From “Which Is Stronger” to “Which Is More Suitable”

    There is no global optimum in model selection. Small-parameter models have deployment advantages for edge and lightweight tasks; medium-scale models balance quality and resources in most everyday scenarios; larger models suit complex reasoning but require stricter hardware and scheduling design. What determines actual results is often not the differences on a spec sheet, but engineering details like quantization strategy, batching scheduling, context management, cold-start governance, and a closed evaluation loop.

    It is best to make selection a reproducible process: first estimate resources with formulas, then load-test to verify performance, and finally use the business evaluation set to guard quality. Leave a data baseline after every round of adjustment. That way, “which is stronger” stops being an argument and becomes a data-backed decision path.