All lessons in AI Engineering: From Foundation Models to Evaluated Applications
Foundation Models and Their Limits
Explain how training, architecture, tokens, and post-training affect application behavior.
60 minutes · Free lesson
What you will learn
- Explain the different roles of pretraining, post-training, inference, and application context.
- Relate tokens, architecture, and model size to concrete application constraints without treating them as quality guarantees.
- Diagnose a model limitation and choose an application-level response that can be evaluated.
Your support assistant receives a question about a product that was introduced yesterday. It writes a convincing answer even though you never supplied the new product policy. Another version refuses a question that the policy clearly answers. These are application failures, but fixing them requires a useful account of how the model produces its responses.
This lesson gives you that account without requiring a training cluster. You will distinguish learned parameters from supplied context, explain what tokens and attention do, and connect training choices to observable behavior. The P02 practice later puts a model adapter behind an application contract. The numerical examples here are deliberately small teaching constructions, not descriptions of a particular commercial model.
Separate learning from using a model
A foundation model is trained on broad data so that the resulting model can support multiple downstream tasks. The term describes a role in a larger ecosystem, not a promise that the model can perform every task reliably. A model may support text, images, audio, or combinations of modalities; you must verify the interface and capabilities of the specific model you use.
During training, an optimization procedure changes parameters to improve an objective on training examples. During inference, the application supplies inputs and the model computes an output using its current parameters. These operations have different costs, time scales, and failure modes. An application can adapt behavior through instructions and evidence without performing additional training.
A common language-model training objective predicts a token from its preceding context. The training text itself supplies many target examples, so the procedure does not require a person to label every next token. This is a form of self-supervision. It can produce useful representations and broad capabilities, but the objective is not the same as verifying a current order or enforcing a company's policy.
The distinction explains why plausible text can be wrong. The model's learned patterns support a likely continuation. Your application needs a supported answer to a particular question under current constraints. Those requirements may align, but they are not identical. When a new policy matters, supply authorized current evidence and check the response instead of assuming the necessary fact is stored reliably in the parameters.
Training data influences what the model can do well. Coverage of languages, technical domains, document styles, and tasks can be uneven. You rarely have a complete inventory of every example used to train a hosted model. Treat a model description as useful context for testing, not a substitute for evaluating your users' actual language and domain.
Data quality also matters. More examples do not automatically repair contradictory labels, missing context, or consistently wrong information. A model can learn shortcuts that perform well on familiar patterns and fail when the task changes. Your job is to include task slices that expose those mismatches, such as colloquial questions, incomplete dates, and products absent from the policy packet.
Understand tokens as the model's working units
A tokenizer maps input text into a sequence of discrete identifiers. A token might correspond to a whole word, a word fragment, punctuation, whitespace, or another unit, depending on the tokenizer. The same visible text can produce different token sequences with different models. Therefore words and characters are unreliable substitutes for measured token counts when limits matter.
| Property | What you should check | Why it matters |
|---|---|---|
| Tokenizer | Counts for representative input languages and formats | Input length and truncation depend on actual tokens |
| Context capacity | The model and endpoint's documented input/output limits | A request can exceed a limit even when the text looks short |
| Output limit | The configured maximum response length | Long responses can stop before completing a usable answer |
| Special formatting | Message wrappers and structured fields | Visible prose is not always the entire encoded request |
| Modality encoding | How images or audio are represented and charged | Text-only estimates do not cover all inputs |
A model commonly maps token identifiers to vectors, which are numerical representations used in its computation. During generation, a language model computes scores for possible next tokens. A decoding procedure turns those scores into a selection. Repeating this process produces a sequence. The next lesson examines that decoding step and the resulting variability.
Do not confuse a token boundary with a factual boundary. A product identifier may split into several tokens; a generated answer can reproduce a familiar-looking identifier while changing one character. Your application should validate exact identifiers against trusted records. A model's fluency is not an appropriate checksum.
For budgeting, measure the full request using the relevant tokenizer or provider-reported usage where available. If the tool only estimates text tokens, label the result as an estimate and retain a margin. Do not claim precise image token usage from a word count. When switching models, repeat the measurement instead of carrying over an old conversion factor.
Worked example
Budget a hypothetical text request
- Suppose a teaching endpoint has a combined input-plus-output budget of 8,000 tokens. Its accounting includes all instruction and message overhead in the counts below.
- Instructions and schema use 900 tokens, the customer question uses 180, and retained conversation uses 1,120. Their subtotal is 900 + 180 + 1,120 = 2,200 tokens.
- Reserve 1,000 tokens for the response and a 400-token safety margin. Evidence can therefore use at most 8,000 − 2,200 − 1,000 − 400 = 4,400 tokens.
- Six policy passages of 650 tokens each use 3,900 tokens and fit. Seven use 4,550 and exceed the evidence allocation by 150 tokens.
- The correct response is to select or shorten evidence deliberately, or change the request design. Silently removing the policy exception paragraph just because it comes last would create a correctness risk.
- The endpoint's combined-limit rule is an assumption for this example. A real endpoint may expose separate limits and additional accounting rules; verify those before using this worksheet unchanged.
Connect architecture to useful questions
The transformer is an influential architecture for foundation models. Attention computes context-dependent combinations of representations, allowing the model to use information from different positions. This is not a database lookup or a guarantee that every supplied statement will be used correctly. Attention is part of the model's numerical computation.
A decoder-style language model generates continuations while respecting a causal constraint: when predicting a next token, it cannot use future tokens that have not yet been generated. Encoder-style models commonly produce representations from supplied inputs. Encoder-decoder designs connect an input representation with an output generator. The names help you understand intended interfaces, but they do not rank models universally.
For a support application, the relevant questions are practical. Can the model process the evidence format? Can it produce an output your application can validate? Does it distinguish exceptions in a long policy? How much memory and time does inference require under your workload? You can answer these through documentation and measurement without implementing the architecture from scratch.
Model size often refers to a parameter count, but that count is not a complete serving specification. Numerical precision, activation memory, context length, caching, batching, and architecture affect runtime requirements. A sparse model may have different total and active parameter counts. Avoid estimating hardware needs solely by comparing two numbers in model names.
For a simplified lower-bound illustration, one billion stored parameters at two bytes each occupy two billion bytes, approximately two decimal gigabytes, for those weights alone. That excludes runtime buffers, activations, caches, and other overhead. It is not a promise that the model fits and runs comfortably on a two-gigabyte device.
Similarly, a larger context limit does not establish better use of long documents. A model can accept a large request and still miss the clause that changes the answer. Test information placement, distractors, and contradictory versions. Input acceptance and task correctness are separate properties.
Explain what post-training changes
Pretraining creates a starting model. Post-training applies additional objectives or examples to shape behavior for useful tasks and interactions. The exact pipeline varies, so avoid assuming that every provider uses the same sequence or terminology.
In supervised fine-tuning, examples specify desired responses to inputs, and optimization adjusts parameters toward those targets. Good examples can teach output style, task conventions, and patterns of instruction following. Poor examples can teach wrong answers or inconsistent behavior. The data and objective remain important even when the starting model is capable.
Preference-based methods use information about which responses are preferred under some criterion. Some approaches involve a learned reward model and reinforcement learning; others optimize from preference comparisons more directly. You do not need to implement those algorithms for the core application project, but you should know that preferred wording is not automatically equivalent to factual correctness.
For example, reviewers may prefer answers that sound decisive and complete. If the review process does not reward appropriate uncertainty, a model could become more persuasive without becoming more reliable on missing-policy questions. Your application evaluation must include unavailable answers and clarification cases, not just pleasant wording on routine cases.
Post-training can improve instruction following and refusal behavior, but it is not an authorization system. An instruction telling a model not to reveal other users' orders should be supported by server-side data filtering. If the model never receives another customer's order, one important disclosure path is removed before generation begins.
Fine-tuning is also not a default mechanism for updating rapidly changing facts. A policy database can change immediately and provide a versioned evidence source. Updating model weights involves a different workflow and may not reliably remove an obsolete fact. Later lessons compare prompting, retrieval, and adaptation based on the failure you actually observe.
An application can combine these methods. It may use a post-trained model for instruction following, retrieve current policy at request time, and enforce action permissions in code. Understanding their different roles makes debugging easier: a missing document calls for a different intervention from a malformed response or an unauthorized database operation.
Turn limitations into testable design decisions
Classify a failure before proposing a repair. If the answer uses an old return deadline, check whether the current policy reached the model. If the right paragraph was present but ignored, inspect the prompt and context arrangement. If the answer is correct but the interface crashes, examine parsing and application error handling. These are different engineering problems.
A useful failure record contains the request version, authorized evidence, model configuration, observed output, expected behavior, and a proposed explanation. Keep the explanation provisional. One incorrect response is evidence of failure, not proof of its root cause. Change one relevant component and re-evaluate on both the failure and a broader regression set.
Language and domain coverage deserve explicit tests. If your users ask in two languages, do not evaluate only one and assume transfer. If product names contain ambiguous abbreviations, include those abbreviations. If policy dates use a regional format, define the interpretation instead of allowing the model to guess silently.
You also need a plan for absence of evidence. A correct application may say that it cannot determine eligibility from the supplied information. This behavior is useful when accompanied by a specific request for the missing fact or an appropriate support route. A generic refusal on every difficult question is not success; it trades misinformation for an unusable service.
Think about what changes over time. The provider may update a model version, the business may revise a policy, and your users may ask different questions. Record versions and keep an evaluation suite so these changes can be assessed. A model that once passed your task contract does not receive permanent approval independent of the surrounding system.
Before P02, sketch the boundary between the model adapter and the application. The adapter accepts a validated request, sends it to a configured model service, and returns a validated result or controlled error. It does not decide the authenticated identity, silently change the policy, or grant itself additional permissions when uncertain.
Exercise
An assistant is given a newly published policy in its request and answers correctly. A teammate says the model has now permanently learned the policy. Explain the error and describe what another session would need.
Check your answer
The successful request shows use of supplied context, not a parameter update. Another session needs access to the current policy through its own authorized context or retrieval. A durable application memory could store a reference, but that is separate from changing model weights. Do not assume later requests inherit the document unless the application explicitly supplies or retrieves it.
Exercise
A hypothetical endpoint allows 12,000 combined tokens. Instructions use 1,500, history 2,000, the question 300, output reserve 1,200, and margin 500. Each complete evidence passage is 900 tokens. Calculate the evidence budget and maximum number of complete passages that fit.
Check your answer
Evidence budget is 12,000 − 1,500 − 2,000 − 300 − 1,200 − 500 = 6,500 tokens. Seven passages use 6,300 and fit; eight use 7,200 and do not. The remaining 200 tokens are unused evidence capacity, separate from the already reserved 500-token margin. Select passages for relevance and completeness, not simply their arrival order.
Exercise
A model follows the requested JSON format but invents a return rule for clearance items. Identify two things this result establishes, two things it does not establish, and one appropriate next diagnostic step.
Check your answer
It establishes that this output was parseable under the checked format and that its content violated the expected policy. It does not establish factual reliability or authorization to perform a return. Inspect the exact policy context and expected answer first: determine whether the clearance exclusion was supplied, omitted, or contradicted before deciding to change the prompt, retrieval, or model.
Inspect the text that actually reaches the model
The original Transformer paper introduced an attention-based architecture; it did not establish that attention weights certify a factual answer. A separate, practical issue is how an application encodes conversation turns. Hugging Face's chat-template documentation shows that role labels become model-specific token sequences. A conversation object is therefore not yet the final model input.
When moving between local models, preserve a fixture containing the messages and inspect the rendered template. Check where the assistant continuation begins and whether evidence is still inside the intended user turn. A formatting mistake can look like a reasoning regression, even when the visible message text is identical.
Worked example
Investigate a migration regression
- A synthetic classifier correctly handles 18 of 20 fixtures with its original model and tokenizer.
- After a model replacement, it handles 11. The team has retained the previous model's conversation template.
- Hold messages and decoding settings fixed, then rerun using the replacement model's documented template. Suppose the score becomes 17 of 20.
- This is evidence that serialization contributed to the observed failure. It does not isolate model quality, because the original and replacement models still differ.
- Save both rendered inputs and model/tokenizer revisions. Inspect the remaining failures before changing the prompt.
Exercise
A developer renders a chat template containing its special tokens, then tokenizes that text with another step that adds special tokens again. What should you inspect?
Check your answer
Inspect the resulting token sequence for duplicated control tokens. Follow the tokenizer's documented template path; if tokenizing an already rendered template separately, the Hugging Face guidance calls for disabling additional special tokens. Verify the actual model/template combination with a fixture.
Sources and further reading
Attention Is All You Need. Abstract and architecture motivation; original translation results are not present-day assistant benchmarks.
Hugging Face Transformers: Chat templates. Role serialization, control tokens, and avoiding duplicate special tokens.
Summary
Training changes parameters; ordinary inference uses parameters with supplied context. Tokens and architecture shape capacity and runtime behavior, while post-training shapes task and interaction behavior. None guarantees current facts, valid permissions, or correct outcomes. Diagnose failures by tracing evidence and application boundaries, then test the proposed repair.
Next action
Continue to Sampling, Context Windows, and Uncertainty. In P02, Build a Model-Powered Application, use these distinctions to document what the adapter controls and what the rest of the application must enforce.