Skip to main content
LearnMLAcademy
Beginner10 min read

What Are Large Language Models? From N-Grams to Modern LLMs

Understand modern Large Language Model architectures and pretraining, with token walkthroughs, prompt design tasks, and retrieval exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

You type “Explain gravity to a 10-year-old.” into an AI chatbot. A few moments later, an explanation appears, perhaps beginning: “Gravity is a force that pulls things toward each other.” How did the AI decide what words to write?

Underneath the chatbot is a model called a Large Language Model, usually shortened to LLM. An LLM learns patterns from huge amounts of text and uses those patterns to predict what text should come next.

Think of the reply as something built a little at a time: read the existing text → predict what comes next → add it → repeat. This lesson follows that process, explains how the model learns, and shows why a convincing reply can still be wrong.

Start with a familiar idea: autocomplete

If someone says “The sky is …”, you can suggest several continuations. “Blue,” “clear,” and “cloudy” sound natural. “Banana” is possible to type, but unusual in this sentence. A language model also ranks possible continuations, using patterns learned from text.

It can assign each candidate a probability: a number expressing how likely that continuation is according to the model. A larger percentage makes a candidate more likely to be selected; it does not certify that a statement is true.

Invented next-word probabilities after “The sky is”

Invented next-word probabilities after “The sky is”
Possible next wordIllustrative probability
blue70%
clear15%
cloudy10%
banana0.1%
All other possibilities together4.9%

These numbers are invented for teaching, not measurements from a commercial LLM. The final row accounts for the possibilities we have not listed, so the total is 100%.

For this example, choose the highest-probability word: blue. The text becomes “The sky is blue.” Now predict again using that longer text. A next addition could be “today,” or the sentence could end. The prediction changes as the text grows.

One addition becomes part of the next prediction

The sky isPredict, then chooseThis time: “blue”Add the chosen textThe sky is blueUse longer textStop when finished / at limit
Read → predict → add → repeat. Each return around the loop uses the longer text, not the original prompt alone.

The sky is enters prediction. In this toy example blue is selected and added, making The sky is blue. An arrow returns the updated text to prediction. Continue until a stopping condition is reached.

Real generation can also select among several likely alternatives instead of always taking the top candidate. That helps explain why the same request can receive differently worded replies.

The small pieces are called tokens

So far we used whole words to make the idea easy. Real LLMs usually work with pieces of text called tokens. A token can be a whole word, part of a word, or punctuation.

One conceptual split of “playing!”

playing!playing!

This is an illustration, not the output of a particular model’s text-splitting method. Different models can split the same text differently.

So “predict the next word” was a useful starting picture; predict the next token is the more accurate description. The next lesson explores how text is split and represented as numbers.

Why is it called “large”?

“Large” refers to the scale of the model and the resources used to teach it, not simply the length of its replies.

  • Large training datasets: huge collections of text provide examples of language, facts, styles, and relationships. The collection’s quality matters as well as its size.
  • Many learned parameters: a parameter is an internal numerical value the model adjusts while learning. Together, these values influence its predictions; they are not a collection of individually labelled facts.
  • Substantial computation: teaching a model involves repeating enormous numbers of calculations. Producing replies also requires computation, but is a different activity from training.

There is no single parameter count that makes every model an LLM. Nor does a larger model automatically give a better answer to every task.

How does an LLM learn from text?

Imagine a training sentence: “The cat sat on the mat.” Give the model the beginning, “The cat sat on the”, and ask it to predict the next piece. The text itself supplies the expected continuation: “mat”.

  1. Predict: suppose “chair” receives the highest score, while “mat” receives a low probability.
  2. Compare: the actual continuation in this training example is “mat”. “Chair” is a sensible sentence ending, but it is not the continuation observed here.
  3. Calculate error: a loss function measures how poorly the prediction fits the observed continuation. Giving “mat” a low probability produces a larger error than giving it a high probability.
  4. Adjust: training makes small changes to the internal parameters to reduce that error. One update does not guarantee that “mat” will become the top choice immediately.
  5. Repeat: many examples and updates gradually teach patterns that can help with new text, rather than only this one sentence.

This is the same learning idea used earlier in Machine Learning: examples → error → adjustment → better prediction. Here, the target comes from the text that follows. Training on varied examples helps the model learn language, but does not guarantee correctness or prevent it from memorizing some passages.

Training and answering a user are different jobs

During training, the model’s parameters are adjusted. When you normally ask a trained model a question, those values stay fixed. The model uses them to generate a reply; this use of a trained model is called inference.

Learning changes the model; using it grows the text

Training: change the model

  1. Example: The cat sat on the …
  2. Predict: chair gets the highest score
  3. Compare with the actual next text: mat
  4. Calculate error; adjust parameters

↺ Repeat with more training examples

The internal numerical values change.

Using: grow the answer

  1. User text: Explain gravity simply.
  2. Predict possible next text; choose one
  3. Add the chosen token to the text
  4. Use the longer text to predict again

↺ Repeat until finished or at a limit

Ordinary generation does not update the parameters.

Both processes make predictions. Only the training path shown here uses prediction error to adjust the model.

Two paths contrast learning from examples with generating a reply. Training loops through examples, prediction, error and parameter adjustment. Generation loops through user text, prediction and appending a token, with parameters fixed.

A follow-up message can change the next answer because it changes the text the model can read. That does not mean the model has retrained itself. An application may separately store a conversation or use feedback for later training; that is outside the ordinary generation loop.

The LLM is the engine, not the whole chatbot

A car needs more than an engine: it also needs controls, a body, and safety systems. Similarly, the LLM is one part of an AI application. The surrounding software decides what to send to the model and what to do with its answer.

Model capability versus application support

Model capability versus application support
PartWhat it does
LLM — the enginePredicts possible next tokens and helps generate the reply.
Instructions and conversation handlingTell the model what task to perform and include relevant earlier messages.
RetrievalFinds passages in a document collection and supplies them with the request.
ToolsLet the application call a calculator, search service, or other program when permitted.
MemoryStores selected information and brings it back into later requests.
Safety checks and interfaceApply application rules and provide the screen where a user reads and types.

Not every chatbot includes every feature in this table. In particular, a fluent answer alone is not evidence that the application searched the web or consulted a database.

A short history: the prediction idea grew more capable

Early approaches counted how often words appeared together. Short groups of consecutive words or tokens are called n-grams. A model relying on these counts can struggle when a phrase has never appeared in its examples.

Neural language models instead learn numerical patterns shared across examples, so learning from one phrase can help with another. Later, Transformers introduced a neural-network design that uses attention—a way to connect relevant parts of the input text. Many modern LLMs build on this design with much larger training efforts.

Word counts / n-grams → neural language models → Transformers → modern LLMs

This is a map of the progression, not a list of prerequisites to memorize. Keep the anchor: the model uses the text already available to help predict what follows.

What can you ask an LLM to do?

The same text-generation ability can serve different purposes when the request explains the task.

Familiar tasks, concrete requests

Familiar tasks, concrete requests
TaskExample request
Answer or explainExplain gravity to a 10-year-old.
SummarizeTurn these lecture notes into five main points.
TranslateTranslate this message into Hindi.
ClassifyLabel each customer message as a complaint, question, or compliment.
Extract informationList the dates and deadlines mentioned in this email.
RewriteMake this email clearer without changing its meaning.
Generate codeDraft a Python function that sorts these records by date.
BrainstormSuggest three possible titles for our college science exhibition.

These are possible uses, not promises of accuracy. Check a summary against the original, review a translation for meaning, and test generated code before relying on it.

Why can a convincing answer still be wrong?

Recall what the model is doing: generating a plausible continuation. That is not the same as looking up guaranteed truth. The model can produce an incorrect date, rely on stale information, invent a reference that looks real, or repeat biases found in its examples.

Later lessons introduce retrieval-augmented generation (RAG), which supplies retrieved source material; evaluation, which checks performance; and guardrails, which apply safeguards. These help manage errors, but none makes every answer automatically correct.

Worked example: build one sentence from beginning to end

Start with “Machine learning allows computers to”. The text available for the current prediction is called the context. Here, it initially contains only that sentence beginning.

For a small teaching example, suppose each word below is a single token and punctuation is a separate token. Actual token splits depend on the model; the spaces needed to read the words are included when the text is assembled.

First prediction — illustrative probabilities only

First prediction — illustrative probabilities only
Candidate next tokenInvented probability
learn62%
process18%
predict12%
banana0.01%
All other candidates together7.99%

The values total 100% and are not measured model outputs. Choose the largest value for this demonstration: learn. The updated context is now “Machine learning allows computers to learn”. The next prediction must use this longer context, not reuse the first table.

Each selection becomes input to the next step

Each selection becomes input to the next step
Context before predictionChosen next tokenText after adding it
Machine learning allows computers tolearnMachine learning allows computers to learn
… computers to learnpatterns… computers to learn patterns
… learn patternsfrom… learn patterns from
… learn patterns fromdata… learn patterns from data
… learn patterns from data.Machine learning allows computers to learn patterns from data.

In the table, “…” hides the unchanged beginning only to keep the rows readable; the model still receives it. Each row involves a fresh prediction. Later choices are illustrative selections, not calculations from the first row’s percentages.

After adding the full stop, this example ends: “Machine learning allows computers to learn patterns from data.” In an application, generation stops when an end signal or configured limit is reached; a full stop alone need not end a reply. Repeated next-token prediction is also called autoregressive generation: each addition helps determine the following one.

Read the rows as successive states of the same sentence. The output of one row becomes the input to the next; the displayed choices illustrate the process rather than promise what a particular model will generate.

The same loop in a few lines of pseudocode

This is a conceptual sketch, not runnable Python or a real model API. It shows the order of actions without hiding the lesson inside a large library program.

Conceptual generation loopPseudocode
text = "The sky is"
max_new_tokens = 20

for step in range(max_new_tokens):
    probabilities = model.predict_next_token(text)
    next_token = choose(probabilities)
    if next_token == END:
        break
    text = append_token(text, next_token)

show(text)
model, choose, END, append_token, and show are teaching placeholders, not imported functions.
  • text starts with the user’s input. The developer-chosen limit of 20 bounds how many new-token steps the loop attempts.
  • predict_next_token asks the trained model for probabilities using the current text. A real system first converts that text into the model’s token representation.
  • choose selects one candidate. In our toy examples it takes the highest probability; other selection rules are possible.
  • END represents a special stop signal. If selected, break exits the loop without adding it to the visible answer.
  • append_token adds the selected piece with the appropriate text spacing. The next iteration sees this updated text. show displays the result when the loop ends.

There is no error calculation or parameter adjustment in this code: it depicts using a trained model, not teaching one.

Pause and check the idea

An LLM says, “The Eiffel Tower is in Paris.” Does that necessarily mean it looked the fact up in a trusted database?

Reveal the explanation

No. The model may have generated this sentence from patterns learned during training. It is a correct statement, but the sentence alone does not show that a lookup happened. To establish that a source was used, inspect the application’s retrieval evidence rather than its confident wording.

Next: how do pieces of language become numbers?

We have repeatedly said that an LLM predicts the next token. But exactly how is text divided into tokens? And since neural networks work with numbers rather than raw words, how does language become numerical information?

The next lesson, Tokens, Embeddings & Context Windows, connects those steps. It explains embeddings—the numerical representations of tokens—and the context window, the limit on how much text a model can work with at once.

Summary / Key Takeaways

  • LLM stands for Large Language Model: the model inside many AI text applications.
  • It learns patterns from large amounts of text rather than needing a hand-written rule for every reply.
  • Generation repeats a loop: predict the next token, choose it, add it, and predict again.
  • Tokens are pieces of text, not necessarily whole words.
  • Training uses prediction error to adjust internal numerical parameters; ordinary generation uses the trained values.
  • Fluent output does not guarantee factual truth. Check important claims against reliable evidence.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "What Are Large Language Models? From N-Grams to Modern LLMs"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What is the core operation repeated during ordinary autoregressive LLM text generation?
Question 2 of 5conceptual
During LLM training, what happens after the model makes a poor next-token prediction?
Question 3 of 5interpretation
Why does an unseen phrase create a bigger problem for a simple n-gram model than for a neural language model?
Question 4 of 5practical selection
A team needs to return the exact current wording of a legal policy. What should it avoid assuming about an LLM?
Question 5 of 5application/scenario
A chatbot remembers conversation state, retrieves private documents, calls tools, and displays an LLM response. Which statement is correct?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the core operation repeated during ordinary autoregressive LLM text generation?▼

Correct Answer: Predict or score possible next tokens from the available context

Autoregressive generation repeatedly scores possible next tokens from the current context, selects one, appends it, and repeats.

2During LLM training, what happens after the model makes a poor next-token prediction?▼

Correct Answer: The model uses the prediction error to adjust its internal parameters

During training, the model compares its prediction with the observed continuation, calculates an error, and uses that error to adjust internal parameters.

3Why does an unseen phrase create a bigger problem for a simple n-gram model than for a neural language model?▼

Correct Answer: N-grams depend on observed short-sequence counts, while neural models share learned representations across patterns

Count-based n-grams may have no useful count for an unseen sequence; neural models can generalize through shared learned parameters and representations.

4A team needs to return the exact current wording of a legal policy. What should it avoid assuming about an LLM?▼

Correct Answer: That fluent generation is equivalent to guaranteed exact retrieval

Fluent next-token generation can still produce unsupported or altered wording. Exact authoritative text should come from a trusted source/retrieval path.

5A chatbot remembers conversation state, retrieves private documents, calls tools, and displays an LLM response. Which statement is correct?▼

Correct Answer: The chatbot is an application around an LLM and adds several system capabilities

The LLM is one model component; conversation handling, retrieval, tools, safety, and UI are application-level capabilities.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next