Serving a local LLM and enforcing structured output
Choose an open-license instruct model with 3 to 8 billion parameters, serve it quantized in GGUF through a local chat API, and measure prefill and decoding latency as context changes. Calculate the VRAM budget and implement grammar-constrained structured output, comparing valid JSON rates with and without constraints.
After this lesson you can
- Serve a quantized model locally and measure tokens per second during prefill and decoding.
- Calculate weight and KV cache memory and choose quantization and context for 8 GB.
- Implement JSON-schema-constrained decoding and measure the valid output rate.
- Write a client with retries, timeouts, and token usage logging.
Before you start
A contract before an agent
An agent that searches documents and calls tools needs two different things: a model capable of answering and an interface that can interpret its response without guessing where an argument begins. The first error can occur before the first answer: the weights fit in the GPU, but the conversation and its cache do not. The second occurs afterward: a string that looks like JSON has an extra comma, or a valid key contains a false answer.
In this lesson we will build the boundary between the model and the rest of the system. We will choose an instruct model and measure its server during prefill and decoding; then we will compare free generation with a grammar. The lab produces a table of measurements, not a speed promise: the card, server version, and concurrent load matter.
The comparison has a useful asymmetry: reducing weight bits saves memory once; reducing cache bits saves memory for every token and every conversation. However, a model that fits arithmetically may not fit in the real server: block metadata, activations, buffers, alignment, and memory used by other processes also matter. Free space must accommodate output, not just input.
The interactive compares Qwen architectures to isolate the effect of their KV heads. The lab uses Phi-3; one model’s figures are not measurements of the other. Choose a quantization and increase context without changing the other variables: the cache band grows linearly in this accounting model. Now double simultaneous requests: the same budget per sequence requires twice the state unless the server shares a prefix. Finally reserve auxiliary memory: the capacity that seemed to spare shrinks before the first token is generated. All these bars follow from the formula; they are not data from a run.
Model, template, and server
We will use Phi-3-mini-128k-instruct, whose model card identifies an MIT license and a size of 3.8 billion parameters. The Ollama phi3:mini distribution identifies Q4_0, the GGUF format, and the license; verify its tag and specific file before reproducing results, since a tag can change. The tag documentation contains conflicting information about the window: consult local file metadata and the effective reservation rather than assuming every file with that name has the same capacity. The original configuration specifies 32 layers, 32 attention heads, and 32 KV heads, with hidden dimension 3072. Thus the head dimension is 3072 / 32 = 96. The card says its intended use is mainly in English: for a Spanish-language agent we must explicitly evaluate language and task before accepting its quality.
GGUF stores weights and metadata for compatible engines. Q4_0 is a block quantization format: four bits per weight is an approximation because blocks include scales and some tensors and metadata have other representations. Quantized weights save memory and can change model behavior: low-bit representation and quantization error must not be confused with cache precision. Quantizing weights does not require quantizing keys and values. A quality comparison needs the same questions, instructions, and evaluation criterion for both versions, along with the actual quantization used.
Parameter count is an initial filter, not a guarantee that a model is suitable for an agent. Compare licenses, language support, retrieval and abstention quality, context limits, file size, and tool protocol. An advertised window is an architectural capability, not available memory or a guarantee of faithfully retrieving a fact at any position. Choose a small test task with a verifiable answer before connecting the model to a full corpus. A smaller model that leaves room for context can be preferable to a larger one with barely any space for documents; it can also reason less well. The choice requires measuring both properties.
Messages are structures, but the model receives tokens. The chat template interleaves roles, content, and special tokens according to training. A different template can radically change the task. Ollama publishes the template and stop sequences for its distribution; let the server apply it and inspect it if in doubt. The template delimits turns; it is not a security boundary against instructions inserted in a document. Tool support is independent of JSON support: the examined phi3:mini instance does not declare tool capability, so here we measure only text and format. Before connecting a tool with side effects, choose a model and template with explicit support and test the complete call-and-result cycle.
The Ollama API offers /api/chat, with metrics for both phases; it also documents an OpenAI-compatible subset. We will use the native API to observe its counters without attributing another server’s fields to it. Install Ollama for your platform, check that it listens on the local interface, and download the model from a registry you have verified:
ollama pull phi3:mini
ollama show phi3:mini
By default the local server uses the loopback address; check its configuration before sending private documents. The Ollama FAQ describes ollama ps, which shows whether the model is on GPU, CPU, or split. If some layers remain on CPU, file size plus cache is no longer a VRAM prediction. num_ctx configures context reservation for a request; verify the value actually applied, because neither the model tag nor the text size proves that the full nominal window was reserved. Do not expose the service to the Internet for convenience.
Cache accounting
With an available budget , weights , and auxiliary reserve , the ideal limit for equal lengths is
provided . The model’s and server’s window and position rules must also be respected. This maximum does not prove that an input of that length is useful or that activation computations fit. The inference budget must be measured with the same configuration and units: GB are bytes and GiB are bytes.
def kv_bytes(layers, tokens, kv_heads, head_dim, bytes_per_element, sequences=1):
return 2 * layers * tokens * kv_heads * head_dim * bytes_per_element * sequences
example = kv_bytes(32, 8192, 8, 128, 2)
print("bytes:", example)
print("GiB:", example / 2**30)
print("Phi-3, 8192 tokens, FP16, GiB:", kv_bytes(32, 8192, 32, 96, 2) / 2**30)
print("Phi-3, 131072 tokens, FP16, GiB:", kv_bytes(32, 131072, 32, 96, 2) / 2**30)The result, 3 GiB for 8192 tokens and 48 GiB for 131072, assumes the entire cache is in FP16 and stored without compression. It shows why nominal positional capacity does not automatically translate into an operational window of that size on an 8 GB GPU. Reducing KV precision, offloading part to RAM, or using another architecture changes what is possible and may also change latency or quality. The real value depends on what the server actually reserves and places on each device.
Where does the formula come from? Each layer and token has a key vector and a value vector per KV head. Each vector contains elements; multiplying by , then and , counts all elements. If the format uses bytes per element, the final multiplication gives bytes. The calculation for multiple sequences assumes they do not share memory and each reserves positions. With different lengths, replace with the sum of lengths or, if the implementation reserves by capacity, the sum of allocated capacities. An implementation with local attention, heterogeneous layers, or paged storage requires adapting the calculation to its architecture.
Query and KV heads are not interchangeable in the formula. In grouped attention, several query heads share keys and values: count KV heads for the cache, even though all query heads participate in computation. This explains why two similarly sized models can require different context budgets. Do not automatically multiply by the number of calls in a session either: if they are sequential and the server releases or reuses their space, not all coexist. Concurrent requests, on the other hand, may reserve separate caches even when weights are shared.
Weight accounting also needs a clear assumption. bytes is the ideal size of values at bits, not a GGUF measurement. To predict card memory, you must know how many tensors are loaded there, their effective representation, and the engine’s reservations. File size is a useful first check, but includes structures that may not be copied to the GPU and excludes some runtime reservations. An honest budget sums identifiable components plus an explicit reserve, checked against measurement, rather than retrospectively adjusting a figure to hide error.
To compare with the server, record VRAM usage before starting it and after loading it and reserving the cache, with the same context, batches, and backend. The measured difference includes buffers and other process allocations: record the tool’s granularity and avoid attributing changes from other processes to the model. Compare prediction and measurement as , using the same units and scope. An error below 10% can only be claimed after measurement; if it is not achieved, break down allocations and correct the model rather than adjusting a figure without evidence.
For an interpretable comparison, first fix the scope: whole-device or process-attributed memory, reserved capacity or occupied state, and context per sequence or total. Measure a baseline before loading the model; then measure again after loading and after requesting the selected context. If the engine reserves the whole cache at startup, memory may remain nearly constant as text grows even though logical occupancy increases. If it allocates blocks on demand, the opposite occurs. Both observations can be consistent with the same theoretical amount of useful data; they are comparable only when reservation is described.
On a shared GPU total-usage readings can change because of other processes. Recording conditions and repeating does not remove that noise, but helps recognize it. Do not infer precision from a result when noise exceeds the margin being checked. If the model is split between CPU and GPU, report that distribution and avoid comparing total theoretical memory with the VRAM of a fraction of the model. The practical decision rule is to leave a safety margin and check the application’s worst case, including retrieved text, history, template, output, and concurrency.
Measuring without confusing phases
Prefill processes input and builds the cache. Decoding generates one token at a time and consults that state. For a request, the server can report counts and times for processed and generated tokens separately; their ratios are the phases’ latency metrics. Total client time also includes local networking, queuing, serialization, and validation. Do not automatically equate prefill throughput with time to first token or decoding throughput with overall throughput.
When comparing contexts, use the effective tokens returned by the server, not character count or nominal window size. The native Ollama API reports counts and durations in nanoseconds. For input actually processed, divide its token count by prompt_eval_duration converted to seconds; if prefix tokens were reused, subtract them from the total only when that server version documents and returns the breakdown. Otherwise, do not present the ratio as uncached full-prefill throughput. For output, divide eval_count by eval_duration in seconds, provided the denominator is positive.
Time to first token requires a streaming measurement: start the clock before the request and mark it upon receiving the first fragment containing output. It can include model loading, queuing, and transport in addition to prefill; it is not identical to internal prefill time. If only a complete non-streaming response is requested, the client clock measures time to completion, not first token. Time between tokens also requires per-fragment timestamps and cannot be recovered by dividing total client time by token count if loading, queuing, or buffering occurred. Record whether fragments contain one or several tokens.
Warm up the server and record initial loading separately: comparing a cold request with a warm one would mix loading and inference costs. Fix model, version, quantization, reserved context, target output length, sampling parameters, and hardware. Change one variable at a time. Record truncations, errors, and zero-token cases without dividing by zero; retrying a failed request solely to fill a row would hide part of system reliability. The median summarizes the center of multiple runs and dispersion shows stability; retain individual rows to see outliers.
Target text length is not tokenized length. Repeating a prefix can activate cache reuse and turn a prefill comparison into something else. Use different inputs of comparable content, record the effective counter and any available reuse counter, and check that input is not truncated. If reused work cannot be distinguished, identify that limitation instead of attributing the entire difference to length. In particular, a real conversation contains template tokens and prior messages as well as the document; measure what the server receives.
To evaluate batch effects, change the server’s processing batch size in a controlled way and, separately, the number of concurrent requests. A prefill batch groups work within the engine; concurrency describes how many requests coexist. Increasing one does not imply the other changes in the same way. Under concurrency measure both aggregate throughput, completed tokens divided by elapsed time, and per-request latency from submission to response. A queue can improve aggregate utilization while making some requests wait. Do not extrapolate from short prompts to long contexts or between batch sizes without measuring.
Constraining language, not truth
The termination condition matters: a token limit, failure, or interruption can leave an incomplete prefix. A JSON grammar guarantees syntax only when generation successfully reaches a final state; an expressible, correctly implemented schema adds constraints on structure, types, and values. Neither guarantees that a claim is true or a citation exists. Ollama documents sending a schema in format and recommends validating the response on the client. The llama.cpp grammar documentation describes GBNF and conversion of a subset of JSON Schema: do not assume every standard constraint is translated or has identical semantics in every engine.
Imagine the prefix already contains a key and a boolean is expected. Depending on the grammar, the next characters must be able to lead to true or false; a token introducing a closing brace at that point is inadmissible. The actual check is per vocabulary token, which may represent multiple characters or bytes: deciding character by character without considering token decoding is insufficient. After accepting a token, update the state and repeat. A grammar describes possible continuations while the model chooses among those remaining. If no valid continuation remains, or the engine stops before closing, the client must receive and log a failure.
Three layers are useful to distinguish. The first is syntax: the text can be parsed as JSON. The second is schema: required keys appear, types are correct, and no forbidden properties occur. The third is semantics: the answer corresponds to the question and is supported by evidence. A string {"respuesta": "París", "abstencion": false} can pass the first two and fail the third if the question asked for something else. Conversely, correct content accompanied by text outside the object fails a strict parser. Record these categories separately to identify the needed repair.
A schema should represent real task states. If every question requires a nonempty string, the model is forced to choose even without evidence. An abstention flag can express uncertainty, but adds a semantic condition: the client must decide which field combinations it accepts and what abstention means. In an application with citations, checking that an identifier exists among retrieved passages is an additional validation; whether the passage actually supports the sentence requires a faithfulness evaluation. Correct data types do not resolve these questions.
The constraint changes the output distribution. If the admissible token set is and the model assigns probability to each token , a mask followed by renormalization assigns to each when the denominator is positive, and zero to the rest. This is not simply repairing an already generated answer: each choice conditions subsequent ones and can change the entire answer. A narrow grammar reduces invalid alternatives, but can also force unlikely choices if the contract poorly reflects the task.
The work of Willard and Louf formalizes guided generation through states and transitions and describes a vocabulary index for regular constraints and context-free grammars. It does not follow that every implementation has the same cost. We will measure cost with and without constraints using the same configuration and paired tasks. A schema that forces an answer before evidence is available can produce a formally valid but wrong answer: include an abstention option and check content against sources.
Lab: client and comparison
To compare formats, use 200 requests per condition and pair each question with its free and constrained version. Interleaving order reduces the chance of attributing a temporal load change to the grammar. Both conditions must receive the same task, generation limit, and parameters, differing only in the constraint mechanism. Request the format in the text of both conditions too; otherwise you would measure both the instruction and grammar effects. A simple schema lets the client check every requirement without relying on an incomplete validator.
The accepted-output proportion is the number of responses passing parsing and schema checks and ending without truncation divided by scheduled requests. Include errors and truncations in the denominator and report their causes separately. If the server does not report how a response ended, the conservative rule does not accept it either. This measures reliability of the whole system, not just arrived responses. Syntax and schema are also counted separately, even for a truncated response that happens to be parseable. If you additionally report the rate conditional on received responses, say so clearly. A 100% rate on this battery means no failures were observed in it, not that failure probability is exactly zero for every task. Factual accuracy requires independent labels and a different metric.
A real client needs a deadline per attempt, a finite retry count, and logging of tokens and stop causes. Retries can recover a transient interruption, but an invalid response must not silently disappear from a first-response measurement. Retain each attempt, even when a later one succeeds. A timeout does not prove the server did not process the request; if the client later invokes tools with effects, retrying without an idempotency key may duplicate an action. This experiment only generates text and invokes no tools.
For the context benchmark, save configuration, effective input count, internal prefill and output times, and full client time. Collecting several calls in a sequential loop does not make them a concurrent batch: studying concurrency requires genuinely overlapping requests and a server configured to allow them. Likewise, the format test does not demonstrate tool-calling capability. If those cases have not been measured, leave them as outstanding work rather than inventing example numbers.
The cell needs Python with requests and jsonschema, Ollama at 127.0.0.1:11434, and the downloaded phi3:mini tag. Run it from the repository with the server active. Verify the tag, license, quantization, and printed template before interpreting figures. It does not modify user documents or call tools: extraction cards are created in memory. The run saves every request, response, attempt, and check, plus summary tables, in a new directory within labs/runs/p05-l01/.
First warm up each context and batch combination, then compare three reserved contexts, three batch sizes, and three input lengths, with two repetitions per combination. Also warm up the card configuration and each batch of the long sweep; record these calls separately and exclude them from the tables. Then process 200 pairs of cards with and without a schema and finally sweep longer inputs. The tables contain server-reported tokens and stop reasons; the long sweep explicitly limits output to 64 tokens, so hitting that limit is deliberate truncation for measurement, not a complete answer. Client time includes retries and waits. Do not turn input count divided by its duration into uncached prefill when the reused-token counter is unavailable.
"""Ollama local: mediciones reales y JSON emparejado; no publica ni envía datos fuera del host."""
import json
import math
import random
import statistics
import subprocess
import time
import tempfile
from datetime import datetime, timezone
from pathlib import Path
import jsonschema
import requests
def project_root():
starts = [Path.cwd().resolve()]
if "__file__" in globals():
starts.append(Path(__file__).resolve().parent)
for start in starts:
for candidate in (start, *start.parents):
if (candidate / "src/content/modules/p05-agente-rag-local.json").is_file():
return candidate
raise RuntimeError("No se encuentra la raíz del proyecto desde este directorio.")
OUTPUT_BASE = project_root() / "labs" / "runs" / "p05-l01"
OUTPUT_BASE.mkdir(parents=True, exist_ok=True)
ROOT = Path(tempfile.mkdtemp(prefix="ejecucion-", dir=str(OUTPUT_BASE)))
print("Datos de esta ejecución:", ROOT, flush=True)
BASE = "http://127.0.0.1:11434"
MODEL = "phi3:mini"
TIMEOUT = (5, 180)
RETRIES = 3
KEEP_ALIVE = "15s"
SCHEMA = {
"type": "object",
"properties": {"status": {"type": "string", "enum": ["open", "closed"]},
"priority": {"type": "integer", "minimum": 1, "maximum": 3}},
"required": ["status", "priority"],
"additionalProperties": False,
}
jsonschema.Draft202012Validator.check_schema(SCHEMA)
VALIDATOR = jsonschema.Draft202012Validator(SCHEMA)
SESSION = requests.Session()
LOG = ROOT / "peticiones.jsonl"
SUMMARY = ROOT / "resultados.json"
def now():
return datetime.now(timezone.utc).isoformat()
def append(record):
with LOG.open("a", encoding="utf-8") as f:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
def get(path):
response = SESSION.get(BASE + path, timeout=TIMEOUT)
response.raise_for_status()
return response.json()
def gpu_snapshot():
try:
p = subprocess.run(["nvidia-smi", "--query-gpu=memory.used,memory.total,utilization.gpu",
"--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=10)
if p.returncode != 0:
return {"error": p.stderr.strip(), "returncode": p.returncode}
return {"raw": p.stdout.strip(), "unit": "MiB, MiB, percent"}
except (OSError, subprocess.TimeoutExpired) as exc:
return {"error": repr(exc)}
def ps_snapshot():
try:
return get("/api/ps")
except (requests.RequestException, ValueError) as exc:
return {"error": repr(exc)}
def chat(messages, *, options, schema=None, kind, case):
"""Cliente propio: tiempo límite, reintentos acotados y registro de cada intento."""
body = {"model": MODEL, "messages": messages, "stream": False,
"truncate": False, "shift": False,
"options": options, "keep_alive": KEEP_ALIVE}
if schema is not None:
body["format"] = schema
attempts = []
overall_start = time.perf_counter()
for attempt in range(1, RETRIES + 1):
start = time.perf_counter()
try:
response = SESSION.post(BASE + "/api/chat", json=body, timeout=TIMEOUT)
elapsed = time.perf_counter() - start
if not response.ok:
error = f"HTTP {response.status_code}: {response.text[:3000]}"
attempts.append({"attempt": attempt, "seconds": elapsed, "error": error})
oom = any(term in error.lower() for term in ("out of memory", "out-of-memory", "cuda_error_out_of_memory"))
retry = response.status_code in (408, 429) or response.status_code >= 500
if retry and attempt < RETRIES:
time.sleep(90 if oom else min(2 ** attempt, 8))
continue
break
result = response.json()
attempts.append({"attempt": attempt, "seconds": elapsed, "status": response.status_code})
record = {"utc": now(), "kind": kind, "case": case, "request": body,
"attempts": attempts, "response": result, "ok": True,
"elapsed_including_backoff": time.perf_counter() - overall_start}
append(record)
return record
except (requests.RequestException, ValueError) as exc:
attempts.append({"attempt": attempt, "seconds": time.perf_counter() - start, "error": repr(exc)})
if attempt < RETRIES:
time.sleep(min(2 ** attempt, 8))
record = {"utc": now(), "kind": kind, "case": case, "request": body,
"attempts": attempts, "response": None, "ok": False,
"elapsed_including_backoff": time.perf_counter() - overall_start}
append(record)
return record
def strict_load(text):
def pairs(items):
result = {}
for key, value in items:
if key in result:
raise ValueError("clave duplicada: " + key)
result[key] = value
return result
def bad_constant(value):
raise ValueError("constante JSON no permitida: " + value)
return json.loads(text, object_pairs_hook=pairs, parse_constant=bad_constant)
def validate(record, expected):
if not record["ok"]:
return {"json_valid": False, "schema_valid": False, "semantic_match": False,
"truncated": None, "error": "petición fallida"}
response = record["response"]
content = response.get("message", {}).get("content", "")
reason = response.get("done_reason")
result = {"json_valid": False, "schema_valid": False, "semantic_match": False,
"truncated": None if reason is None else reason == "length", "error": None}
try:
obj = strict_load(content)
result["json_valid"] = True
errors = sorted(VALIDATOR.iter_errors(obj), key=lambda e: str(list(e.absolute_path)))
if errors:
result["error"] = "; ".join(e.message for e in errors)
else:
result["schema_valid"] = True
result["semantic_match"] = obj == expected
if not result["semantic_match"]:
result["error"] = "estructura válida, valores distintos de la ficha"
except (ValueError, TypeError) as exc:
result["error"] = repr(exc)
return result
def rates(record):
if not record["ok"]:
return None
response = record["response"]
def per_second(count, duration):
return count * 1e9 / duration if isinstance(count, int) and isinstance(duration, int) and duration > 0 else None
count = response.get("prompt_eval_count")
cached = response.get("prompt_eval_cached_count")
measured = count - cached if isinstance(count, int) and isinstance(cached, int) and 0 <= cached <= count else None
return {"prompt_tokens": count,
"prompt_cached_tokens": cached,
"prefill_uncached_tokens_per_second": per_second(measured, response.get("prompt_eval_duration")),
"reported_prompt_count_over_eval_duration": per_second(count, response.get("prompt_eval_duration")),
"output_tokens": response.get("eval_count"),
"decode_tokens_per_second": per_second(response.get("eval_count"), response.get("eval_duration")),
"done_reason": response.get("done_reason"),
"attempt_seconds_sum": sum(a["seconds"] for a in record["attempts"]),
"end_to_end_seconds": record["elapsed_including_backoff"]}
def main():
if LOG.exists() or SUMMARY.exists():
raise RuntimeError("La salida ya existe. Conserva el registro anterior antes de ejecutar otra bateria.")
status = get("/api/ps")
resident_before = any(m.get("name") == MODEL for m in status.get("models", []))
tags = get("/api/tags")
model = next(m for m in tags["models"] if m["name"] == MODEL)
show_response = SESSION.post(BASE + "/api/show", json={"model": MODEL}, timeout=TIMEOUT)
show_response.raise_for_status()
show = show_response.json()
info = show["model_info"]
assert show["details"]["format"] == "gguf" and show["details"]["quantization_level"] == "Q4_0"
assert "MIT License" in show["license"]
meta = {"utc": now(), "server": BASE, "version": get("/api/version"), "tag": model,
"details": show["details"], "license": "MIT", "template": show.get("template"),
"capabilities": show.get("capabilities"),
"model_info": {k: v for k, v in info.items() if k.startswith("phi3.") or k in ("general.parameter_count", "general.license")},
"resident_before": resident_before, "ps_before": status, "gpu_before": gpu_snapshot(),
"schema": SCHEMA, "schema_repetitions_per_condition": 200}
append({"kind": "metadata", **meta})
print("Metadatos:", json.dumps(meta, ensure_ascii=False), flush=True)
# Entrada distinta por ensayo, sin afirmar cuántos tokens son antes de medirlos.
bench = []
for ctx in (1024, 2048, 4096):
for batch in (32, 128, 512):
chat([{"role": "user", "content": "Warm up. Say ready."}],
options={"temperature": 0, "seed": 17, "num_ctx": ctx,
"num_batch": batch, "num_predict": 16},
kind="warmup", case=f"ctx{ctx}-batch{batch}")
for blocks in (3, 12, 30):
for repeat in range(2):
key = f"ctx{ctx}-bloques{blocks}-batch{batch}-rep{repeat}"
rng = random.Random(f"atlas-p05-{key}")
text = " ".join(f"Record {j} has value {rng.randrange(100000, 999999)} and is ready."
for j in range(blocks))
messages = [{"role": "system", "content": "Answer briefly and accurately."},
{"role": "user", "content": f"Run {key}. Read the following data, then say ready: {text}"}]
options = {"temperature": 0, "seed": 17, "num_ctx": ctx,
"num_batch": batch, "num_predict": 16}
record = chat(messages, options=options, kind="benchmark", case=key)
row = {"case": key, "num_ctx": ctx, "blocks": blocks, "num_batch": batch,
"repeat": repeat, "rates": rates(record), "ok": record["ok"],
"ps": ps_snapshot(), "gpu": gpu_snapshot()}
bench.append(row)
append({"kind": "benchmark_observation", **row})
print("Benchmark", key, json.dumps(row["rates"]), flush=True)
# Mismas 200 fichas en cada condición; alternar el orden de cada pareja.
chat([{"role": "user", "content": "Warm up. Say ready."}],
options={"temperature": 0, "seed": 17, "num_ctx": 1024,
"num_batch": 128, "num_predict": 16},
kind="warmup", case="structured")
evaluations = []
for i in range(200):
expected = {"status": "open" if i % 2 == 0 else "closed", "priority": (i % 3) + 1}
messages = [
{"role": "system", "content": "Return exactly one JSON object, without markdown or commentary."},
{"role": "user", "content": f"Extract the values in this record: id={i:03d}, status={expected['status']}, priority={expected['priority']}. Return an object with exactly status and priority, using the same values."},
]
for condition in (("free", "schema") if (i // 2) % 2 == 0 else ("schema", "free")):
record = chat(messages, options={"temperature": 0, "seed": 17, "num_ctx": 1024,
"num_batch": 128, "num_predict": 64},
schema=SCHEMA if condition == "schema" else None,
kind="structured", case=f"{i:03d}-{condition}")
check = validate(record, expected)
content = record["response"].get("message", {}).get("content", "") if record["ok"] else ""
content = content if isinstance(content, str) else ""
item = {"index": i, "condition": condition, "expected": expected,
"starts_markdown_fence": content.lstrip().startswith(chr(96) * 3),
"ok": record["ok"], "validation": check, "rates": rates(record)}
evaluations.append(item)
append({"kind": "validation", **item})
if (i + 1) % 20 == 0:
print("Pares completados:", i + 1, "/ 200", flush=True)
# La batería complementaria se inicia tras la expiración natural de la anterior.
# Nunca se fuerza la descarga si otro cliente mantiene el modelo ocupado.
for _ in range(20):
try:
active_models = get("/api/ps").get("models", [])
except (requests.RequestException, ValueError):
break
if not any(m.get("name") == MODEL for m in active_models):
print("Modelo no residente antes del barrido largo.", flush=True)
break
time.sleep(1)
else:
print("El modelo sigue residente; no se fuerza su descarga.", flush=True)
# Barrido complementario largo: misma API, contexto real 4096 y hasta 64 tokens de salida.
long_bench = []
for batch in (128, 512):
chat([{"role": "user", "content": "Warm up. Say ready."}],
options={"temperature": 0, "seed": 17, "num_ctx": 4096,
"num_batch": batch, "num_predict": 16},
kind="warmup", case=f"long-batch{batch}")
for blocks in (55, 115, 175):
for repeat in range(2):
key = f"largo-ctx4096-bloques{blocks}-batch{batch}-rep{repeat}"
rng = random.Random(f"atlas-p05-{key}")
text = " ".join(f"Record {j} has value {rng.randrange(100000, 999999)} and is ready."
for j in range(blocks))
messages = [
{"role": "system", "content": "Write a detailed response in clear English."},
{"role": "user", "content": f"Run {key}. Read these records and write a detailed report of at least 300 words describing how to audit their consistency: {text}"}
]
record = chat(messages, options={"temperature": 0, "seed": 17, "num_ctx": 4096,
"num_batch": batch, "num_predict": 64},
kind="benchmark_largo", case=key)
row = {"case": key, "num_ctx": 4096, "blocks": blocks, "num_batch": batch,
"repeat": repeat, "ok": record["ok"], "rates": rates(record),
"ps": ps_snapshot(), "gpu": gpu_snapshot()}
long_bench.append(row)
append({"kind": "benchmark_largo_observation", **row})
print("Benchmark largo", key, json.dumps(row["rates"]), flush=True)
long_table = []
for batch in (128, 512):
for blocks in (55, 115, 175):
group = [r for r in long_bench if r["num_batch"] == batch and r["blocks"] == blocks and r["rates"]]
def long_median(field):
values = [r["rates"][field] for r in group if r["rates"].get(field) is not None]
return statistics.median(values) if values else None
long_table.append({"num_ctx": 4096, "blocks": blocks, "num_batch": batch,
"successful_repetitions": len(group),
"prompt_tokens_reported": [r["rates"]["prompt_tokens"] for r in group],
"output_tokens": [r["rates"]["output_tokens"] for r in group],
"done_reason": [r["rates"]["done_reason"] for r in group],
"median_uncached_prefill_tokens_per_second": long_median("prefill_uncached_tokens_per_second"),
"median_reported_prompt_count_over_eval_duration": long_median("reported_prompt_count_over_eval_duration"),
"median_decode_tokens_per_second": long_median("decode_tokens_per_second")})
totals = {}
for condition in ("free", "schema"):
group = [x for x in evaluations if x["condition"] == condition]
def condition_median(field):
values = [x["rates"][field] for x in group
if x["rates"] and x["rates"].get(field) is not None]
return statistics.median(values) if values else None
totals[condition] = {"denominator": len(group), "request_failures": sum(not x["ok"] for x in group),
"valid_json": sum(x["validation"]["json_valid"] for x in group),
"valid_schema": sum(x["validation"]["schema_valid"] for x in group),
"accepted_schema": sum(x["validation"]["schema_valid"] and x["validation"]["truncated"] is False for x in group),
"semantic_matches": sum(x["validation"]["semantic_match"] for x in group),
"starts_markdown_fence": sum(x["starts_markdown_fence"] for x in group),
"truncated": sum(x["validation"]["truncated"] is True for x in group),
"median_end_to_end_seconds_successful": condition_median("end_to_end_seconds"),
"median_decode_tokens_per_second_successful": condition_median("decode_tokens_per_second"),
"median_output_tokens_successful": condition_median("output_tokens")}
# Estimación, no medición: KV FP16 y todos los pesos del tag en GPU.
layers = info["phi3.block_count"]
n_heads = info["phi3.attention.head_count"]
n_kv = info["phi3.attention.head_count_kv"]
head_dim = info["phi3.embedding_length"] // n_heads
budgets = []
for ctx in (1024, 2048, 4096):
rows = [r for r in bench if r["num_ctx"] == ctx and r["ok"]]
for row in rows:
active = next((m for m in row["ps"].get("models", []) if m.get("name") == MODEL), None)
if active and active.get("size_vram"):
actual_ctx = active.get("context_length")
if not isinstance(actual_ctx, int) or actual_ctx <= 0:
continue
kv = 2 * layers * n_kv * head_dim * actual_ctx * 2
estimated = model["size"] + kv
observed = active["size_vram"]
budgets.append({"case": row["case"], "context_reported": active.get("context_length"),
"tag_bytes": model["size"], "kv_fp16_hypothesis_bytes": kv,
"estimate_bytes": estimated, "size_vram_reported_bytes": observed,
"relative_difference_vs_reported": abs(estimated - observed) / observed})
table = []
for ctx in (1024, 2048, 4096):
for blocks in (3, 12, 30):
for batch in (32, 128, 512):
group = [r for r in bench if r["num_ctx"] == ctx and r["blocks"] == blocks and r["num_batch"] == batch and r["rates"]]
def median(field):
values = [r["rates"][field] for r in group if r["rates"].get(field) is not None]
return statistics.median(values) if values else None
table.append({"num_ctx": ctx, "blocks": blocks, "num_batch": batch, "successful_repetitions": len(group),
"prompt_tokens_reported": [r["rates"]["prompt_tokens"] for r in group],
"median_uncached_prefill_tokens_per_second": median("prefill_uncached_tokens_per_second"),
"median_reported_prompt_count_over_eval_duration": median("reported_prompt_count_over_eval_duration"),
"median_decode_tokens_per_second": median("decode_tokens_per_second")})
result = {"metadata": meta, "benchmark": bench, "benchmark_table": table, "long_benchmark": long_bench,
"long_benchmark_table": long_table, "structured_totals": totals,
"structured_evaluations": evaluations, "budget": budgets,
"budget_note": "Hipótesis: KV FP16, un solo contexto y todos los bytes del tag en GPU. No incluye buffers, metadatos ni otras asignaciones; size_vram es lo que informa /api/ps.",
"prefill_note": "Contadores y tiempos nativos de Ollama. Si el servidor no informa tokens cacheados, no podemos corregir el numerador de prefill; no extrapolar.",
"paired_note": "Las dos condiciones reciben cada ficha y el mismo mensaje. El orden alterna. JSON válido no implica respuesta semánticamente correcta."}
SUMMARY.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
print("Totales:", json.dumps(totals), flush=True)
free_latency = totals["free"]["median_end_to_end_seconds_successful"]
schema_latency = totals["schema"]["median_end_to_end_seconds_successful"]
print("Cociente de medianas de latencia restringida/libre:",
schema_latency / free_latency if free_latency and schema_latency is not None else None, flush=True)
print("Tabla larga: contexto | lote | tokens entrada | tokens salida | parada | prefill sin caché | contador/duración | decode", flush=True)
for row in long_table:
print(row["num_ctx"], row["num_batch"], row["prompt_tokens_reported"], row["output_tokens"],
row["done_reason"], row["median_uncached_prefill_tokens_per_second"],
row["median_reported_prompt_count_over_eval_duration"], row["median_decode_tokens_per_second"], flush=True)
for ctx in (1024, 2048, 4096):
values = [x["relative_difference_vs_reported"] for x in budgets if x["case"].startswith(f"ctx{ctx}-")]
print("Contexto", ctx, "diferencia relativa minima/maxima con /api/ps:",
(min(values), max(values)) if values else "sin medición", flush=True)
try:
main()
finally:
SESSION.close()
# Todas las peticiones usaron una vida corta; nunca se fuerza la descarga de
# un modelo que pueda estar atendiendo otra petición. Comprobar expiración natural.
for _ in range(20):
try:
running = requests.get(BASE + "/api/ps", timeout=5).json().get("models", [])
except (requests.RequestException, ValueError):
break
if not any(m.get("name") == MODEL for m in running):
print("Modelo no residente tras expiración natural.", flush=True)
break
time.sleep(1)
else:
print("El modelo sigue residente; no se fuerza su descarga para no interrumpir terceros.", flush=True)npm run lab and open the connection link.In a review run with Ollama 0.17.7 and the tag whose digest begins 4f2222927938, all 200 constrained answers satisfied the schema and card values. All 200 free answers failed strict parsing: all began with a Markdown fence, and 13 reached the output limit. No request in that battery failed due to transport. This result describes that narrow extraction battery, not the reliability of every schema or task. Removing fences before parsing would be a different client policy and would need to be evaluated and logged as such.
The cost comparison also needs context: in that run median output length was 31 tokens for the free condition and 21 for the constrained condition. Since they generated different amounts of text, their latency ratio does not isolate per-token grammar cost. There were no retries in that run. The cell prints median end-to-end latency and tokens per second and retains every observation to study variability and repeat the comparison with controlled tasks and lengths.
For memory, the full-file-on-GPU plus FP16 KV assumption came within 10% of Ollama-reported VRAM in the 1024 and 4096 context observations of that run. In a measurement split between devices, the server reported less VRAM than total model memory and the difference exceeded that margin: the full-GPU-residency assumption does not hold there. The cause of the split is not known from those counters. size_vram is server-reported attribution, not an independent measurement of physical consumption; saved nvidia-smi readings are for the whole device and other processes can alter the baseline. A new run may have a different distribution if available memory changes; inspect size, size_vram, and context before deciding whether comparison is appropriate.
The observed long sweep reported 995, 2031, and 3111 input tokens with reserved context 4096. Its outputs hit the fixed 64-token limit. The server version did not return a cached-prefix token counter, so reused prefill work cannot be separated exactly. The API metric definition in version 0.17.7 does not include that counter either, and the runner in that version reuses cache state for generation. This is a limitation of this measurement, not a claim about all versions and servers. Diagnostic rates in the table do not justify extrapolation to other lengths, versions, or loads.
Exercises
def chat(send, messages, schema=None, attempts=3, timeout=5):
passThe budget determines whether the service can start; separate measurements show how it behaves under a particular load; and the grammar establishes a format contract. Factual correctness and action authorization need additional checks.