Skip to the content.

Every Programmer Should Know: AI Edition - Tokens, Embeddings, Attention, Sampling, Evals, RAG, Fine-Tuning and Inference Costs

The core ideas every AI engineer and every programmer working with large language models (LLMs) should know, explained in plain words with rules of thumb, worked numbers and links to the best free deep dives: tokens and tokenization, context windows, embeddings, attention and transformers, how LLMs are trained, sampling, prompting, structured output and tool calling, RAG, agents, evaluation, fine-tuning, inference cost and latency, memory math, hallucination and AI security. It also ships a tiny, tested Python calculator for LLM memory, KV cache, compute and cost estimates.

Last reviewed: December 2026. Model names and prices change constantly, so this page teaches the concepts and math that stay true. All numbers are approximations; check them against your own models and hardware.


Contents


The 20 Facts in One Table

# Fact Why it matters
1 Models read tokens, not characters or words Cost, limits and odd failures (spelling, counting letters) all come from tokenization
2 English prose averages roughly 4 characters or 0.75 words per token Quick cost and context estimates; code and other languages use more tokens
3 Input and output tokens are usually priced differently, output higher Long answers cost more than long prompts per token
4 Everything the model knows about your request is in the context window No memory between calls unless you send it
5 Models use the middle of long contexts less reliably than the start and end Put key instructions and evidence where they will be used
6 Embeddings turn text into vectors where similar meaning is nearby The basis of semantic search and RAG
7 Attention lets each token look at every earlier token Cost grows with context length
8 LLMs are pre-trained on next-token prediction, then post-trained to follow instructions Explains both broad knowledge and assistant behavior
9 Temperature reshapes the next-token distribution; 0 means near-deterministic, not guaranteed identical Choose per task
10 Structured output and tool calling turn text models into software components Validate everything
11 RAG gives models fresh or private knowledge without retraining Most business AI is retrieval plus generation
12 An agent is a loop: model, tools, observations, stop Simple to build, hard to make reliable
13 Without an eval set, you cannot tell if a change helped The core skill
14 Fine-tune for behavior, retrieve for knowledge The most common misconception
15 Generation has two phases: prefill (parallel) and decode (one token at a time) Time to first token versus tokens per second
16 Decode is usually memory-bandwidth bound Smaller weights (quantization) speed it up
17 Weights need parameters x bytes per parameter: about 2 GB per billion parameters in 16-bit Quick hardware sizing
18 The KV cache grows with context length and batch size Often the real memory limit when serving
19 Models hallucinate fluent, wrong answers Ground, cite, verify
20 Any text a model reads can contain instructions aimed at it Prompt injection is a design problem, not a prompt problem

1. Tokens

What: A tokenizer splits text into pieces from a fixed vocabulary (often tens of thousands to a few hundred thousand entries), usually with byte-pair encoding (BPE). Common words become one token; rare words split into several.

Why it matters:

Rules of thumb: about 4 characters or 0.75 words per token for English with common tokenizers; use the provider’s token counting for real numbers.

Go deeper: OpenAI: Understanding and counting tokens, Claude token counting, Tiktokenizer playground, Let’s build the GPT Tokenizer (video), tiktoken, the original subword paper Neural Machine Translation of Rare Words with Subword Units.


2. Context Windows

What: The maximum number of tokens (input plus output) the model processes in one call. Models are stateless: “memory” in chat apps is the app re-sending history.

Why it matters:

Practice: put instructions first, keep only relevant context, summarize or drop old turns, and test with realistic lengths. See Claude: context windows and Effective context engineering for AI agents.


3. Embeddings and Similarity

What: An embedding model maps text (or images) to a vector of numbers. Texts with similar meaning have vectors pointing in similar directions; cosine similarity measures this (from -1 to 1).

Why it matters: semantic search, clustering, deduplication, recommendation and retrieval for RAG all run on embeddings.

Know this:

Go deeper: The Illustrated Word2vec, Sentence-BERT, Sentence Transformers docs, MTEB paper.


4. Attention and the Transformer

What: A transformer turns tokens into vectors, then repeats blocks of attention and feed-forward layers. Attention lets each token build its representation from a weighted mix of earlier tokens (“which earlier words matter for this one?”). The last layer produces a probability for every possible next token.

Why it matters:

Go deeper: The Illustrated Transformer, 3Blue1Brown: Transformers, Transformer Explainer, Attention Is All You Need, The Annotated Transformer, RoFormer (rotary embeddings), GQA.


5. How LLMs Are Trained

Stage Data Result
Pre-training Huge amounts of text, next-token prediction Broad knowledge and language ability, not yet a helpful assistant
Supervised fine-tuning (SFT) Example conversations and instructions Follows instructions, uses a chat format
Preference tuning (RLHF, DPO) Human or AI comparisons of answers More helpful, safer, preferred style
Reinforcement learning with verifiable rewards Problems with checkable answers (math, code) Stronger step-by-step reasoning

Why it matters: knowledge has a cutoff date; behavior comes from post-training; models can be confidently wrong because next-token prediction rewards plausibility.

Go deeper: InstructGPT, Illustrating RLHF, DPO, Constitutional AI, DeepSeek-R1, Deep Dive into LLMs like ChatGPT (video), RLHF book.


6. Sampling and Decoding

What: at each step the model outputs probabilities; a decoding strategy picks the next token.

Setting Effect Use when
Temperature low (near 0) Picks the most likely tokens Extraction, classification, code
Temperature higher More varied, more surprising Brainstorming, creative writing
Top-p (nucleus) Sample only from the smallest set covering probability p Limit nonsense while keeping variety
Max tokens Hard cap on output length Cost control; truncation risk
Stop sequences End generation at a marker Structured formats

Know this: temperature 0 is not a determinism guarantee (batching and floating point can change results). Some reasoning models restrict or ignore sampling parameters; check provider docs.

Go deeper: How to generate text (Hugging Face), The Curious Case of Neural Text Degeneration, Generation strategies.


7. Prompting and Context Engineering

Principles that keep working:

  1. State the task, the audience and the output format explicitly.
  2. Separate instructions from data with clear delimiters.
  3. Give a few varied examples for formats and edge cases.
  4. Ask for reasoning when the task needs multiple steps.
  5. Split complex jobs into chained calls you can test individually.
  6. Version prompts and test them against an eval set like code.

Go deeper: Claude prompt engineering overview, OpenAI prompt engineering, Chain-of-Thought prompting, Prompt Engineering (Lilian Weng), chat templates for how messages become tokens.


8. Structured Output and Tool Calling

What: You give the model a JSON Schema (for output) or a list of tools with schemas. The model returns JSON or a tool call; your code executes the tool and sends the result back.

Know this:

Go deeper: Claude tool use, OpenAI function calling, Writing effective tools for agents, Toolformer.


9. Retrieval-Augmented Generation (RAG)

Pipeline: split documents into chunks, embed them, store vectors, retrieve the most relevant chunks for a question (often hybrid vector plus keyword search, then reranking), and put them in the prompt with instructions to answer from them and cite.

Failure modes: wrong chunks retrieved, right chunks lost in a long prompt, outdated documents, missing permissions filtering, model ignoring sources.

Measure separately: retrieval quality (did the right chunk come back?) and answer quality (is the answer correct and faithful to the sources?).

Go deeper: RAG paper, Contextual Retrieval, Advanced RAG cookbook, RAG Evaluation cookbook, Pinecone RAG series, HNSW paper.


10. Agents

What: a loop where the model chooses actions (tool calls), sees results, and continues until done. Workflows (fixed steps) are often better when the path is predictable.

Know this: errors compound over steps; cost grows with steps and context; agents need step limits, budgets, sandboxes and human approval for risky actions.

Go deeper: Building effective agents, ReAct, LLM Powered Autonomous Agents, Demystifying evals for AI agents, Model Context Protocol.


11. Evaluation

What: a set of inputs with expected behavior, plus scorers, run on every change.

Scorer Good for Watch out
Exact match or regex Classification, extraction Brittle for free text
Code-based checks JSON validity, tests passing, SQL results Only checks what you code
LLM-as-judge Tone, helpfulness, faithfulness Must be validated against human labels
Human review Ground truth, error analysis Slow; sample wisely

Habit: read real outputs, group failures into categories, fix the biggest category, add cases so it stays fixed.

Go deeper: AI Evals FAQ, Your AI Product Needs Evals, Evaluating LLM-evaluators, LLM-as-a-judge cookbook, lm-evaluation-harness.


12. Fine-Tuning

Use it for: consistent format or style, narrow tasks at lower latency and cost, distilling a large model into a small one. Not for adding facts that change; use retrieval.

Methods: full fine-tuning (expensive), LoRA (train small low-rank adapters), QLoRA (LoRA on a quantized base model to save memory), preference tuning (DPO) for style and quality preferences.

Always: compare against a well-prompted baseline on the same eval set.

Go deeper: LoRA, QLoRA, PEFT, Distilling the Knowledge in a Neural Network, TRL.


13. Inference: Latency, Throughput and Cost

Go deeper: PagedAttention (vLLM), Optimizing inference (Hugging Face), KV cache from scratch, How to Scale Your Model, FlashAttention.


14. Memory Math

Quantity Formula Worked example
Weights params x bytes per param (fp32 4, bf16 2, int8 1, 4-bit 0.5) 7B in bf16: 14 GB; in 4-bit: 3.5 GB
KV cache per token 2 x layers x KV heads x head dim x bytes 32 layers, 8 KV heads, 128 dim, bf16: 128 KiB
KV cache total per token x tokens x batch 8,192 tokens: 1 GiB per sequence
Full fine-tune with Adam about 16 bytes per param, plus activations 7B: about 112 GB before activations
Training compute about 6 x params x tokens FLOPs 1B params on 20B tokens: 1.2e20 FLOPs
Inference compute about 2 x params FLOPs per token 7B: 14 GFLOPs per token
Decode speed ceiling (batch 1) memory bandwidth / bytes read per token 14 GB of weights at 1 TB/s: about 70 tokens/s at most

These are the standard back-of-the-envelope formulas for dense transformers. Real systems add overhead (activations, fragmentation, framework memory) and reach only part of theoretical bandwidth. Compute them with the calculator.


15. Quantization

What: storing weights (and sometimes activations or the KV cache) in fewer bits: 8-bit, 4-bit and lower.

Trade-off: less memory and faster decode, at some quality cost that grows as bits shrink and varies by model and task. Always evaluate on your task.

Go deeper: A Visual Guide to Quantization, LLM.int8(), GPTQ, 8-bit matrix multiplication (Hugging Face).


16. Scaling, Mixture of Experts and Reasoning Models


17. Hallucination

What: fluent output that is false or unsupported by the provided sources.

Reduce it: ground answers in retrieved sources and require citations; allow and reward “I don’t know”; check claims with tools (code execution, search, database queries); evaluate faithfulness separately from fluency.

Go deeper: Extrinsic Hallucinations in LLMs, Mapping the mind of a large language model for interpretability research.


18. Security: Prompt Injection and Friends

Risk What happens Defense
Direct prompt injection User tells the model to ignore its rules Do not put secrets in prompts; enforce rules in code
Indirect prompt injection Instructions hidden in web pages, documents, emails or tool results Treat all retrieved content as untrusted; limit tool permissions
Data exfiltration Model sends private data out through links, tools or images Avoid combining private data, untrusted input and outbound channels
Jailbreaks Crafted prompts bypass safety behavior Layered defenses, monitoring; see many-shot jailbreaking
Excessive agency Agent takes harmful actions Least privilege, approvals, sandboxes, audit logs

Go deeper: OWASP Top 10 for LLM Applications, The lethal trifecta, Adversarial attacks on LLMs, garak.


The LLM Math Calculator

tools/llm_math.py implements the formulas from Memory Math with no dependencies.

python3 tools/llm_math.py --params 8e9 --layers 32 --kv-heads 8 --head-dim 128 --context 8192 --bandwidth-gbs 1000

Example output:

weights (bf16):               14.90 GiB
KV cache per token (bf16):     128.0 KiB
KV cache (1 x 8192 tokens):     1.00 GiB
full fine-tune (no activations):    119.2 GiB
compute-optimal training tokens: 1.6e+11
decode upper bound at 1000 GB/s:     62.5 tokens/s

Use it from Python:

from llm_math import kv_cache_bytes, weight_memory_bytes, cost_usd

weight_memory_bytes(70e9, "int4") / 1e9    # 35.0 GB
kv_cache_bytes(80, 8, 128, 32_000) / 2**30 # KV cache for one 32k-token sequence, in GiB
cost_usd(1_000_000, 200_000, 3.0, 15.0)    # 6.0 with example prices per million tokens

Run the tests: python3 -m unittest discover -s tests.


Ten Papers Worth Reading

  1. Attention Is All You Need - the transformer.
  2. Scaling Laws for Neural Language Models - why bigger keeps working.
  3. Training Compute-Optimal Large Language Models - the data-versus-size balance.
  4. Training language models to follow instructions with human feedback - how assistants are made.
  5. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks - RAG.
  6. Chain-of-Thought Prompting Elicits Reasoning - reasoning by prompting.
  7. ReAct - reasoning plus acting, the agent loop.
  8. LoRA - cheap fine-tuning.
  9. Efficient Memory Management with PagedAttention - modern LLM serving.
  10. Lost in the Middle - limits of long context.

Self-Quiz

  1. A prompt is 3,000 words of English. Roughly how many tokens?
  2. Why can a model fail to count the letters in a word?
  3. You switch embedding models. What must you do to your index?
  4. Name the two phases of generation and which one sets time to first token.
  5. How much memory do the weights of a 13B model need in bf16 and in 4-bit?
  6. Should you fine-tune to teach the model your product catalog that changes weekly?
  7. What three capabilities together make prompt injection dangerous?
Answers 1. About 4,000 tokens. 2. It sees tokens, not individual letters. 3. Re-embed every document; vectors from different models are not comparable. 4. Prefill and decode; prefill sets time to first token. 5. About 26 GB and 6.5 GB, plus overhead. 6. No. Use retrieval for changing facts. 7. Access to private data, exposure to untrusted content, and a way to send data out.

FAQ

What should every AI engineer know first? Tokens, context windows, sampling, and how to build an eval set. Those four explain most early surprises.

How many tokens is a word? For English with common tokenizers, a token is about three quarters of a word on average. Code, numbers and many other languages use more tokens.

Why are output tokens more expensive? Output is generated one token at a time (decode), while input is processed in parallel (prefill), so output uses more hardware time per token.

What is the KV cache? Stored attention keys and values for previous tokens, so the model does not recompute them for every new token. It grows with context length and batch size.

Do I need a GPU to work with LLMs? Not to build applications with hosted APIs. Running or fine-tuning open models needs a GPU or Apple silicon, or a rented machine; use the memory math to size it.

RAG or fine-tuning? RAG for knowledge, fine-tuning for behavior. Many systems use both.


Where to Go Next


Contributing

Pull requests are welcome. Please keep entries accurate:

License

MIT. Copyright (c) 2026 Ralpberry Labs.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.