AI Logic

Meta-Learning and Few-Shot Learning

MAML

Updated:

Training flow of MAML. The left side shows the flow of sampling tasks from the shared initialization θ, adapting to each task, computing the loss on validation data, and correcting θ with the outer update. The right side shows the per-task inner update and evaluation on validation data, along with a parameter-space view of inner updates taking one step toward each task's optimum and the direction of the outer update

Background and Overview

MAML (Model-Agnostic Meta-Learning) is a meta-learning method that learns a model's "initial weights" so that new tasks can be learned with little data and only a few gradient updates. It was proposed in 2017 by Finn, Abbeel, and Levine at UC Berkeley.

In ordinary training, the weights are tuned from scratch on a large amount of data for one task (for example, "tell dogs from cats"). In practice, however, there are often tasks with only a handful of examples (few-shot learning), such as "learn a new character type from just five samples." Training directly on so little data leads to overfitting.

MAML experiences many similar tasks and looks for a starting point from which a few steps of gradient descent work well for any task. As an analogy, it is like a person who travels to many different towns choosing to live near the station so that every town is quickly reachable. The station (initialization) itself is not the best place for any one town (task), but a short move from it reaches anywhere.

"Model-Agnostic" in the name means that it can be used without changing the architecture for any model trainable by gradient descent. No new parameters or special components need to be added, and the paper applies the same idea to three kinds of problems: classification, regression, and reinforcement learning.

In the paper's image classification experiments, accuracy on the "pick among 5 classes" task on Omniglot, a dataset of character images, was 98.7% with one sample (1-shot) and 99.9% with five samples (5-shot). On the harder 5-class classification of MiniImagenet, it reached 48.70% in 1-shot and 63.11% in 5-shot, surpassing the methods of the time (Matching Networks and a method that learns how to update with an LSTM).

Training Procedure (Inner and Outer Loops)

MAML training consists of two nested loops. The inner loop "moves the weights a little to fit each task," and the outer loop "corrects the starting weights so that the performance after the move improves"; these are repeated. For supervised learning, following Algorithm 2 of the paper, it proceeds in the following order.

  1. Initialize the weights θ\theta randomly.
  2. Sample several tasks Ti\mathcal{T}_i (a meta-batch) from the task distribution p(T)p(\mathcal{T}).
  3. For each task, compute the gradient of the loss on KK examples Di\mathcal{D}_i and move the weights by gradient descent (the inner update).
    • The weights after the move, θi′\theta'_i, are specific to that task. θ\theta itself is not changed.
  4. Draw separate data Di′\mathcal{D}'_i from the same task and compute the loss of the model using θi′\theta'_i.
  5. Sum the losses from step 4 over all tasks and update θ\theta to reduce it (the outer update).
  6. Repeat steps 2–5.

Written as equations, the updates in steps 3 and 5 are as follows.

θi′=θ−α∇θLTi(fθ),θ←θ−β∇θ∑Ti∼p(T)LTi(fθi′)\theta'_i = \theta - \alpha \nabla_\theta \mathcal{L}_{\mathcal{T}_i}(f_\theta), \qquad \theta \leftarrow \theta - \beta \nabla_\theta \sum_{\mathcal{T}_i \sim p(\mathcal{T})} \mathcal{L}_{\mathcal{T}_i}(f_{\theta'_i})

Here, fθf_\theta is the model with weights θ\theta, LTi\mathcal{L}_{\mathcal{T}_i} is the loss for task Ti\mathcal{T}_i (mean squared error for regression, cross-entropy for classification), α\alpha is the learning rate of the inner update, and β\beta is the learning rate of the outer update. The inner update may be one step or several.

The key point is that the outer-update loss is computed with the updated θi′\theta'_i, not with θ\theta before the update. In other words, MAML moves θ\theta to improve not "the current performance" but "the performance after a little training." Also, because evaluation uses data Di′\mathcal{D}'_i separate from the data Di\mathcal{D}_i used in the inner loop, starting points that overfit to small data are unlikely to be chosen.

After training, it is used the same way as ordinary fine-tuning: just take a few gradient descent steps from the learned θ\theta on the small data of a new task. The difference is that the starting point has been deliberately chosen so that those few steps work well.

Second-Order Derivatives and the First-Order Approximation

The gradient of the outer update, ∇θL(fθi′)\nabla_\theta \mathcal{L}(f_{\theta'_i}), is a "gradient of a gradient," because θi′\theta'_i already contains a gradient. With a single inner step, the chain rule gives the following.

∇θL(fθi′)=(I−α∇θ2LTi(fθ)) ∇θ′L(fθi′)\nabla_\theta \mathcal{L}(f_{\theta'_i}) = \bigl(I - \alpha \nabla_\theta^2 \mathcal{L}_{\mathcal{T}_i}(f_\theta)\bigr)\, \nabla_{\theta'} \mathcal{L}(f_{\theta'_i})

II is the identity matrix, and ∇θ2L\nabla_\theta^2 \mathcal{L} is the matrix of second derivatives of the loss (the Hessian). The Hessian itself need not be formed; deep learning libraries can compute Hessian-vector products by running backpropagation one more time. Even so, the entire computation of the inner update must be retained, which increases computation and memory.

The paper therefore also tries a first-order approximation that drops the second-derivative term (called first-order MAML, or FOMAML). It treats ∇θ2L\nabla_\theta^2 \mathcal{L} in the equation above as 0 and uses the gradient computed at the updated weights θi′\theta'_i directly to update θ\theta.

MethodMiniImagenet 5-way 1-shotMiniImagenet 5-way 5-shotComputation
MAML (with second-order derivatives)48.70%63.11%One extra backpropagation for the Hessian-vector product
First-order approximation of MAML48.07%63.15%No second-order derivatives; about 33% faster in the paper's experiments

Accuracy barely changed. The paper suggests that part of the reason is that ReLU networks are locally almost linear, so second derivatives are often close to 0. A practical order is to try the first-order approximation first and use second-order derivatives only if needed.

In MAML, the more inner steps are taken, the more computation must be retained and backpropagated, so memory and computation time grow in proportion to the number of steps. Training also tends to become unstable depending on the inner learning rate α\alpha, the number of steps, and the meta-batch size, and the paper changes these values for each dataset (table below).

Settings in the Paper and Scope of Application

The main settings in the paper are as follows. NN-way KK-shot denotes the task of "classifying among NN classes after seeing KK samples per class."

ExperimentModelInner update (training)Inner update (evaluation)Meta-batch
Sinusoid regression (K=10K = 10)MLP with 2 hidden layers of 40, ReLU1 step, α=0.01\alpha = 0.01Several steps on the same KK points—
Omniglot 5-way4 convolutional layers (3×3, 64 channels)1 step, α=0.4\alpha = 0.43 steps, α=0.4\alpha = 0.432 tasks
Omniglot 20-waySame as above5 steps, α=0.1\alpha = 0.15 steps, α=0.1\alpha = 0.116 tasks
MiniImagenet 5-way4 convolutional layers (32 channels)5 steps, α=0.01\alpha = 0.0110 steps, α=0.01\alpha = 0.014 tasks for 1-shot, 2 for 5-shot

In sinusoid regression, each task is a sine wave with a different amplitude (0.1–5.0) and phase (0–π\pi), to be predicted from only 10 points. This experiment uses Adam to optimize the outer update. On MiniImagenet, the outer-update loss is computed on 15 separate images per class.

Reinforcement learning uses the same two nested loops. The inner update computes a policy gradient from trials (rollouts) collected on the task and moves the policy, and the outer update evaluates on trials collected again with the updated policy. The paper shows adaptation to a new goal in 2–3 updates on 2D navigation tasks with different goal positions and on simulated legged-robot tasks with different target speeds and directions.

Comparison with Other Meta-Learning Methods

Meta-learning for few-shot learning can be broadly divided by "what is learned."

MethodWhat is learnedHow it adapts to a new taskSuitable conditions
MAMLInitial weightsA few gradient descent steps on little dataUse beyond classification (regression, reinforcement learning); no change to the model architecture
ReptileInitial weightsSame as MAML. Training only moves the initialization toward the adapted weights and uses no second-order derivativesUse the MAML idea with lighter computation
Matching NetworksA function mapping images to featuresDecide the label by weighting samples by feature similarityClassification without computing gradients for adaptation
Prototypical NetworksA function mapping images to featuresPick the class whose mean sample feature (prototype) is closestClassification with a simple, fast method
Relation NetworkA feature function and a similarity functionScore sample–query pairs with a learned functionClassification where the similarity measure is also learned from data

Methods that "classify by feature similarity," such as Matching Networks, Prototypical Networks, and Relation Network, are fast because no gradients are computed on new tasks, and they are widely used for classification. MAML's strength, on the other hand, is that it can be applied in the same form to classification, regression, and reinforcement learning, as long as the loss can be reduced by gradient descent.

PyTorch example

Show code
python
import math
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.func import functional_call
from tqdm import tqdm

"""
Train MAML on sinusoid regression (Section 5.1 of the paper).
Learn an initialization that can fit sine waves with task-specific amplitude and phase from only K = 10 points
"""

# Hyperparameters (K, α, and the network shape follow the paper)
K = 10                # number of examples seen per task (K-shot)
inner_lr = 0.01       # inner-update learning rate α
meta_lr = 1e-3        # outer-update (Adam) learning rate β
meta_batch = 25       # number of tasks per outer update
meta_steps = 20000    # number of outer updates
first_order = False   # set True for the first-order approximation (FOMAML)

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


def sample_task():
  """Pick a sine wave with amplitude in [0.1, 5.0] and phase in [0, π], and return a function that generates data"""
  amp = random.uniform(0.1, 5.0)
  phase = random.uniform(0, math.pi)
  def sample(n):
    x = torch.empty(n, 1).uniform_(-5.0, 5.0)
    return x.to(device), (amp * torch.sin(x - phase)).to(device)
  return sample


# 2 hidden layers of 40 units, ReLU (as in the paper)
model = nn.Sequential(
  nn.Linear(1, 40), nn.ReLU(),
  nn.Linear(40, 40), nn.ReLU(),
  nn.Linear(40, 1),
).to(device)
meta_optimizer = optim.Adam(model.parameters(), lr=meta_lr)


def adapt(params, x, y, steps, create_graph):
  """Inner update: repeat θ′ = θ − α ∇θ L(f_θ) for `steps` steps"""
  for _ in range(steps):
    loss = F.mse_loss(functional_call(model, params, (x,)), y)
    grads = torch.autograd.grad(loss, list(params.values()), create_graph=create_graph)
    params = {name: p - inner_lr * g for (name, p), g in zip(params.items(), grads)}
  return params


for step in tqdm(range(meta_steps)):
  meta_loss = 0.0
  for _ in range(meta_batch):
    sample = sample_task()
    x_train, y_train = sample(K)   # data D for the inner update
    x_val, y_val = sample(K)       # separate data D′ for the outer update
    # create_graph=True allows backpropagating through the "gradient of the gradient" (second-order derivatives)
    fast = adapt(dict(model.named_parameters()), x_train, y_train, steps=1, create_graph=not first_order)
    meta_loss = meta_loss + F.mse_loss(functional_call(model, fast, (x_val,)), y_val)

  # Outer update: θ ← θ − β ∇θ Σ L(f_θ′)
  meta_optimizer.zero_grad()
  (meta_loss / meta_batch).backward()
  meta_optimizer.step()

# Evaluation: adapt for 10 steps on a new task using only K points, then measure error on 100 points
errors_before, errors_after = [], []
for _ in range(100):
  sample = sample_task()
  x_train, y_train = sample(K)
  x_test, y_test = sample(100)
  params = dict(model.named_parameters())
  fast = adapt(params, x_train, y_train, steps=10, create_graph=False)
  with torch.no_grad():
    errors_before.append(F.mse_loss(functional_call(model, params, (x_test,)), y_test).item())
    errors_after.append(F.mse_loss(functional_call(model, fast, (x_test,)), y_test).item())

print(f"MSE before adaptation: {sum(errors_before) / len(errors_before):.3f}")
print(f"MSE after 10 steps:    {sum(errors_after) / len(errors_after):.3f}")

FAQ

Q. How does MAML differ from ordinary pretraining followed by fine-tuning?
A.

Ordinary pretraining pools the data of all tasks and trains to improve "the current performance." MAML learns an initialization that improves "the performance after" a few gradient descent steps on each task. In the paper's sinusoid regression, a model pretrained on all tasks failed to adapt well even when fine-tuned on a few points, whereas the model trained with MAML could fit the shape of the wave with a few points and a few steps.

Q. Can the inner learning rate α also be learned?
A.

Yes. The paper also states that α may be fixed as a hyperparameter or meta-learned. There are extensions such as Meta-SGD that learn a learning rate for each weight.

Q. Can the tasks used for testing be the same as those used for training?
A.

No. Meta-learning is evaluated on tasks not used in training (for Omniglot and MiniImagenet, classes not used in training). The goal is to adapt to tasks never seen before with little data.

References

  1. Finn, C., Abbeel, P., & Levine, S. (2017). Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks. Proceedings of the 34th International Conference on Machine Learning (ICML), PMLR 70, 1126–1135.
  2. Nichol, A., Achiam, J., & Schulman, J. (2018). On First-Order Meta-Learning Algorithms. arXiv:1803.02999.
  3. Vinyals, O., Blundell, C., Lillicrap, T., Kavukcuoglu, K., & Wierstra, D. (2016). Matching Networks for One Shot Learning. NeurIPS 2016.
  4. Snell, J., Swersky, K., & Zemel, R. (2017). Prototypical Networks for Few-shot Learning. NeurIPS 2017.
  5. Sung, F., Yang, Y., Zhang, L., Xiang, T., Torr, P. H. S., & Hospedales, T. M. (2018). Learning to Compare: Relation Network for Few-Shot Learning. CVPR 2018.
  6. Li, Z., Zhou, F., Chen, F., & Li, H. (2017). Meta-SGD: Learning to Learn Quickly for Few-Shot Learning. arXiv:1707.09835.