How Does Generative AI Work?
Generative AI learns patterns from training examples by adjusting numerical parameters to improve a training objective. At inference time, it uses those learned parameters with an input, such as a text prompt, to generate an output by predicting tokens, removing noise, or running another generation process. The exact method depends on the model family.
The basic workflow has two paths. On the training path, prepared examples go into a model, a loss measures how well its predictions match the training targets, and an optimizer updates the model's weights. On the generation path, a prompt goes into the trained model, and a generation algorithm turns the model's predictions into an output. For example, an image system may encode the prompt “A cat sitting on a chair” and use that representation to guide the generation of an image.
Weights are arrays of numbers used in operations such as matrix multiplication. They affect which tokens the model scores highly or which changes it predicts for a noisy image. A checkpoint saves weight values at a particular stage of training. The original dataset is normally outside the inference path, although a model can memorize parts of its training data. Generating an output therefore does not establish that the output is original or correct.
If you are new to the terminology, start with what generative AI is. This chapter focuses on the mechanics: how input examples become training signals, how those signals change weights, and how fixed weights produce an answer later.
Training vs Inference: What Changes in Each Phase?
| Aspect | Training | Inference |
|---|---|---|
| Goal | Improve performance on a training objective. | Use the trained model to produce an output for a new input. |
| Process | Run a forward pass, compute loss and gradients, then update trainable parameters. | Run forward computations and select tokens or apply another generation procedure. |
| Data | Batches of examples and their targets, such as shifted text tokens. | A prompt, image, audio signal, or other input, depending on the model. |
| Parameters | Trainable parameters change after optimizer steps. | Weights stay fixed during ordinary generation. |
| Compute | Includes forward and backward passes, often repeated over many batches on GPUs or TPUs. | Skips gradient computation and optimizer updates, but long outputs or large request volumes can be expensive. |
| Output | A checkpoint containing learned weights. A resumable checkpoint may also store optimizer state. | Generated text, code, images, audio, video, or another model output. |
Consider a model that assigns a low probability to chair after “The cat sat on a”. During training, if chair is the recorded target, the loss penalizes the low probability. Backpropagation computes how changes in trainable weights would affect that loss. The optimizer uses those gradients to update the weights. During inference, there is usually no recorded target for your prompt. The system uses its current scores to choose a continuation and leaves the weights alone.
Changing the conversation context is different from updating weights. If you correct a chatbot and it revises its answer, the next request can include your correction as input. The model can then produce a different response without training. This is also why an example placed in a prompt can affect the immediate answer without becoming a permanent part of the model.
Training is often more expensive than serving one request, but compare workloads with the same scope. Training stores intermediate results needed for backpropagation and usually tracks optimizer state. Inference avoids those costs, yet text generation can require a sequence of dependent forward steps. A popular service can spend substantial compute serving a fixed checkpoint repeatedly.
How Do Generative Models Learn Probability and Patterns?
Generative modelling aims to learn a distribution that approximates the examples in the training data. Write the data distribution as P_data(x) and the model distribution as P_theta(x), where theta denotes the learned parameters. A conditional model uses an additional input c, such as a caption, and generates samples from a distribution represented as P_theta(x | c). An image classifier might estimate a label given a photo, whereas an image generator can sample a photo-like output given a description.
| Model family | Typical training signal | How it generates |
|---|---|---|
| Autoregressive language model | Cross-entropy against the observed next token. | Chooses a token from next-token scores, appends it, and repeats. |
| Generative adversarial network (GAN) | A discriminator learns to distinguish real samples from generated ones, while the generator learns to produce samples that the discriminator judges as real. | Maps a sampled latent vector to an output using the generator. |
| Variational autoencoder (VAE) | An objective combines reconstruction with a penalty that encourages the encoded latent distribution to stay close to a prior. | Samples a latent vector from a prior and decodes it. |
| Diffusion model | A common objective trains the model to predict noise added to examples at different noise levels. | Starts from noise and applies repeated denoising updates, optionally guided by a prompt. |
These generative model families represent distributions in different ways. A GAN can produce samples without exposing a tractable probability for a particular image. An autoregressive text model, by contrast, can assign a probability to a token sequence by multiplying the conditional probability of each token given its predecessors.
For tokens x_1 through x_n, the chain rule gives P_theta(x_1, ..., x_n) = product over t of P_theta(x_t | x_1, ..., x_(t-1)). For the first token, the context is empty or contains a start marker, depending on the model. If you want the probability of generating exactly that sequence and then stopping, include the probability of the end token when termination is modelled that way.
For example, suppose the probability of cat first is 0.20, the probability of sits after cat is 0.50, and the probability of ending after cat sits is 0.40. Under unmodified sampling from those distributions, the probability of that complete sequence is 0.20 * 0.50 * 0.40 = 0.04. In software, summing log probabilities avoids multiplying many small numbers, which can underflow. A high sequence probability indicates that the model finds the sequence plausible, and says nothing by itself about whether the statement is true.
What Is Pretraining in Generative AI?
Pretraining is an initial learning stage that gives a model general capabilities before task-specific adaptation. It commonly uses self-supervised objectives, where targets are constructed from the data itself. In next-token training, a text sequence supplies the answer token. In masked-token training, used by BERT-style encoders, selected input tokens are hidden and the model predicts them from surrounding context. The masked-token objective does not by itself define the left-to-right generation loop used by a chat model.

Pretraining starts with data preparation. Teams may filter corrupt files, remove duplicates, check permitted uses, and separate training and evaluation data. The mixture matters: a corpus with little Marathi text can give the model less opportunity to learn Marathi usage than a corpus with extensive Marathi coverage. A lower loss on the training set cannot establish that the model performs equally well across languages, domains, or writing styles.
For a decoder language model, tokenization converts text to integer IDs. Tokens can represent whole words, parts of words, punctuation, or other units. Suppose “The cat sat on a chair” is represented by one token per word for illustration. The inputs are The, cat, sat, on, a, and the shifted targets are cat, sat, on, a, chair. The prediction at the input position a is compared with chair.
A decoder-only Transformer uses a causal attention mask so that a prediction at position t cannot use input positions after t. This allows the training system to compute predictions for several positions in one forward pass without exposing the answers to earlier positions. The model sees the recorded preceding tokens even if its own earlier prediction would have been wrong. This training setup is called teacher forcing.
The model produces a logit for each vocabulary item at each prediction position. Softmax converts logits to probabilities by dividing each exponentiated score by the sum of the exponentiated scores. The loss for target ID y is -log(p_y), where p_y is the model's probability for that target. Implementations typically compute cross-entropy directly from logits for numerical stability and average over valid target positions, excluding padding. That average supplies the scalar loss for backpropagation.
Worked Example: How Does One Training Step Change a Prediction?
Use a toy vocabulary with three candidate tokens: chair, mat, and floor. Given the final context token a, suppose the model outputs logits ln(6), ln(3), ln(1). Exponentiating gives scores 6, 3, 1. Softmax divides each score by 10, giving probabilities 0.60, 0.30, 0.10. If the training target is chair, the loss is -ln(0.60) = 0.5108, rounded to four decimal places.
For softmax cross-entropy, the gradient with respect to logit z_i is p_i - 1[i = y], where the indicator is one only for the target index. Here the gradients are -0.40, 0.30, 0.10. In the toy model, the logits are themselves trainable entries in a lookup table. A gradient descent step with learning rate 0.5 therefore adds 0.20 to the first logit and subtracts 0.15 and 0.05 from the others. The target probability rises to about 0.675.
import torch
from torch import nn
vocab = ["chair", "mat", "floor", "a"]
# One logit row per previous token; only three outputs are allowed.
model = nn.Embedding(len(vocab), 3)
context = torch.tensor([vocab.index("a")])
target = torch.tensor([vocab.index("chair")])
with torch.no_grad():
model.weight.zero_()
model.weight[context.item()] = torch.tensor([6.0, 3.0, 1.0]).log()
optimizer = torch.optim.SGD(model.parameters(), lr=0.5)
loss_fn = nn.CrossEntropyLoss()
# Training: backward() computes gradients; step() updates weights.
model.train()
optimizer.zero_grad()
logits = model(context)
loss = loss_fn(logits, target)
print("Before:", logits.detach().softmax(dim=-1).tolist())
print("Loss:", round(loss.item(), 4))
loss.backward()
optimizer.step()
# Inference: score the same context with the updated weights.
model.eval()
with torch.inference_mode():
logits = model(context)
print("After:", logits.softmax(dim=-1).tolist())
print("Greedy next token:", vocab[logits.argmax(dim=-1).item()])
This lookup table uses only the last token. It cannot tell “The cat sat on a” from “Please wipe it with a” because both inputs end in a. A Transformer computes logits from a context-dependent hidden representation instead. Its gradients pass through the output layer and the earlier operations that produced the representation. The toy example isolates the local loss calculation; it does not establish that a step that helps one training example will help on unseen text.
How Does Inference Generate Text Token by Token?
At inference time, a text generation system formats the request, tokenizes it, and processes the prompt in a stage often called prefill. The logits at the last prompt position score candidates for the next token. Greedy decoding selects the highest-scoring candidate. Sampling draws a candidate from a distribution derived from the logits. The system appends that token to the context and uses the extended sequence to score the following token.

- Encode a prompt such as “Once upon a time” as token IDs.
- Run the trained model on the prompt to obtain scores for the first continuation token.
- Select a token using the configured decoding rule, then append it to the sequence.
- Repeat until the system emits an end token, detects a configured stop condition, or reaches the output limit.
- Decode the generated token IDs into text. The application can stream that text as it becomes available.
For an interactive service, the prompt length influences how long the user waits for the first token, and the decoding loop influences how quickly the remaining tokens arrive. Transformer implementations commonly use a key-value cache to retain attention keys and values from earlier positions. This avoids recomputing them from scratch at each step. The cache uses memory and grows with sequence length for standard full-context attention. It stores intermediate results for the current context, rather than learned weights.
With ordinary temperature sampling, the system applies softmax to logits / T for T > 0. Smaller positive temperatures concentrate probability on higher-scoring tokens; larger temperatures spread it out. Top-k can restrict selection to a fixed number of candidates, and top-p can retain a set whose cumulative probability reaches a threshold. These generation parameters change selection at inference, without changing the checkpoint. Greedy selection can be implemented directly as argmax, without softmax.
What Is the Generative AI Workflow from Data to Applications?
A practical workflow is data preparation, pretraining, evaluation of the base model, optional adaptation, then deployment for inference. Broadly pretrained models that can support many downstream uses are commonly called foundation models. The term describes their role as a reusable starting point. There is no single model size or parameter count that determines whether a model qualifies.
A base language model trained for continuation may extend a support question instead of answering it directly. Fine-tuning on instruction-and-response examples can teach it to produce more useful answers. Adaptation is another training stage: it can update all weights, a subset of weights, or newly added parameters. During a later inference request, the resulting trained parameters are used without optimizer updates.
Consider a campus help desk that needs to answer questions about lab timings. Pretraining can supply general language skills, and instruction tuning can help the model follow a requested answer format. To use the current schedule, the application can fetch an approved document and place the relevant passage in the input using retrieval-augmented generation. A schedule change can then be handled by updating the source document. The system still needs tests for whether it retrieves the right passage and whether its answer matches that passage.
Keep the evaluation questions separate at each stage. For pretraining, compare loss on held-out examples that were excluded from training. For adaptation, test behaviours such as instruction following and output format adherence with representative prompts. For deployment, measure response time and check whether the application meets its quality requirements. The same workflow applies to text, code, image, audio, and video applications, but the generation algorithm and the tests must fit the modality.
Key Takeaways
- Training updates trainable parameters by minimizing a loss. Inference uses fixed weights to generate outputs for an input.
- Pretraining often uses self-supervised targets, such as the next token already present in a training sequence.
- Autoregressive models factor sequence probability into conditional next-token probabilities. GANs, VAEs, and diffusion models use different generation procedures.
- Cross-entropy penalizes low probability on the observed target. Backpropagation computes gradients, and the optimizer applies updates.
- Decoding settings affect which outputs are selected, and the key-value cache avoids repeated computation during text generation.
- Fine-tuning changes trained parameters. Prompting and retrieving information change the input to inference.
Frequently Asked Questions
Is pretraining the same as training?
Pretraining is one stage of training. It builds general capabilities before adaptation to particular tasks or behaviours. Training is the broader term for stages that optimize parameters, including pretraining and fine-tuning. They may use similar update rules, but the datasets, objectives, and parameters selected for updating can differ.
Does a model learn from my prompt during inference?
During ordinary inference, the prompt influences the output because it is part of the model's input. The request does not update the model's weights. A service may retain conversation history or run a separate training pipeline, depending on its design and data policy. Neither should be confused with generating a response.
Why can a language model give different answers to the same prompt?
When decoding uses sampling, the system can pick different tokens from the same probability distribution. Once the first selected token differs, later predictions are conditioned on a different prefix. Greedy decoding removes that sampling step, but reproducibility can still depend on the complete input, model version, and serving configuration.
Do all generative models predict the next token?
No. Autoregressive language models are a common example of next-token prediction. A diffusion image model typically learns a denoising-related objective and generates by updating a noisy representation repeatedly. A GAN can generate an output from a latent vector in one generator pass. The model family determines the generation procedure.
Does lower pretraining loss mean a model gives more factual answers?
Lower loss on comparable held-out text means the model assigns higher probability to the observed tokens on average. It does not directly measure whether an answer is supported by reliable evidence or whether the model abstains when it lacks context. Factual reliability needs separate evaluation with representative questions and verifiable references.