LLM Usage
In-Context Learning β Teaching LLMs New Tasks Without Training
In-context learning is one of the most remarkable emergent capabilities of LLMsβthe ability to learn new tasks from examples provided in the prompt. This guide explores what ICL is, why it works, and how to use it effectively.
- No Training Required β Adapt models to new tasks purely through prompts
- Bayesian Inference β ICL implicitly performs posterior inference over task hypotheses
- Production Deployment β Balance example count, latency, and cost for real-world use
The most elegant learning happens without changing a single weight.
In-Context Learning
In-context learning (ICL) is one of the most remarkable emergent capabilities of LLMs. This tutorial explores what ICL is, why it works, and how to use it effectively.
How ICL Works
The Bayesian Inference Hypothesis
The model effectively performs Bayesian inference over task hypotheses, using the in-context examples to update its beliefs about which task is being performed.
The Task Vector Hypothesis
The Grokking Hypothesis
Impact of Example Ordering
The order of in-context examples significantly affects performance:
Ordering Strategies
- Random ordering: Baseline, moderate performance
- Similarity-based: Most similar examples last (best average)
- Label-balanced: Equal representation of each class
- Difficulty-based: Easy examples first, hard examples last
Impact of Example Selection
Selection Strategies
- Random: No selection bias, but may include irrelevant examples
- Top-k retrieval: Select k most similar examples from a pool
- Diverse selection: Balance similarity with diversity
- Label-aware: Ensure balanced label distribution in selected examples
ICL vs Fine-tuning
| Aspect | ICL | Fine-tuning |
|---|---|---|
| Data required | 2-32 examples | 100-10,000+ examples |
| Compute | Forward pass only | Gradient updates |
| Task switching | Change prompt | Retrain model |
| Performance | 80-95% of fine-tuning | 100% (baseline) |
| Latency | Higher (longer prompts) | Lower (shorter prompts) |
| Knowledge access | Full pre-trained knowledge | May forget pre-trained knowledge |
Practical ICL Implementation
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
# Few-shot examples
examples = [
("This movie was fantastic!", "Positive"),
("Terrible waste of time.", "Negative"),
("The food was okay.", "Neutral"),
]
def build_icl_prompt(test_input, examples):
prompt = "Classify the sentiment of each review.\n\n"
for text, label in examples:
prompt += f"Review: \"{text}\" -> {label}\n"
prompt += f"Review: \"{test_input}\" -> "
return prompt
test = "Absolutely loved every minute of it!"
prompt = build_icl_prompt(test, examples)
inputs = tokenizer(prompt, return_tensors="pt")
output = model.generate(**inputs, max_new_tokens=10, temperature=0.0)
response = tokenizer.decode(output[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
print(f"Prediction: {response}") # Expected: Positive
Practice Exercises
- Empirical: Test ICL on a 3-class classification task with 1, 2, 4, 8, and 16 examples. Plot accuracy vs number of examples.
- Ordering: Compare random, similarity-based, and reverse ordering of examples. Which is most robust?
- Selection: Implement a retrieval-based example selector using sentence embeddings. Compare with random selection.
- Theory: Explain why ICL works for decoder-only models but not for encoder-only models like BERT.
Theoretical Foundations
ICL as Gradient Descent
Recent research suggests that transformer attention mechanisms can implicitly perform gradient descent during the forward pass. The attention computation effectively computes a linear regression over the in-context examples, updating the model internal representations without explicit parameter updates.
Mechanistic Interpretability of ICL
Mechanistic interpretability studies have identified specific circuits responsible for ICL. The induction head circuit, composed of two attention heads, learns to perform pattern completion by copying from previous contexts. This circuit emerges during training and is essential for few-shot learning.
Limitations of ICL
- Context window limits: ICL is constrained by the maximum sequence length. Long contexts increase latency and cost.
- Distribution shift: ICL performance degrades when test examples differ significantly from the pre-training distribution.
- Instability: Small changes in example ordering or selection can cause large performance swings.
- Limited complexity: ICL struggles with tasks requiring deep reasoning or memorization of complex patterns.
Advanced ICL Techniques
Retrieval-Augmented ICL
Instead of selecting examples randomly, use a retrieval system to find the most relevant in-context examples for each query. This combines the benefits of RAG with ICL, improving accuracy on diverse inputs.
Learned Prompting
Rather than selecting natural examples, learn continuous prompt embeddings that maximize task performance. This is the basis of prefix tuning and prompt tuning methods, which bridge the gap between ICL and fine-tuning.
Task-Aware ICL
Analyze the task structure and design ICL prompts that explicitly communicate the task type, input format, and output format. This reduces ambiguity and improves consistency across diverse inputs.
ICL in Production
When deploying ICL in production, consider:
- Latency: Longer prompts mean slower inference. Balance example count with speed requirements.
- Cost: API calls are priced by token count. Fewer, more relevant examples reduce cost.
- Consistency: Use deterministic example selection for reproducible outputs.
- Fallback: Have a fine-tuned model as fallback when ICL performance is insufficient.
What to Learn Next
-> Chain-of-Thought Reasoning Making LLMs think step by step for complex reasoning problems.
-> Prompt Engineering Getting the most out of language models through effective input design.
-> RAG System Design Building production-ready retrieval systems for grounded generation.
-> Retrieval-Augmented Generation Combining LLMs with external knowledge for accurate, cited answers.
-> LLM Agent Frameworks Building autonomous agents that reason, plan, and act.
-> Building Production LLM Apps From prototype to production: deploying LLMs at scale.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type β Always start by categorizing the problem
- Incorrect formula application β Verify the formula applies to your specific case
- Unit errors β Always check units are consistent throughout
- Sign errors β Pay careful attention to positive and negative values
- Rounding too early β Keep full precision until the final answer
- Forgetting constraints β Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic β Build on the foundation laid here
- Next Topic β See how this concept extends to more advanced material
- Practice Problems β Additional exercises with solutions
- Video Explanation β Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions