Speaker Notes

A Hackers' Guide to Language Models

Language models function through text compression and compute scaling, and developers can effectively leverage them using prompt engineering, function calling, quantization, and retrieval augmentation.

Jeremy Howard · 1:31:13 · YouTube ↗

Talk · solo speaker  Intermediate · Concepts, API usage, and code examples

Highlights

7 clips · 12 min of 91 min
    • Predicting next words requires learning world rules
    • Intelligence emerges from compressing massive text data
    • Custom instructions prime models to prioritize high-quality info
    • Generating more text allows the model to perform more computation
    • API servers store zero state between calls
    • The entire conversation history must be sent on every request
    • You can manipulate past assistant turns in the history array
    • Multi-turn conversations do not store state on OpenAI servers.
    • The entire conversation history must be sent back with every API call.
    • Developers can explicitly manipulate or fabricate message history to steer responses.
    • OpenAI API accepts custom tools via the `functions` keyword argument using JSON schemas.
    • Libraries like Pydantic and Python's `inspect` module can auto-generate schemas from functions.
    • The function's docstring is critical because the LLM reads it to decide when and how to call the tool.
    • Language models are bound by memory speed and capacity rather than raw processor power.
    • Used NVIDIA GTX 3090 cards offer a cost-effective entry point with 24GB of VRAM.
    • Apple Silicon Macs with high unified memory (like M2 Ultra) are viable alternatives for running local models.
    • Quantization (like GPTQ) optimizes models to run on lower precision data structures.
    • Quantized models reduce memory movement, often making larger models run faster than smaller unquantized ones.
    • Pre-quantized models are readily available on Hugging Face via contributors like 'TheBloke'.
    • Sentence Transformers encode documents and queries into vector embeddings.
    • Vector similarity allows developers to find the most relevant context documents for a given query.
    • Vector databases can scale this approach to millions of documents for Retrieval-Augmented Generation.

Questions this video answers

12 · every answer cites the moment it was said
01 What is a language model fundamentally doing under the hood? 2 sources · 1:33

A language model is essentially a function that predicts the next likely word or token in a sentence based on its training. By predicting successive words, it constructs coherent continuations or fills in missing parts of text. During this process, it evaluates probabilities for various candidate words to determine the most fitting output.

02 How do language models process text instead of whole words? 3 sources · 4:45

Language models tokenize text into sub-word units, whole words, punctuation, or numbers using specific tokenizers like tick token. These tokens are mapped to numeric IDs that act as lookups into the model's vocabulary. For instance, prefixes like spaces are often encoded directly into the token representation.

03 How does pre-training compress world knowledge into a neural network? 3 sources · 7:40

Pre-training forces a deep neural network to guess the next word across vast corpuses like Wikipedia, utilizing stochastic gradient descent to optimize its weights. To succeed at this task, the model must implicitly learn complex real-world concepts, entities, and relationships. This capability essentially acts as a form of information compression.

04 Why are fine-tuning and instruction tuning necessary after pre-training? 3 sources · 15:40

While pre-training instills broad world knowledge, raw models are not inherently optimized for answering questions or solving tasks. Instruction tuning feeds the model targeted datasets of questions and responses to shape its behavior for problem-solving. Additional steps like reinforcement learning from human feedback further refine the outputs by aligning them with human preference.

05 How can developers prime language models to provide higher-quality answers? 2 sources · 22:21

Developers can improve model outputs by supplying custom instructions that act as prepended text guiding the model's persona and reasoning quality. Explicitly instructing the model to think through background context helps combat its tendency to generate overly confident hallucinations. Additionally, because generation happens sequentially token by token, prompting the model to reason longer increases its computational thoroughness.

06 How do I handle multi-turn state with the OpenAI API? 2 sources · 43:33

The OpenAI API is stateless, meaning nothing is stored on the server between requests. To maintain a conversation, you must pass the entire history of messages back in every new API call.

07 How do I handle API rate limits automatically? 2 sources · 44:53

New or free users often hit low request-per-minute limits initially. You can handle this programmatically by writing a retry function that catches rate limit errors, reads the retry duration, and sleeps before calling itself again.

08 How do I enable function calling with OpenAI? 2 sources · 47:12

You pass a list of available tools or functions under the functions keyword argument in the chat completion request. Because you cannot pass raw Python functions directly, you must convert them into JSON schemas using libraries like Pydantic and Python's inspect module.

09 How do I use quantized models to speed up local inference? 2 sources · 1:05:30

Quantized formats like GPTQ optimize models to use lower-precision data formats. This significantly reduces the memory moving around, making inference faster and allowing larger models to run efficiently on standard hardware.

10 Why do I need to match the exact prompt format for instruction-tuned models? 2 sources · 1:08:12

Instruction-tuned models rely on specific prefix tokens and formatting rules established during their fine-tuning process. Failing to replicate this exact prompt structure results in degraded model performance or incorrect behavior.

11 How does retrieval augmented generation fix knowledge cutoffs? 2 sources · 1:11:52

Retrieval augmented generation searches external sources like Wikipedia to find relevant documents for a given query. It then injects this retrieved text directly into the prompt context so the language model can generate an accurate, up-to-date response.

12 How do I fine-tune a model for domain-specific tasks like text-to-SQL? 2 sources · 1:22:19

You can load a domain-specific dataset using the Hugging Face datasets library and train the model using tools like Axolotl. This process modifies model weights to adapt to specialized structures, such as converting natural language questions into database SQL queries.

Section-by-section summary

18 parts

Code-first practical approach to language models

This tutorial provides a hands-on, code-first guide to using and understanding modern language models. It bridges deep learning fundamentals with practical engineering applications using both open-source and OpenAI models.

Language models predict tokens, not whole words

A language model fundamentally predicts the probability of the next token, which can be a whole word, sub-word unit, or punctuation. Tokenizers encode text into numeric lookups in a vocabulary, forming the input basis for these models.

Pre-training compresses world knowledge into parameters

Originating from algorithms like ULMFiT, pre-training forces a neural network to predict missing words across vast corpuses like Wikipedia. To succeed at this, the model must compress deep structural knowledge about the world into its weights.

Fine-tuning and instruction tuning shape raw models

Raw pre-trained models are not inherently useful for answering questions directly without additional steps. Instruction tuning and reinforcement learning from human feedback redirect the model's predictive capabilities toward helpful problem-solving.

GPT-4 outperforms expectations when properly prompted

While academic papers often claim GPT-4 cannot reason, careful testing shows it handles complex logic puzzles successfully. Priming the model with custom instructions and allowing it to generate intermediate reasoning steps drastically improves its output.

Language models hallucinate on self-knowledge and logic traps

Models lack intrinsic awareness of their own architecture, training data, or URLs due to knowledge cutoffs and stateless design. When repeatedly exposed to common trick questions, their training bias overrides logic, leading to persistent errors.

Advanced data analysis enables OCR and unstructured parsing

Advanced Data Analysis allows models to execute code, perform OCR on uploaded images, and convert messy unstructured web pages into clean markdown tables. However, it remains a tool to assist programmers rather than replace them.

API usage costs scale by token with massive price discrepancies

Using OpenAI via the API incurs costs per token, which roughly equates to words. GPT-3.5 Turbo is exponentially cheaper than GPT-4, making it ideal for prototyping and high-volume tasks before stepping up to GPT-4.

Managing multi-turn state and API rate limits

Because the API is stateless, conversation history must be resent on every turn. Developers must also implement retry logic to handle rate limits encountered during automated loops.

Building a code interpreter with function calling

OpenAI's function calling feature allows models to request tool execution based on JSON schemas. By inspecting Python functions and parsing model outputs, developers can safely build custom execution loops like local code interpreters.

Evaluating hardware options for local LLMs

Running models locally requires understanding GPU memory constraints and bandwidth. While NVIDIA cards remain the industry standard for performance, high-memory Apple Silicon Macs offer a viable alternative for inference.

Navigating open source models on Hugging Face

Hugging Face hosts a vast ecosystem of pre-trained and fine-tuned models. Leaderboards help identify top performers, though benchmark metrics do not always align with real-world task suitability.

Generating text with local language models

Using the Transformers library, developers can load raw models and write custom generation loops. Different floating-point precisions and quantization methods trade off between memory usage and generation speed.

Matching exact prompt formats for instruction-tuned models

Instruction-tuned models like Llama 2 variants require strict adherence to their specific prompt formatting templates. Failing to match the training prompt structure leads to degraded model performance and hallucinations.

Overcoming knowledge cutoffs with RAG

Retrieval-Augmented Generation bridges the gap between static model training and current data by injecting relevant external documents directly into the prompt context.

Finding relevant context using vector embeddings

Sentence transformers convert text into vector embeddings to measure semantic similarity. This enables systems to automatically select the most relevant source documents from a knowledge base before querying the LLM.

Fine-tuning models for domain-specific tasks

Fine-tuning adapts a base model's behavior for specialized tasks, such as translating natural language into SQL queries. Tools like Axolotl simplify the training configuration and execution process on consumer hardware.

Running models locally on Apple Silicon and CPUs

Frameworks like MLC and llama.cpp allow efficient local execution of quantized models across diverse hardware including Macs and mobile devices. Engaging with developer communities helps navigate the rapidly changing ecosystem.

0:00 / 1:31:13
k play/pause · f fullscreen · m mute
n next · p previous clip · t highlights/full
< > slower/faster · / search what was said
  • Tokenization1× · first 5:06

    The process of converting strings into numeric token IDs that map to a model vocabulary.

  • Pre-training11× · first 7:01

    Initial training phase where a neural network learns to predict the next word across massive text corpora.

  • Instruction tuning7× · first 12:51

    A fine-tuning approach using question-and-answer datasets to orient raw language models toward solving tasks.

  • Pydantic1× · first 48:01

    A Python library used alongside inspection to automatically generate JSON schemas for OpenAI function calling.

  • GPTQ5× · first 1:05:36

    A quantization method optimized for running low-precision language models efficiently.

  • Retrieval Augmented Generation3× · first 1:11:43

    A technique that supplies external documents into the prompt context to ground model answers.

  • Axolotl2× · first 1:23:27

    An open-source tool used for streamlining the fine-tuning of language models.