What Are Large Language Models and What Is an LLM?
Large language models (LLMs) are neural networks trained on large collections of token sequences to model language. A generative LLM answers a prompt by scoring possible next tokens, selecting one and repeating the process to produce text or code. It can perform tasks such as summarisation, translation and reasoning, but fluent output does not establish that an answer is correct.
A token is a unit of input that a tokenizer maps to an integer. It can represent a word, part of a word, punctuation or whitespace. For example, a tokenizer might split an unfamiliar technical term across several IDs. English, Hindi and code can therefore use different numbers of tokens for similarly sized passages. The model operates on token IDs, so word counts and character counts are poor substitutes for measuring what fits in a request.
Many text-generating LLMs use a decoder-only Transformer architecture. An embedding table maps each input ID to a vector, and the model incorporates information about token positions. In each decoder layer, causal self-attention lets a position draw information from itself and earlier positions. Feed-forward layers transform the resulting vectors. A final projection converts the last position's vector into one score per vocabulary entry. Those scores, called logits, are what the generation code uses to decide which token comes next.
The word large has no formal parameter threshold. It generally describes models with substantial training data and capacity, relative to earlier language models. Some families, including GPT, Llama, Gemini and Claude, also include versions that accept inputs such as images. The training objective and generation loop below focus on text.
How Are LLMs Trained?
The typical workflow starts with assembling a dataset. Sources can include books, web pages, articles and source code, depending on the project. Teams decide which sources to use, then filter, deduplicate and tokenize the data. These choices shape what the model sees and how often it sees it. For example, duplicates can inflate the prominence of particular text, and overlap between training data and benchmark answers can make an evaluation score misleading.
During pretraining, the model practises a general objective across many batches of text. Large runs can process trillions of tokens, but there is no required token count. A count of tokens processed may also include repeated passes over material. As the model gets better at prediction, it can develop useful representations of grammar, meaning and relationships across passages. Facts are learned indirectly through the prediction task, so the learned weights do not provide a reliable record of sources or a reliable way to look up a fact.
The resulting base model can continue text. Given a question, it could produce an answer, a second question or even another line of a worksheet. Optional post-training shapes that behaviour. In supervised instruction tuning, training examples pair user requests with desired replies. Many implementations compute the loss on reply tokens and mask out prompt tokens. Preference-based methods can further favour responses judged more useful than alternatives. A team may also use fine-tuning methods such as LoRA to adapt an existing model to a narrower task or response format.
| Stage | Input and learning signal | Result |
|---|---|---|
| Pretraining | Token sequences, with the next token in each sequence as the target | A base model that can continue text |
| Optional post-training | Examples of desired replies, preference signals or task-specific data | A model adapted for instructions, conversation or a particular task |
| Inference | A prompt and decoding settings, with no training targets | A generated output from a fixed set of weights |
The handoff between these stages is a saved model checkpoint. A team can evaluate a base checkpoint, post-train a copy, then compare both under the same task conditions. The chapter on training versus inference explains where the learning computation ends and deployment begins.
How Does LLM Pretraining Work?
For an autoregressive language model, next-token prediction is self-supervised because the target comes from the data itself. If a training passage says “The cat is sitting on a chair”, the model uses “The cat is sitting on a” to predict the next token. No one needs to label the passage with its topic or type the correct answer into a separate field. The original token sequence provides supervision.

Training does not need a separate forward pass per prefix. Suppose the tokenizer produces four IDs, [11, 24, 39, 52]. The input is [11, 24, 39] and the aligned targets are [24, 39, 52]. The first input position predicts 24, the second predicts 39 and the third predicts 52. The causal attention mask prevents each position from seeing later input positions, so the model cannot copy its target from the right. Because the original tokens serve as prefixes even when the model would have predicted something else, this setup is also called teacher forcing.
Worked example: Compute the next-token loss by hand
Imagine a toy vocabulary with four entries: “chair”, “mat”, “roof” and “other”. Treat each entry as one token for this calculation. After “The cat is sitting on a”, the model produces logits [ln(4), ln(2), 0, 0]. To turn scores into probabilities, softmax computes p(i) = exp(z_i) / sum_j exp(z_j). The exponentials are [4, 2, 1, 1], with a sum of 8. The resulting probabilities are [0.50, 0.25, 0.125, 0.125].
If the observed next token is “chair”, the loss at this position is -ln(0.50) = 0.693 approximately. If the same prediction is compared against a passage where the next token is “mat”, the loss is -ln(0.25) = 1.386 approximately. Both completions are plausible, but the loss for each example is based on the token the author actually wrote. In a real implementation, cross-entropy normally takes raw logits and computes the log probabilities internally for numerical stability.
Training averages losses over the target positions that count, excluding padding or other masked targets. Backpropagation computes gradients through the network, and an optimiser uses them to update the parameters. The same parameters serve many different contexts, so a single update can affect multiple predictions. Repeating the process across diverse text teaches the model to favour continuations that fit the prefix.
What Are LLM Parameters?
LLM parameters are the learned numerical values stored in the model, such as embedding entries, attention projection weights and feed-forward weights. A weight matrix with 4,096 input features and 4,096 output features contains 4,096 × 4,096 = 16,777,216 parameters before any bias. Counting parameters means counting the stored learned values across the network. If the input embedding and output projection share the same weights, the shared values count once.
Some model sizes are public. The largest GPT-3 variant has 175 billion parameters, and Meta published Llama 2 variants with 7 billion, 13 billion and 70 billion. Do not substitute unofficial parameter estimates for documented counts when discussing proprietary model versions. Also check what a published count measures. A mixture-of-experts model can report total parameters and a smaller activated count because its router uses only selected expert layers for a given token, alongside shared components.
Parameter count helps estimate weight storage. For example, 7 billion values in a 16-bit format need about 7 × 10^9 × 2 = 14 × 10^9 bytes, or 14 GB in decimal units, for the weights alone. This leaves out runtime allocations such as temporary tensors and the attention cache. Quantisation can reduce the bytes per value, while sequence length and batch size can increase runtime memory. Training needs additional memory for gradients, saved activations and, depending on the optimiser, optimiser state.
More parameters can increase capacity. They do not tell you how many tokens the model can read at once or how well it will handle your task. Data quality, architecture, training objectives and post-training all matter. Also distinguish learned parameters from generation settings such as temperature. Changing temperature during a request changes how the application selects tokens; it does not modify the checkpoint.
How Do LLMs Work at Inference Time?
Inference uses a trained model to compute predictions without updating its parameters. Start with a prompt such as “Explain RAG in simple terms.” A chat application may combine that prompt with system instructions and conversation history, formatting them with the checkpoint's chat template. The tokenizer converts the resulting text into IDs, and the model processes the input sequence to produce logits for the first new token. This initial input-processing stage is often called prefill.

The decoding algorithm selects a token from those logits. Greedy decoding picks the highest-scoring token. Sampling instead draws from a distribution, which can change across runs. For a positive temperature T, the sampler can apply softmax to logits / T. Lower values concentrate probability on high-scoring candidates. Filters such as top-k or top-p can restrict the candidates further. The chapter on the context window and sampling parameters shows how these settings affect the output.
The system appends the selected token and uses the extended prefix to predict again. In many Transformer runtimes, a key-value cache stores attention keys and values from positions already processed. At each decode step, the new token can attend to those stored values without rebuilding them for the entire prefix. The cache speeds up decoding by trading memory for less recomputation. It is temporary request state, separate from both the learned weights and any persistent conversation history managed by the application.
Generation can stop at an end-of-sequence token, an application-defined stop condition or a new-token limit. The prompt and generated tokens must fit within the model's supported context, subject to runtime limits. If a conversation grows too long, an application may trim or summarise old messages. Sending more text in the next request changes the context and can change the reply, but it does not train the model.
How Can You Run an LLM in Python?
This example uses a small base checkpoint, DistilGPT2, so you can inspect the generation loop on a CPU. The first run downloads the tokenizer and weights. Install torch and transformers in a Python environment, then run the script. The line that indexes logits[0, -1] takes the vocabulary scores for the final position of the first sequence in the batch.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
checkpoint = "distilbert/distilgpt2"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForCausalLM.from_pretrained(checkpoint)
model.eval()
prompt = "A database index helps a query by"
ids = tokenizer(prompt, return_tensors="pt")["input_ids"]
prompt_length = ids.shape[1]
eos_id = tokenizer.eos_token_id
with torch.inference_mode():
for step in range(12):
result = model(input_ids=ids, use_cache=False)
next_logits = result.logits[0, -1]
next_id = next_logits.argmax().reshape(1, 1)
print(step + 1, next_id.item(),
repr(tokenizer.decode([next_id.item()])))
ids = torch.cat([ids, next_id], dim=1)
if next_id.item() == eos_id:
break
new_ids = ids[0, prompt_length:].tolist()
print("Continuation:", tokenizer.decode(new_ids, skip_special_tokens=True))
model.eval() switches off training behaviour such as dropout. torch.inference_mode() disables gradient tracking for the forward passes. The code deliberately disables caching and resends the full prefix at every iteration so that the dependency is visible. For routine generation, model.generate() can handle the loop and use caching where supported.
Look at the printed token IDs and fragments. Leading spaces and partial words show why adding one token does not necessarily add one word. Try changing “helps a query by” to “can slow down writes because”. Compare the first few tokens under greedy decoding. The change comes from the prefix, with the same model weights in both runs. Since this checkpoint is a base model, judge the experiment by whether you can trace the loop, rather than treating its database explanation as authoritative.
What Are the Main LLM Families and Use Cases?
GPT, Llama, Gemini and Claude are family names. A product name alone cannot tell you what modalities, context limits, licence terms or deployment options apply. Check the exact version before comparing models or building an application around one.
| Family | Developer | What to check when choosing a version |
|---|---|---|
| GPT | OpenAI | GPT-3, GPT-4 and GPT-4o are distinct releases. GPT-4o is multimodal; check which input and output modes your interface exposes. |
| Llama | Meta | Llama 2 and Llama 3 have downloadable weight releases under version-specific licences. Check for base and instruction variants and verify usage terms before local deployment. |
| Gemini | Gemini includes multimodal models. Verify the supported text, image, audio and video inputs, context limits and tool features for the chosen version. | |
| Claude | Anthropic | Claude 3 included Haiku, Sonnet and Opus. Compare specific variants on your task and check interface features such as document inputs and tool use. |
The same generation loop can serve a chatbot, write code, translate a message or summarise a document. What changes is the input, the evidence provided and how the result is verified. For code, run tests against the intended behaviour. For translation, check terminology, meaning and register. For an internal policy assistant, use retrieval-augmented generation (RAG) to fetch relevant policy excerpts before generating a reply. Then check whether the reply's claims are supported by those excerpts, especially when policies have dates or exceptions.
For a first project, build a small evaluation set before trying several models. Include ordinary requests, incomplete requests and examples where the correct response is to ask for more information. Compare correctness, format compliance and latency with the same inputs and decoding settings. This gives you evidence about your application instead of relying on family names or parameter counts.
Key Takeaways
- A generative LLM predicts the next token from a prefix and repeats that prediction to produce a response.
- Next-token pretraining gets its targets from the original text and uses cross-entropy to penalise low probability on observed tokens.
- Optional post-training can turn a base text completer into an instruction-following assistant or adapt it to a specific task.
- LLM parameters are learned values. Context length, temperature and output limits are separate concepts.
- Inference uses fixed weights. A key-value cache can save computation without adding facts to the checkpoint.
- Choose a specific model version and test it on examples that reflect the real application.
Frequently Asked Questions
What is an LLM in simple words?
An LLM is a neural network that learns language patterns from large amounts of tokenised data. A generative LLM uses those patterns to write a response in small units called tokens. It can answer questions, summarise notes or write code, but its response may still contain unsupported claims or mistakes.
How does an LLM learn without labelled examples?
In next-token pretraining, the training text already contains the correct target. The model sees a prefix and predicts the following token. The training code measures how much probability it assigned to the token that actually followed, then updates the weights. People can still supply examples or preferences during later training stages.
Does a larger parameter count always mean a better LLM?
No. A higher count can give the model room to learn more patterns, but architecture, training data and post-training influence how useful those patterns are. Compare models on tasks you actually need, including relevant languages and input lengths. A smaller specialist model can be a better fit for a narrow task or limited hardware.
Does an LLM learn from my prompt during inference?
Standard inference leaves the model weights unchanged. The current prompt, earlier messages and examples can influence the reply when the application includes them in the input. This is temporary conditioning on the supplied context. If a provider separately uses saved conversations for future training, that is a different process from generating the current reply.
Why do two runs with the same prompt produce different answers?
When sampling is enabled, the system draws a token from a probability distribution. Two runs can choose different tokens, after which they have different prefixes for the next prediction. Greedy decoding removes this sampling choice, although repeatability can still depend on the model version, request formatting and numerical behaviour of the serving system.