LLM Fundamentals

Welcome to the AI Engineering section of the course. We’ll start with foundational ideas behind LLMs and then progress to more progressive concepts and applications.

Let’s. F***ing. Go.

This Lesson Will Cover
  • 🧠 Core concepts behind Large Language Models (LLMs)
  • 🏗️ Transformer architecture and its key components
  • 🔤 Token-based processing and embeddings
  • 🪟 Context windows and attention mechanisms
  • 🌡️ Temperature and sampling strategies
  • 🌍 Real-world applications of LLMs

Why Large Language Models?

Large Language Models (LLMs) are transforming natural language processing (NLP), making it easier to build systems capable of understanding, generating, and interacting with human language. They are becoming foundational tools for AI engineers, enabling applications in chatbots, content creation, translation, and more.

Let’s break down how LLMs work and why they’re so effective.

Transformer Architecture

As we discussed in the Neural Networks section of this course, the transformer architecture has led to the creation of powerful language models that can understand and generate human-like text at unprecedented scales. This architecture revolutionized natural language processing by introducing a novel approach that moved beyond traditional recurrent neural networks.

A transformer has two core components:

  • Encoder: Maps input data into high-dimensional representations.
  • Decoder: Translates those representations back into human-readable text (or other outputs).

A key innovation in transformers is the self-attention mechanism, which allows the model to weigh the importance of different words in a sentence relative to each other.

Input Text -> Embedding -> Self-Attention -> Feedforward Layers -> Output Text

Token-Based Processing

LLMs break text into smaller units called tokens. A token might represent:

  • A single word (“dog”)
  • A subword (“un”, “believable”)
  • Or even a character (“a”)

For example, the sentence “AI is amazing!” might tokenize into:

["AI", "is", "amazing", "!"]

Each token is mapped to a high-dimensional vector in an embeddings space, where semantically similar words are positioned closer together:

"AI":      [0.2, -0.5, 0.1, 0.8, ...]
"is":      [-0.1, 0.2, 0.3, -0.4, ...]
"amazing": [0.7, 0.6, -0.2, 0.5, ...]
"!":       [0.1, -0.1, 0.0, 0.1, ...]

We’ve got a few lessons on embeddings coming up soon, but for now, it’s only important to understand that these vectors are numerical representations that serve as the actual input data for the model.

Context Windows and Attention Mechanisms

LLMs have a context window, which determines how much text they can “see” at a time. For example, if the context window is 4k tokens, the model can analyze roughly 3k words of text at once.

Here we’ve applied a commonly used ratio of 0.75 words per token, or 1/0.75=4/3=1 / 0.75 = 4 / 3 = 1.33 tokens per word.

Consider how the attention mechanism plays a critical role here. Its job is to help the model focus on relevant parts of the input. For example, in the sentence “The eagle soared gracefully above the ancient forest”, when processing the word “gracefully”, the attention mechanism gives higher weight to “eagle” (the subject) than to “forest”. This helps establish proper subject-verb relationships.

GPT-2 Attention Scores for 'Grace' in the Sentence 'The eagle soared gracefully above the ancient forest'
Actual attention scores from GPT-2 for the example above: "The eagle soared gracefully above the ancient forest". The word gracefully is split into two tokens: " grace" (notice the space prefix, which is included in the GPT-2 tokenized word) and "fully".

The power of attention becomes even more apparent with long-form text spanning hundreds or thousands of words. Unlike traditional models that struggle to maintain context over distance, attention mechanisms are able to reference information from much earlier in the sequence. This ability to maintain long-range dependencies allows LLMs to be highly effective for tasks like document summarization, complex reasoning, and maintaining coherent dialogue over extended conversations.

Temperature and Sampling Strategies

When generating text, LLMs use temperature to control creativity:

  • A low temperature (e.g., 0.2) makes the output more deterministic, favoring common phrases.
  • A high temperature (e.g., 1.0) increases randomness, allowing for more creative or diverse outputs.

In addition, sampling strategies like top-k sampling or nucleus sampling (top-p) can further refine how text is generated:

  • Top-k sampling: Selects randomly from the top-k most likely words.
    • For example, if k=3 and the most likely next words are “happy” (40%), “sad” (30%), “excited” (20%), and “nervous” (10%), only “happy”, “sad”, and “excited” would be considered for random selection.
  • Nucleus sampling: Chooses from the smallest group of words whose probabilities add up to p.
    • For example, if p=0.9 and words are “the” (50%), “a” (30%), “one” (15%), and “any” (5%), it would select from “the”, “a”, and “one” since they are the smallest group of words that exceeds the threshold, summing to 95%.
GPT-2 Next Token Probabilities Example
Next token probabilities for the example below: "The future of AI is __".

Here’s an example using Python and the transformers library to set some of these parameters for a GPT-2 model:

from transformers import GPT2LMHeadModel, GPT2Tokenizer

model = GPT2LMHeadModel.from_pretrained("gpt2")
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")

input_text = "The future of AI is"
input_ids = tokenizer.encode(input_text, return_tensors="pt")

output = model.generate(
    input_ids,
    max_length=50,
    temperature=0.7,
    top_p=0.9,
    do_sample=True
)

print(tokenizer.decode(output[0], skip_special_tokens=True))

# Output example: The world of AI is already becoming increasingly complex, and the possibilities for this are immense. Some of these

By the way, you might be curious what the output object itself looks like in the example above. Well, it’s a pytorch tensor of tokens.

For the example output above:

tensor([[  464,  2003,   286,  9552,   318,   991,  8627,    11,   475,   340,
           318,  1884,   326,   340,   481,   307,  1498,   284,  1011,   625,
           262,   995,   287,   262,  1474,  2003,    13,   198,   198,   464,
           995,   286,  9552,   318,  1541,  5033,  6481,  3716,    11,   290,
           262, 12779,   329,   428,   389, 13964,    13,  2773,   286,   777]])
GPT-2 Effect of Temperature on Token Probability Distribution Example
Next-token probability distribution at various temperatures for the GPT-2 model and input text above: "The future of AI is ___".

Real-World Applications

As we all know, LLMs perform exceptionally well in a variety of real-world applications.

Here are the highest-value applications that are transforming industries today:

  • Summarization: Summarize, classify, and extract key information from documents.
  • Content Generation: Draft articles, social media posts, and marketing copy at scale.
  • Customer Support: Automated agents handle natural conversations and resolve issues 24/7.
  • Coding Assistance: Write, debug, and optimize code while explaining complex logic.
  • Translation: Break language barriers with near-human fluency across hundreds of languages.

Conclusion

To complement this introduction to LLMs, you might consider watching Andrej Karpathy’s Intro to Large Language Models[1] (if you have an hour) or 3Blue1Brown’s Large Language Models Explained Briefly[2] (if you have 10 minutes).

Key Takeaways

🤖 LLMs are built on the transformer architecture with encoder-decoder components and self-attention mechanisms.

🔡 Text is processed as tokens that are converted into high-dimensional vector embeddings.

📏 Context windows determine how much text the model can process at once.

🎛️ Temperature and sampling strategies control the creativity and randomness of outputs.

Next: Prompt Engineering

With these foundational concepts under our belt, we’re moving on to the hottest programming language: English!

Footnotes


  1. 1 hour presentation (free, on YouTube) from Andrej Karparthy: Intro to Large Language Models. ↩︎

  2. Entertaining conceptual overview of LLMs from 3Blue1Brown: Large Language Models explained briefly. ↩︎

Comments (0)

No comments yet.