🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Text Generation Models: Choosing and Running Them

đŸŸĸ Free Lesson

Text Generation Models: Choosing and Running Them

Every text generation model solves the same problem — predict the next token, repeat — yet two models with similar parameter counts can feel like entirely different products. The differences come from data, post-training, context length, and how carefully the serving stack is tuned. This lesson gives you a map of the landscape, a fair way to compare hosted and open-weight options, and a procedure for choosing a model with evidence instead of brand loyalty.

One Architecture, Many Personalities

Modern generators are almost all decoder-only Transformers with causal masking, and the visible variety comes from what happens after pretraining. Instruction tuning teaches the model to answer rather than continue; preference optimization shapes which answers it prefers; long-context training extends how much it can hold at once; tool training teaches it to emit structured calls instead of prose. A base model and its instruct sibling share weights at initialization yet behave nothing alike, so never benchmark a base model on chat tasks and conclude the family is weak.

Scale still matters, but not linearly. Larger models reason further ahead, hold more facts, and follow intricate instructions, while smaller models with strong post-training can beat larger ones on narrow, well-specified work. Context window is a separate axis entirely: a model with a million-token window can ingest whole codebases, but attention quality at the far end of that window is what determines whether long-context claims hold up in your task.

Family traitWhat it signalsWatch out for
Decoder-only, instruct tunedGeneral assistant workCalibration of refusals varies by vendor
Base or completion modelContinuation, fill-in, customizationNeeds its own prompt format
Code specializedDiff and completion strengthWeaker at long-form prose
Small distilled modelLatency and cost leaderStruggles with multi-step reasoning
Long-context variantDocument-scale inputCost rises with prompt length regardless
Mixture of expertsLarge capacity, partial activationRouter overhead, uneven expertise

Use the table as a filter, not a verdict: run your own evaluation set before committing, because family-level expectations are priors, not results.

Hosted APIs Versus Open Weights

Hosted APIs win on time to value: no drivers, no quantization decisions, no capacity planning, and upgrades arrive without your involvement. They cost more per token at scale, add a network dependency to every request, and place your prompts in someone else's infrastructure, which some data policies forbid. Open weights reverse the trade: you pay in engineering effort and hardware, and you gain control over quantization, batching, fine-tuning, and data residency.

The economics cross over earlier than people expect. A self-hosted 8-billion-parameter model serving moderate traffic on a single accelerator can undercut API pricing within weeks, provided utilization stays high — idle GPUs are the hidden tax. Quantization makes the arithmetic friendlier still, at a quality cost that you must measure rather than assume. Choose hosted while you are still changing prompts hourly, and model the crossover once traffic stabilizes.

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

def load_and_generate(name, prompts, max_new_tokens=96, temperature=0.7, top_p=0.9):
    tok = AutoTokenizer.from_pretrained(name)
    model = AutoModelForCausalLM.from_pretrained(
        name,
        torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
        device_map="auto" if torch.cuda.is_available() else None,
    )
    model.eval()
    inputs = tok(prompts, return_tensors="pt", padding=True)
    with torch.no_grad():
        out = model.generate(
            **inputs,
            max_new_tokens=max_new_tokens,
            do_sample=temperature > 0,
            temperature=max(temperature, 1e-5),
            top_p=top_p,
            pad_token_id=tok.eos_token_id,
        )
    return [tok.decode(row, skip_special_tokens=True) for row in out]

prompts = ["Write a one-sentence changelog entry for a caching fix.",
           "Explain rate limiting to a new engineer in two sentences."]
for text in load_and_generate("gpt2", prompts, max_new_tokens=40):
    print(text.splitlines()[-1][:160], "\n---")

Note the padding and end-of-sequence handling: generation with batched prompts fails or loops without them, and it is the most common first bug when moving from single examples to a loader.

Sampling Settings That Actually Change Behavior

Post-training gives the model a distribution; decoding decides what you get from it. Greedy decoding is deterministic and safe for extraction, but it drifts into loops on open-ended writing because repetitive text often has the highest conditional probability. Sampling fixes that, and its two filters serve different purposes: top-k caps the candidate count outright, while top-p keeps the smallest set whose cumulative probability reaches p, adapting to the model's confidence. Temperature rescales logits before either filter, sharpening or flattening the whole distribution.

python
import torch
import torch.nn.functional as F

def decode_one(logits, mode="nucleus", temperature=0.8, top_k=40, top_p=0.9):
    logits = logits / max(temperature, 1e-5)
    if mode == "greedy":
        return int(torch.argmax(logits))
    if mode == "top_k":
        kth = torch.topk(logits, top_k)[-1][..., -1, None]
        logits = logits.masked_fill(logits < kth, float("-inf"))
    elif mode == "nucleus":
        sorted_logits, sorted_idx = torch.sort(logits, descending=True)
        probs = F.softmax(sorted_logits, dim=-1)
        cum = torch.cumsum(probs, dim=-1)
        remove = cum - probs > top_p
        logits[sorted_idx[remove]] = float("-inf")
    probs = F.softmax(logits, dim=-1)
    return int(torch.multinomial(probs, 1))

torch.manual_seed(0)
logits = torch.randn(5000) * 2.0
for mode in ("greedy", "top_k", "nucleus"):
    draws = [decode_one(logits.clone(), mode=mode) for _ in range(200)]
    print(mode, "distinct tokens:", len(set(draws)))
print("temperature 0.1 vs 1.5 spread:",
      len({decode_one(logits.clone(), temperature=t) for t in (0.1, 1.5)}))

Running this experiment once builds the intuition that temperature and nucleus size interact: a tight nucleus caps the effect of high temperature, because the risky tail has already been cut.

A Selection Procedure That Survives Review

Treat model choice as a short, documented experiment. First, fix an evaluation set of fifty to a few hundred cases drawn from production phrasing, including hard and unanswerable inputs. Second, shortlist two or three candidates that fit your constraint envelope — latency, context length, data policy, budget. Third, run identical prompts against all of them at matched decoding settings and score for correctness, format validity, and cost per case. Fourth, inspect the failures rather than only the scores; a model that is wrong in recoverable ways may be better than one that is confidently wrong.

Decision factorQuestions to answerEvidence to collect
CapabilityDoes it solve my cases reliably?Eval pass rate, per-slice breakdown
LatencyDoes it fit my interaction budget?Time to first token, tokens per second
CostWhat does a typical conversation cost?Prompt and completion tokens times price
ContextCan it hold my documents?Effective recall at your prompt lengths
OperationWho handles uptime and upgrades?On-call plan, version pinning options
PolicyWhere does data go?Retention terms, regional endpoints

Keep the run artifacts — prompts, model versions, raw outputs, scores. Six months later, when someone asks why this model was chosen, the folder answers better than memory.

Routing Several Models in One Pipeline

Few production systems settle on a single model. A router inspects the incoming request, assigns it a tier, and sends it to the cheapest model that can handle it, escalating to a larger one only when the answer looks uncertain or the format check fails. Simple transformations, classification, and rewriting belong on a small fast model; multi-step reasoning and messy real-world questions justify the expensive one. The routing rule itself can be as plain as keyword matching or as elaborate as a classifier trained on your own evaluation outcomes.

python
import re
from dataclasses import dataclass

@dataclass
class Tier:
    name: str
    model: str
    cost_per_1k: float
    max_latency_ms: int

TIERS = {
    "fast": Tier("fast", "small-instruct", 0.0002, 400),
    "strong": Tier("strong", "large-instruct", 0.006, 2500),
}

SIGNALS = {
    "fast": r"^(list|rename|extract|classify|format)\b",
    "multi_step": r"\b(step by step|compare|prove|design|root cause)\b",
}

def route(question: str) -> Tier:
    lowered = question.lower()
    if re.search(SIGNALS["multi_step"], lowered) or "?" in question and len(question) > 300:
        return TIERS["strong"]
    if re.search(SIGNALS["fast"], lowered):
        return TIERS["fast"]
    return TIERS["strong"] if len(question) > 200 else TIERS["fast"]

for q in ("Rename these three files.", "Design a rollback plan for the migration step by step."):
    tier = route(q)
    print(f"{tier.name:6} {tier.model:16} {tier.cost_per_1k}")

Measure the router separately from the models it chooses: log the tier, the final answer quality, and the cost, then look for requests that were served cheaply and failed, since those are the cases your rules misjudged. Done well, routing typically cuts cost per request substantially while leaving quality roughly flat.

What Benchmarks Do Not Tell You

Public leaderboards are contaminated by training overlap, evaluated with prompts unlike yours, and averaged over tasks you may not care about. They also miss operational qualities entirely: how the model behaves under streaming, whether tool calls are well-formed on the first attempt, how it handles your users' typos, and whether it degrades gracefully when context fills up. Domain-specific quirks — legal citation formats, internal product names, tabular numbers — surface only on your data.

One more caution about comparing runs: pin the decoding settings, seed where the API allows it, and repeat. Temperature non-zero introduces variance large enough to flip individual cases, so a two-point difference measured once is noise. Report a range across repeats, and only treat a lead as real when it holds.

â„šī¸Match the model to the step

Many pipelines waste their most expensive model on tasks like reformatting or keyword extraction. Split the workflow and route simple steps to a small model; the quality loss is often undetectable while cost drops sharply.

Common Mistakes

Benchmarking a base model on chat prompts

Fix: Compare instruct variants with each vendor's documented chat template

Accepting vendor benchmark numbers for your use case

Fix: Run your own labeled set at matched decoding settings and compare per-slice

Ignoring batch padding and stop tokens

Fix: Set pad and eos ids explicitly, or batched generation loops or truncates

Choosing on parameter count alone

Fix: Post-training and data quality dominate; measure behavior, not size

Skipping the cost model before launch

Fix: Multiply realistic prompt and completion tokens by price for your expected volume

Key Takeaways

  • Nearly all text generators are decoder-only Transformers differentiated by post-training
  • Hosted APIs buy speed and shift operations; open weights buy control and shift cost
  • Greedy, top-k, top-p, and temperature jointly determine the feel and risk of output
  • Choose with a fixed evaluation set, matched settings, and per-slice failure review
  • Benchmarks are priors — your traffic, your phrasing, and your constraints decide
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement