πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

In-Context Learning

InferenceICL🟒 Free Lesson

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

  1. Random ordering: Baseline, moderate performance
  2. Similarity-based: Most similar examples last (best average)
  3. Label-balanced: Equal representation of each class
  4. 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

AspectICLFine-tuning
Data required2-32 examples100-10,000+ examples
ComputeForward pass onlyGradient updates
Task switchingChange promptRetrain model
Performance80-95% of fine-tuning100% (baseline)
LatencyHigher (longer prompts)Lower (shorter prompts)
Knowledge accessFull pre-trained knowledgeMay forget pre-trained knowledge

Practical ICL Implementation

python
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

  1. Empirical: Test ICL on a 3-class classification task with 1, 2, 4, 8, and 16 examples. Plot accuracy vs number of examples.
  2. Ordering: Compare random, similarity-based, and reverse ordering of examples. Which is most robust?
  3. Selection: Implement a retrieval-based example selector using sentence embeddings. Compare with random selection.
  4. 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

  1. Context window limits: ICL is constrained by the maximum sequence length. Long contexts increase latency and cost.
  2. Distribution shift: ICL performance degrades when test examples differ significantly from the pre-training distribution.
  3. Instability: Small changes in example ordering or selection can cause large performance swings.
  4. 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

  1. Misidentifying the problem type β€” Always start by categorizing the problem
  2. Incorrect formula application β€” Verify the formula applies to your specific case
  3. Unit errors β€” Always check units are consistent throughout
  4. Sign errors β€” Pay careful attention to positive and negative values
  5. Rounding too early β€” Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert LLM Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement