Operational review: the language model as a policy and local inference
Review decoder-only LLMs as stochastic policies over continuations. Build a local Transformers and quantized GGUF inference stack, budget VRAM, and construct a reproducible call harness with caching, logging, and token accounting.
After this lesson you can
- Write the probability of a complete answer as a product of conditionals and compute its log likelihood from logits.
- Explain how temperature, top-p, and seed define stochastic policy π(y | x), and why temperature 0 does not guarantee GPU determinism.
- Budget weight and KV-cache VRAM to select a model, quantization, and context length that fit in 8 GB.
- Build a call harness with chat template, hash-based disk cache, JSONL logging, and token, latency, and FLOP accounting.
- Compare the same task using Transformers and llama.cpp and explain output, memory, and speed differences.
Before you start
A call is an experiment
An agent querying a model does not call a fixed mathematical function that always returns the same answer. Output depends on a distribution, transformations applied to its logits, and execution decisions. Comparing reasoning strategies requires knowing what was generated, under which configuration, and at what cost. Causal factorization supplies the distribution; sampling and a harness turn it into a measurable call.
For next-token logits , . Subtracting the maximum before exponentiation prevents overflow without changing the result. Indexing matters: logits at the last prompt position predict the first generated token. Logits at a generated token predict the next one, not that token itself.
With , we obtain . The maximum shifted exponent is zero, so none exceeds one. This identity also explains why adding the same constant to every logit leaves the distribution unchanged. In the cell, the second row predicts the second token and the sum of both log probabilities corresponds to the joint continuation.
import numpy as np
logits = np.array([[2.0, 1.0, 0.0], [0.0, 2.0, 1.0]])
tokens = np.array([0, 2])
maximos = logits.max(axis=1, keepdims=True)
log_norm = maximos[:, 0] + np.log(np.exp(logits - maximos).sum(axis=1))
por_token = logits[np.arange(len(tokens)), tokens] - log_norm
print("por token:", np.round(por_token, 6))
print("total:", round(float(por_token.sum()), 6))
print("media:", round(float(por_token.mean()), 6))The policy being sampled
With temperature , next-token mass is proportional to . Lowering it emphasizes logit differences and raising it flattens the distribution. Top-k discards all but the largest logits; top-p retains the smallest ordered prefix whose cumulative mass reaches , then renormalizes. The exact ordering of logit processors is part of the generation policy definition.
For example, if two logits differ by , their probability ratio after temperature is . Reducing increases that ratio for . Exactly zero temperature is not evaluated by division by zero: it normally denotes greedy decoding. Exact ties also require a tie rule. Top-p does not always retain the same token count and must include the token reaching the threshold; after discarding the rest, retained probabilities are divided by their total mass.
Probability under the truncated policy need not equal probability under the untruncated model. When comparing sequences by log likelihood, record which is used. A seed reproduces a pseudorandom sequence under compatible execution conditions; it does not fix floating-point operations dependent on device, batch size, or implementation. Greedy decoding has no sampling, but nearly tied logits may change order when those conditions change.
In Transformers, the generation configuration may inherit checkpoint values. Also inspect filters and penalties not explicitly passed. Fixing seed, versions, device, and batch reduces variation; the PyTorch reproducibility guide explains why it does not guarantee identity across versions or platforms. Deterministic operations may impose costs or be unavailable in some cases.
The figure’s model is checkpoint Qwen/Qwen2.5-0.5B-Instruct, revision 7ae557604adf67be50417f59c2c2f167def9a775. Logits were extracted using Transformers in bf16 on the local GPU: the top five after the prompt and after adding each of those five tokens. The words “fin” and “salto” represent the special end token and line breaks respectively. The following code repeats extraction; values and order may vary slightly with device or version. The goal is not to measure accuracy on one question, but to observe how the policy is composed.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
modelo_id = "Qwen/Qwen2.5-0.5B-Instruct"
revision = "7ae557604adf67be50417f59c2c2f167def9a775"
tokenizador = AutoTokenizer.from_pretrained(modelo_id, revision=revision)
modelo = AutoModelForCausalLM.from_pretrained(modelo_id, revision=revision, dtype=torch.bfloat16).to("cuda").eval()
mensajes = [{"role": "user", "content": "What is 2 + 2? Answer with one number."}]
entrada = tokenizador.apply_chat_template(mensajes, add_generation_prompt=True, return_tensors="pt")["input_ids"].to("cuda")
def cinco(ids):
with torch.inference_mode():
logits = modelo(ids).logits[0, -1].float()
valores, indices = logits.topk(5)
return [(int(i), tokenizador.decode([int(i)]), float(v)) for v, i in zip(valores, indices)]
primero = cinco(entrada)
print("primer nodo:", primero)
for indice, texto, _ in primero:
siguiente = torch.cat([entrada, torch.tensor([[indice]], device=entrada.device)], dim=1)
print("tras", repr(texto), cinco(siguiente))
del modelo
torch.cuda.empty_cache()npm run lab and open the connection link.Messages and tokens
The chat template turns a list of messages and roles into the sequence received by the model. It may insert delimiters, end markers, and an assistant prefix to start generation. It is part of the checkpoint contract, not a universal format. Apply the template supplied with the tokenizer and inspect its IDs and serialized text; do not duplicate special tokens when tokenizing an already formatted string. The Transformers documentation explains both routes and their conditions.
A tool response is data from an external source. Role and delimiters help the model identify the format, but alone do not form a security boundary. Tool authorization must live outside the model.
Memory before loading
The local inference stack can use Transformers with bf16 weights or an engine such as llama.cpp with a quantized GGUF file. GGUF is a container; a quantization label does not mean each parameter consumes exactly four or eight bits. Headers, scales, unquantized tensors, and additional structures also occupy memory.
A GGUF catalog includes, for example, Q8_0 and Q4_K_M. These are representation and tensor-type mixture choices, not promises that the entire file weighs exactly eight or four bits per parameter. The practice file Q4_K_M is 491400032 bytes on disk; loading also requires memory for context and buffers. The figure’s 8.5- and 4.5-bit selector is an adjustable calculation model, not measured sizes for those formats. Check the actual file and measure process memory.
With parameters and effective bits per parameter, ideal weights occupy bytes. For a KV cache with layers, key and value heads, dimension , tokens, sequences, and bytes per element, the budget excluding metadata is
The factor two counts keys and values. The formula assumes all layers store all positions without paging or sliding windows, and each sequence has an independent cache. Prefix sharing or cache quantization changes actual cost. Temporary activations, CUDA context, fragmentation, and other applications require headroom. GB in this lesson means bytes; GiB means bytes.
To choose a starting point, consult the specific checkpoint’s model card. Qwen2.5-1.5B-Instruct states 1.54 billion parameters, 28 layers, and two KV heads. Assuming dimension 128 and fp16 KV, one 8192-token sequence needs 3.08 GB of ideal bf16 weights and about 0.235 GB KV; with assumed 1 GB headroom, the ideal total is 4.315 GB. This is a budget, not a measured allocation or fit guarantee. The card for Qwen3-0.6B states 28 layers and eight KV heads: counting parameters alone would hide that difference. Llama 3.2 1B states 1.23 billion parameters and a large nominal context; that model limit also does not guarantee the corresponding cache fits an 8 GB GPU. Verify access and license, exact format, head dimension, and execution configuration before loading any checkpoint.
Quantization can allow more weights to load but does not itself determine speed. Prefill processes the prompt and decoding produces successive tokens; measure their times separately when the backend permits. Tokens per second depends on hardware, length, batch, configuration, and synchronization. A dense-multiplication FLOP estimate can compare budgets but does not replace latency measurement or automatically include attention, sampling, or memory movement.
This phase difference affects comparison design. Prefill can exploit operations across several prompt tokens; during autoregressive decoding each token depends on predecessors and cache avoids recomputing their keys and values. Larger batches can share some operations but increase memory and potential waiting. Speed measured while generating a two-token answer includes fixed costs that may dominate; report token count, call count, and whether the model was already loaded.
With 7 billion parameters and 4.5 effective bits, estimated weights occupy GB. If the hypothetical model has 32 layers, eight KV heads of dimension 128, context 8192, and one fp16 sequence, the formula adds approximately 1.074 GB. With hypothetical 1 GB headroom the total is about 6.011 GB. Doubling sequences doubles cache in this formula, not weights; actual memory depends on implementation. A budget roomy for one sample may not remain so when sampling several in parallel.
Experimental contract
A call harness receives messages, model, template, parameters, and seed, and returns text, IDs, available log probabilities, and counters. The cache key must identify exact content and model and tokenizer versions, along with template, messages, parameters, and seed. Serializing JSON with sorted keys before hashing makes argument order irrelevant to the key; it does not make omitted parameters equivalent to changing defaults.
Token and cost accounting distinguishes input and output tokens, load time, prefill and generation, cache hits, and peak memory. One JSONL record per call links configuration and result. Do not mix cached responses with fresh inference when computing speed: record both cases.
The following harness uses a batch of one sequence and saves practice responses in llm_cache. Each call also logs one JSON line to calls.jsonl; both files may contain private messages, so store them appropriately. Measured latency includes the full generation call and does not separate prefill from decoding. Log probabilities use raw logits returned by generate, not the distribution after temperature and top-p. The interface excludes load time from the call. Its key includes library version and device type but does not claim reproducibility across machines or kernels. This is a sequential research harness: concurrent calls would need independent generators and atomic, coordinated cache and log writes.
import hashlib, json, time
from pathlib import Path
import torch
import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer
class LLM:
def __init__(self, model_id, revision, cache_dir="llm_cache"):
self.model_id, self.revision = model_id, revision
self.tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
self.model = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, dtype=torch.bfloat16).to("cuda").eval()
self.parameters = sum(p.numel() for p in self.model.parameters())
self.cache = Path(cache_dir)
self.cache.mkdir(parents=True, exist_ok=True)
def chat(self, messages, seed=0, temperature=0.7, top_p=0.9, max_new_tokens=32, use_cache=True):
if temperature < 0 or not 0 < top_p <= 1 or max_new_tokens < 1:
raise ValueError("Parámetros de muestreo inválidos")
config = {"harness_version": 3, "model": self.model_id, "revision": self.revision,
"template": self.tokenizer.chat_template, "messages": messages,
"seed": seed, "temperature": temperature, "top_p": top_p,
"max_new_tokens": max_new_tokens, "top_k": 0, "repetition_penalty": 1.1, "batch_size": 1,
"torch": torch.__version__, "transformers": transformers.__version__,
"device": torch.cuda.get_device_name()}
canonical = json.dumps(config, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
key = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
path = self.cache / (key + ".json")
cached = use_cache and path.exists()
if cached:
result = json.loads(path.read_text(encoding="utf-8"))
else:
encoded = self.tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to("cuda")
torch.manual_seed(seed)
kwargs = {"max_new_tokens": max_new_tokens, "do_sample": temperature > 0,
"return_dict_in_generate": True, "output_logits": True, "repetition_penalty": 1.1,
"pad_token_id": self.tokenizer.eos_token_id}
if temperature > 0:
kwargs.update(temperature=temperature, top_p=top_p, top_k=0)
torch.cuda.synchronize()
start = time.perf_counter()
with torch.inference_mode():
out = self.model.generate(**encoded, **kwargs)
torch.cuda.synchronize()
elapsed = time.perf_counter() - start
n_in = encoded["input_ids"].shape[1]
generated = out.sequences[0, n_in:]
logprobs = [float(torch.log_softmax(z[0].float(), dim=-1)[token]) for z, token in zip(out.logits, generated)]
result = {"text": self.tokenizer.decode(generated, skip_special_tokens=True),
"token_ids": generated.tolist(), "raw_logprobs": logprobs,
"input_tokens": n_in, "output_tokens": len(generated), "seconds": elapsed,
"approx_dense_flops": 2 * self.parameters * (n_in + len(generated) - 1)}
path.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
event = {"key": key, "cached": cached, "config": config, "result": result}
with (self.cache / "calls.jsonl").open("a", encoding="utf-8") as log:
log.write(json.dumps(event, ensure_ascii=False) + chr(10))
return result
llm = LLM(modelo_id, revision)
pregunta = [{"role": "user", "content": "What is 2 + 2? Answer with one number."}]
a = llm.chat(pregunta, seed=3, use_cache=False)
b = llm.chat(pregunta, seed=3, use_cache=False)
print("Igualdad de IDs en dos ejecuciones:", a["token_ids"] == b["token_ids"])
print("Tokens de entrada y salida:", a["input_tokens"], a["output_tokens"])
print("Texto:", repr(a["text"]))
print("Log-probabilidades del modelo:", a["raw_logprobs"])
print("FLOPs densos aproximados:", a["approx_dense_flops"])npm run lab and open the connection link.The equality printed by this run applies only to those two calls with identical batch and environment. To study batch-size drift, prepare identical prompt copies, fix the seed, and compare IDs with a single call; correspondence of draws can change when generating multiple sequences even without numerical differences. To isolate logit effects, compare greedy decoding first, then study sampling with documented generators and seeds.
encoded = llm.tokenizer.apply_chat_template(pregunta, add_generation_prompt=True, return_tensors="pt").to("cuda")
batch = {k: v.repeat(2, 1) for k, v in encoded.items()}
with torch.inference_mode():
uno = llm.model.generate(**encoded, max_new_tokens=16, do_sample=False, pad_token_id=llm.tokenizer.eos_token_id)
dos = llm.model.generate(**batch, max_new_tokens=16, do_sample=False, pad_token_id=llm.tokenizer.eos_token_id)
longitud_prompt = encoded["input_ids"].shape[1]
print("IDs individuales:", uno[0, longitud_prompt:].tolist())
print("IDs en lote:", [fila[longitud_prompt:].tolist() for fila in dos])
print("Iguales en esta prueba:", all(torch.equal(uno[0], fila) for fila in dos))
# Vuelve a puntuar los tokens de la primera llamada con teacher forcing.
continuacion = torch.tensor([a["token_ids"]], device="cuda")
completa = torch.cat([encoded["input_ids"], continuacion], dim=1)
with torch.inference_mode():
logits_completos = llm.model(completa).logits[0].float()
filas = logits_completos[longitud_prompt - 1:completa.shape[1] - 1]
recalculadas = torch.log_softmax(filas, dim=-1).gather(1, continuacion.T).squeeze(1)
print("Puntuaciones teacher forcing:", recalculadas.tolist())
print("Coinciden con generate a tolerancia bf16:", torch.allclose(recalculadas.cpu(), torch.tensor(a["raw_logprobs"]), atol=0.02, rtol=0))npm run lab and open the connection link.A match here does not establish universal determinism: this input, version, GPU, and batch size are one case. For sampling, running each sequence with an independent generator and explicit seed helps separate random-number consumption from numerical batch effects, provided the backend supports that contract.
The same contract on GGUF
The following adapter uses official Qwen GGUF and the template in its metadata. Install llama-cpp-python, huggingface-hub, and psutil in your local environment. This run uses four CPU threads and no GPU layers: do not compare its latency with bf16 GPU execution as though only the engine changed. The implementation returns text, counts, and time through the same chat interface; score details may differ across backends and must not be mixed without verifying their definitions.
import hashlib, json, time
from pathlib import Path
from huggingface_hub import hf_hub_download
import llama_cpp
import psutil
from llama_cpp import Llama
class LLMGGUF:
def __init__(self, filename, revision, cache_dir="llm_cache_gguf"):
self.path = hf_hub_download("Qwen/Qwen2.5-0.5B-Instruct-GGUF", filename, revision=revision)
self.revision = revision
with open(self.path, "rb") as file:
self.sha = hashlib.file_digest(file, "sha256").hexdigest()
self.file_bytes = Path(self.path).stat().st_size
rss_before = psutil.Process().memory_info().rss
self.model = Llama(model_path=self.path, n_ctx=2048, n_gpu_layers=0,
n_threads=4, n_threads_batch=4, logits_all=True, verbose=False)
self.rss_delta_load = psutil.Process().memory_info().rss - rss_before
self.template = self.model.metadata.get("tokenizer.chat_template", "")
self.cache = Path(cache_dir)
self.cache.mkdir(parents=True, exist_ok=True)
def chat(self, messages, seed=0, temperature=0.7, top_p=0.9, max_new_tokens=32, use_cache=True):
if temperature < 0 or not 0 < top_p <= 1 or max_new_tokens < 1:
raise ValueError("Parámetros de muestreo inválidos")
config = {"harness_version": 3, "sha256": self.sha, "revision": self.revision, "template": self.template,
"messages": messages, "seed": seed, "temperature": temperature,
"top_p": top_p, "max_new_tokens": max_new_tokens,
"llama_cpp": llama_cpp.__version__, "n_ctx": 2048, "n_threads": 4,
"n_gpu_layers": 0, "top_k": 0, "min_p": 0, "repeat_penalty": 1.1}
canonical = json.dumps(config, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
key = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
path = self.cache / (key + ".json")
cached = use_cache and path.exists()
if cached:
result = json.loads(path.read_text(encoding="utf-8"))
else:
start = time.perf_counter()
output = self.model.create_chat_completion(messages=messages, seed=seed,
temperature=temperature, top_p=top_p, top_k=0, min_p=0, repeat_penalty=1.1,
max_tokens=max_new_tokens, logprobs=True, top_logprobs=1)
elapsed = time.perf_counter() - start
choice = output["choices"][0]
scores = choice.get("logprobs") or {}
result = {"text": choice["message"]["content"], "token_ids": None,
"raw_logprobs": [float(x["logprob"]) for x in scores.get("content", [])],
"input_tokens": output["usage"]["prompt_tokens"],
"output_tokens": output["usage"]["completion_tokens"], "seconds": elapsed}
path.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
with (self.cache / "calls.jsonl").open("a", encoding="utf-8") as log:
log.write(json.dumps({"key": key, "cached": cached, "config": config, "result": result}, ensure_ascii=False) + chr(10))
return result
gguf = LLMGGUF("qwen2.5-0.5b-instruct-q4_k_m.gguf", "9217f5db79a29953eb74d5343926648285ec7e67")
respuesta_gguf = gguf.chat(pregunta, temperature=0, max_new_tokens=16, use_cache=False)
print("Texto GGUF:", repr(respuesta_gguf["text"]))
print("Tokens de entrada y salida:", respuesta_gguf["input_tokens"], respuesta_gguf["output_tokens"])
print("Log-probabilidades disponibles:", respuesta_gguf["raw_logprobs"])
print("Archivo GGUF (bytes) y variación RSS al cargar:", gguf.file_bytes, gguf.rss_delta_load)npm run lab and open the connection link.The chat interface used here does not return output IDs: the adapter marks token_ids as None instead of reconstructing them from text. llama.cpp’s output count may exclude the special stop token Transformers includes in its generated sequence. Exact ID and stop-rule comparison requires instrumenting a generation interface that exposes them; do not assume the counters equivalent. Quantization changes weights and potentially logits and answers; high or low agreement on one set does not prove general equivalence.
RSS change while loading GGUF is a process observation, not peak generation memory: file pages can be mapped and loaded on demand. The GGUF file is not VRAM either. Compare this reading with peak PyTorch-allocated memory printed by the experiment, remembering they use different resources and criteria. Fair backend comparison requires repeating both in isolated processes on the same device with equivalent measurement methods.
The next experiment compares 100 one-digit additions with the same text, output limit, repetition penalty, and greedy decoding. This is an easy integration test, not a reasoning benchmark. It counts exact match after trimming spaces and accuracy against the known sum. Aggregate latency includes prefill and generation; dividing output tokens by it gives end-to-end throughput, not a separate decoding rate. Results depend on machine load and one backend using GPU while the other uses CPU. The full loop is an explicit local run because of its duration.
In one run of this loop with an RTX 3060 in bf16 and Q4 GGUF on CPU, texts matched on 58 of 100 questions. Exact comparison with the expected number counted 63 correct for Transformers and 44 for GGUF. This metric marks an answer such as 8 + 3 = 11 incorrect even if arithmetic is correct: it measures required format as well as arithmetic. Times vary with shared load and do not isolate engine, quantization, or device effects.
import statistics
filas = []
for i in range(100):
a, b = divmod(i, 10)
mensajes = [{"role": "user", "content": f"What is {a} + {b}? Answer with one number."}]
t = llm.chat(mensajes, temperature=0, max_new_tokens=8, use_cache=False)
g = gguf.chat(mensajes, temperature=0, max_new_tokens=8, use_cache=False)
filas.append((a + b, t, g))
print("Coincidencias de texto:", sum(t["text"].strip() == g["text"].strip() for _, t, g in filas), "/", len(filas))
print("Aciertos exactos Transformers:", sum(t["text"].strip() == str(y) for y, t, _ in filas))
print("Aciertos exactos GGUF:", sum(g["text"].strip() == str(y) for y, _, g in filas))
for nombre, pos in [("Transformers", 1), ("GGUF", 2)]:
resultados = [fila[pos] for fila in filas]
tokens = sum(r["output_tokens"] for r in resultados)
segundos = sum(r["seconds"] for r in resultados)
print(nombre, "tokens de salida medios:", statistics.mean(r["output_tokens"] for r in resultados),
"tokens/s de extremo a extremo:", tokens / segundos)
print("GPU PyTorch, máximo asignado (bytes):", torch.cuda.max_memory_allocated())
gguf.model.close()npm run lab and open the connection link.Output max_memory_allocated counts PyTorch-managed memory in this process, not all system VRAM. To compare total memory across engines, measure separately in isolated processes and include context, reserves, and host RAM. The loop explicitly closes the GGUF model when finished; rerun the adapter cell to use it again. As a rough dense-matrix operation approximation, FLOPs for parameters, prompt tokens, and generated tokens helps count compute: the last generated token need not be processed to generate another. This omits attention, embeddings, cache, quantization, and control operations. Do not present it as measured FLOPs.
To study a technique, first fix the engine used in every condition. Transformers bf16 is useful when model logits and a PyTorch stack are needed to instrument the experiment; GGUF supports testing quantized formats with llama.cpp, including CPU execution. Changing format, template, or device along with technique means an answer difference does not identify its cause. Check agreement, budget, and accuracy on your own sample and remeasure before selecting for production.
Exercises
def sequence_logprob(logits, tokens, prompt_len):
passdef cache_key(model, template, messages, params, seed):
pass