AI Logic

Meta-Learning and Few-Shot Learning

Reptile

Updated:

Training flow of Reptile. The left shows the flow of sampling tasks from a shared initialization φ and moving the initialization toward the weights trained for k steps on each task; the right shows the inner loop running k steps of SGD or Adam on the task data, how φ moves in parameter space toward the average of the weights after k steps toward each task's optimum, and how it is used by training on a new task's support set and classifying the query

Background and Overview

Reptile is a meta-learning method that learns an initialization of the weights able to adapt quickly to new tasks by gradually moving a shared initialization toward the weights obtained after a few training steps on each task. It was proposed in 2018 by Nichol, Achiam, and Schulman at OpenAI.

Its goal is the same as MAML: find "a starting point that fits any task well after only a few steps of gradient descent on a small amount of data." However, MAML computes "the gradient of a gradient" (second-order derivatives) in its outer update, which makes computation and memory expensive. Reptile uses only first-order gradients. It runs ordinary SGD or Adam for a few steps on each task and uses the difference between the resulting weights and the initialization directly as the direction for updating the initialization.

As an analogy, picture actually walking a little way toward several towns (tasks) and gradually moving your home (the initialization) in the direction you walked. After many repetitions, your home settles at a place close to every town.

On 5-way classification on miniImageNet in the paper, with the setting that processes the test data all at once (transductive), it reached 49.97% in 1-shot and 65.99% in 5-shot, on par with or better than MAML (48.70%, 63.11%).

Training Procedure (Inner and Outer Loops)

Like MAML, Reptile's training consists of two nested loops. Following Algorithm 1 of the paper and Eq. (5), which uses multiple tasks at once, it proceeds in this order.

  1. Prepare the initial weights ϕ\phi.
  2. Sample nn tasks τi\tau_i from the task distribution (n=1n = 1 is fine).
  3. For each task, start from ϕ\phi and run SGD or Adam for kk steps on that task's data to obtain the weights ϕ~i\tilde{\phi}_i (the inner loop).
  4. Move the initialization toward the trained weights (the outer update).
  5. Repeat steps 2–4.

In formulas, steps 3 and 4 are as follows.

ϕ~i=Uτik(ϕ),ϕ←ϕ+ϵ 1n∑i=1n(ϕ~i−ϕ)\tilde{\phi}_i = U^k_{\tau_i}(\phi), \qquad \phi \leftarrow \phi + \epsilon \, \frac{1}{n} \sum_{i=1}^{n} \bigl(\tilde{\phi}_i - \phi\bigr)

UτkU^k_{\tau} is the operation "update kk times on the data of task τ\tau," and ϵ\epsilon is the size of the outer update. ϕ−ϕ~\phi - \tilde{\phi} can also be treated as a gradient and passed to an optimizer such as Adam. The right side of the figure at the top shows the initialization ϕ\phi moving toward the average of the weights after kk steps toward each task's optimum.

The first-order approximation of MAML (FOMAML) needs to split each task's data into "training data for the inner update" and "evaluation data for computing the outer gradient." Reptile needs no such split, because it uses only the weights resulting from training on the task's data.

A Single Step Is Not Meta-Learning

When the inner loop takes a single step (k=1k = 1), ϕ~−ϕ=−α∇ϕLτ(ϕ)\tilde{\phi} - \phi = -\alpha \nabla_\phi L_\tau(\phi), so Reptile's update is the same as ordinary SGD on "the average loss over all tasks" (joint training). Reptile works as meta-learning only when it takes multiple steps, k≥2k \geq 2. In the paper's sine-wave regression example, the phases vary, so the average function over all tasks is 0, and joint training yields only a useless initialization that "always outputs 0." From the initialization learned by Reptile, on the other hand, just 32 steps of training on 10 data points reproduced the shape of the wave well.

Why It Works (Gradient Inner Products and Taylor Expansion)

The paper explains why Reptile works well from two viewpoints.

Encouraging Generalization Within a Task

Taylor-expanding the gradients of the inner updates and keeping terms up to first order in the learning rate α\alpha, the expected updates of MAML, FOMAML, and Reptile are all combinations of the following two kinds of terms (for two inner steps).

  • AvgGrad: The gradient of the average task loss Eτ,1[gˉ1]\mathbb{E}_{\tau,1}[\bar{g}_1]. This term pushes toward the minimum of joint training.
  • AvgGradInner: Eτ,1,2[Hˉ2gˉ1]\mathbb{E}_{\tau,1,2}[\bar{H}_2 \bar{g}_1], which equals half the gradient of the inner product gˉ1⋅gˉ2\bar{g}_1 \cdot \bar{g}_2 of gradients from different minibatches of the same task. Moving opposite to this term shifts the weights so that within the same task, training on one minibatch also lowers the loss on another minibatch.
E[gMAML]=AvgGrad−2α AvgGradInner,E[gFOMAML]=AvgGrad−α AvgGradInner,E[gReptile]=2 AvgGrad−α AvgGradInner\mathbb{E}[g_{\mathrm{MAML}}] = \mathrm{AvgGrad} - 2\alpha\,\mathrm{AvgGradInner}, \quad \mathbb{E}[g_{\mathrm{FOMAML}}] = \mathrm{AvgGrad} - \alpha\,\mathrm{AvgGradInner}, \quad \mathbb{E}[g_{\mathrm{Reptile}}] = 2\,\mathrm{AvgGrad} - \alpha\,\mathrm{AvgGradInner}

(All omit O(α2)O(\alpha^2) terms.) This shows that even though Reptile computes no second-order derivatives, running SGD while switching minibatches in turn naturally includes the same kind of second-order term as MAML. The weight of AvgGradInner is in the order MAML > FOMAML > Reptile, but in all of them it grows in proportion to the learning rate α\alpha and the number of steps kk.

Finding a Point Close to Every Task's Optimum

The other explanation is one the paper itself notes is "not rigorous." Let Wτ\mathcal{W}_\tau be the set of optimal weights for task τ\tau, and D(ϕ,Wτ)D(\phi, \mathcal{W}_\tau) the Euclidean distance to it. An initialization close to the optima of all tasks is a point that minimizes the following.

min⁡ϕ  Eτ[12D(ϕ,Wτ)2]\min_\phi \; \mathbb{E}_\tau \Bigl[ \tfrac{1}{2} D(\phi, \mathcal{W}_\tau)^2 \Bigr]

The gradient of this objective is ϕ−PWτ(ϕ)\phi - P_{\mathcal{W}_\tau}(\phi) (where PP is the projection onto the nearest optimum), so one SGD step on a single task gives ϕ←ϕ−ϵ(ϕ−PWτ(ϕ))\phi \leftarrow \phi - \epsilon(\phi - P_{\mathcal{W}_\tau}(\phi)). Since the projection cannot be computed directly, Reptile's update substitutes "the weights after kk training steps" ϕ~\tilde{\phi} for it.

Experimental Results

For few-shot classification, it uses the same convolutional network and data preprocessing as MAML. The inner loop is Adam (with momentum β1=0\beta_1 = 0), the outer loop is plain SGD, and the outer update size is decreased linearly to 0. The main settings in the paper are as follows.

SettingOmniglot 5-wayOmniglot 20-wayminiImageNet
Inner Adam learning rate0.0010.00050.001
Inner minibatch / steps10 / 520 / 1010 / 8
Images per class during training101015
Meta-batch (number of tasks nn) / outer updates5 / 100K5 / 200K5 / 100K
Inner steps at evaluation505050

The 5-way accuracies on miniImageNet are as follows (MAML and FOMAML figures are from the MAML paper).

Method (miniImageNet)1-shot5-shot
MAML (transductive)48.70 ± 1.84%63.11 ± 0.92%
FOMAML (transductive)48.07 ± 1.75%63.15 ± 0.91%
Reptile47.07 ± 0.26%62.74 ± 0.37%
Reptile (transductive)49.97 ± 0.32%65.99 ± 0.58%

The accuracies on Omniglot are as follows.

Method (Omniglot)5-way 1-shot5-way 5-shot20-way 1-shot20-way 5-shot
MAML (transductive)98.7 ± 0.4%99.9 ± 0.1%95.8 ± 0.3%98.9 ± 0.2%
FOMAML (transductive)98.3 ± 0.5%99.2 ± 0.2%89.4 ± 0.5%97.9 ± 0.1%
Reptile95.39 ± 0.09%98.90 ± 0.10%88.14 ± 0.15%96.65 ± 0.33%
Reptile (transductive)97.68 ± 0.04%99.48 ± 0.06%89.43 ± 0.14%97.12 ± 0.32%

The three methods perform nearly the same; Reptile is slightly better on miniImageNet and slightly worse on Omniglot.

"Transductive" here means the setting in which the test queries are classified together at once and the batch normalization statistics are shared among the queries. In the non-transductive setting, the statistics are computed from all the training examples plus a single query. Accuracy is higher in the transductive setting for every method, and the paper cautions that the MAML paper's evaluation was also transductive.

The paper further shows that using more minibatches in the inner loop improves training for every combination, and that when the number of inner steps or the minibatch size is varied, Reptile degrades less than FOMAML (in the case where the last minibatch overlaps the earlier ones).

Caveats in Practice

With only one inner step, it reduces to plain joint training. Reptile works as meta-learning only when the inner loop takes multiple steps (multiple minibatches). In the paper's experiments as well, the inner loop takes 5–10 steps, and 50 steps at evaluation.

  • A setting without momentum in the inner optimizer is recommended. The paper reports that setting Adam's β1\beta_1 to 0 performed better in every experiment, and explains that this is consistent with the Taylor expansion analysis (it matters that successive steps come from different minibatches).
  • Numbers change with the evaluation setting. Whether it is transductive (whether the batch normalization statistics are shared among queries) makes a difference of several points in accuracy. Match this setting when comparing methods.
  • Be careful with Adam's internal state. In the paper, the inner Adam statistics are kept and reused without resetting during training, while at evaluation they are saved and reset so that no information leaks.
  • It has not yet succeeded in reinforcement learning. The paper states that in reinforcement learning, joint training is a strong baseline and Reptile has produced only negative results.
  • Since there is no need to keep the computation graph of the inner updates, memory stays nearly constant regardless of the number of inner steps. Increasing the number of steps does not increase backpropagation memory as it does with MAML.

Comparison with Other Meta-Learning Methods

The table compares methods that learn an initialization of the weights and methods that classify by feature similarity, from the same viewpoints.

MethodWhat is learnedQuantity used for the outer updateSplitting task dataStrengthsWeaknesses
ReptileWeight initializationDifference between the weights after kk steps and the initialization, ϕ~−ϕ\tilde{\phi} - \phiNot neededShort implementation; only first-order gradients, and memory independent of the number of stepsReduces to joint training with k=1k = 1; no successes in reinforcement learning
MAMLWeight initializationGradient including second-order derivativesSplit into training and evaluationDirectly optimizes adaptation with few steps; also usable for regression and reinforcement learningSecond-order derivatives make computation and memory heavy
FOMAML (first-order approximation of MAML)Weight initializationGradient on the evaluation data computed at the trained weightsSplit into training and evaluationNo second-order derivatives neededPerformance drops if the split is wrong (if the data overlap)
Prototypical NetworksFunction mapping images to featuresNot used (trained with the episode's classification loss)Split into support set and queriesFast, with no gradient computation on new tasksClassification only

Rough guidelines for choosing are as follows.

  • When you want to try learning a weight initialization with as little computation and as short an implementation as possible, Reptile is a good fit. It can be used just by adding the outer update to existing training code.
  • When you want to push adaptation performance with few steps to the limit, or want to use it for reinforcement learning, consider MAML.
  • For classification only, when you do not want gradient computation at test time, methods that classify by feature similarity, such as Prototypical Networks, Matching Networks, and Relation Network, are a good fit.

PyTorch example

Show code
python
import copy
import math
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm

"""
Train Reptile on sine-wave regression (Chapter 4 of the paper).
Move the initialization φ toward the weights φ̃ trained for k steps on each task: φ ← φ + ε(φ̃ − φ)
"""

# Hyperparameters (network shape, amplitude/phase ranges, and number of points follow Chapter 4 of the paper; the rest are examples)
K = 10                # number of points seen per task
inner_lr = 0.02       # learning rate α of the inner SGD (example)
inner_steps = 32      # number of inner steps k (Figure 1 of the paper adapts in 32 steps)
outer_lr = 0.1        # outer update size ε (example; decreased linearly to 0)
meta_steps = 30000    # number of outer updates (example)

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


def sample_task():
  """Pick one sine wave with amplitude in [0.1, 5.0] and phase in [0, 2π], and return a function that generates data"""
  amp = random.uniform(0.1, 5.0)
  phase = random.uniform(0, 2 * 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


# 1 → 64 → 64 → 1 MLP (same shape as Figure 1 of the paper; the activation is not stated in the paper, so Tanh is an example)
model = nn.Sequential(
  nn.Linear(1, 64), nn.Tanh(),
  nn.Linear(64, 64), nn.Tanh(),
  nn.Linear(64, 1),
).to(device)


def train_on_task(net, x, y, steps):
  """Inner loop: φ̃ = U^k_τ(φ). Ordinary SGD for `steps` steps (first-order gradients only)"""
  opt = torch.optim.SGD(net.parameters(), lr=inner_lr)
  for _ in range(steps):
    loss = F.mse_loss(net(x), y)
    opt.zero_grad()
    loss.backward()
    opt.step()


for step in tqdm(range(meta_steps)):
  sample = sample_task()
  x, y = sample(K)                          # no need to split into training and evaluation
  task_model = copy.deepcopy(model)         # start from φ
  train_on_task(task_model, x, y, inner_steps)

  # Outer update: φ ← φ + ε(φ̃ − φ). ε is decreased linearly to 0 (Appendix A of the paper)
  eps = outer_lr * (1 - step / meta_steps)
  with torch.no_grad():
    for p, p_task in zip(model.parameters(), task_model.parameters()):
      p.add_(eps * (p_task - p))

# Evaluation: train on a new task using only K points and measure the error over the whole interval
errors_before, errors_after = [], []
for _ in range(100):
  sample = sample_task()
  x_train, y_train = sample(K)
  x_test, y_test = sample(100)
  task_model = copy.deepcopy(model)
  with torch.no_grad():
    errors_before.append(F.mse_loss(task_model(x_test), y_test).item())
  train_on_task(task_model, x_train, y_train, inner_steps)
  with torch.no_grad():
    errors_after.append(F.mse_loss(task_model(x_test), y_test).item())

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

FAQ

Q. Is Reptile the same as the first-order approximation of MAML (FOMAML)?
A.

No. FOMAML uses the gradient on the evaluation data computed at the trained weights for the outer update, so it needs to split each task's data into training and evaluation sets. Reptile uses the difference ϕ~−ϕ\tilde{\phi} - \phi between the trained weights and the initialization, and does not split the data. With two inner steps, FOMAML uses only the gradient of the second step, while Reptile uses the sum of the gradients of the first and second steps.

Q. How should ε (the outer update size) be chosen?
A.

In the paper's few-shot classification experiments, ϵ\epsilon starts at 1.01.0 and is decreased linearly so that it reaches 0 at the end of training. ϵ=1\epsilon = 1 means "replace the initialization with the trained weights themselves," but since the update averages over multiple tasks (a meta-batch of 5), the actual movement is the average of the directions of the individual tasks.

Q. How is it used after training is finished?
A.

The same way as MAML. On the small amount of data for a new task (the support set), run SGD or Adam for a few to a few dozen steps from the learned initialization, and predict the queries with the resulting weights. In the paper's classification experiments, 50 training steps are taken at evaluation.

References

  1. Nichol, A., Achiam, J., & Schulman, J. (2018). On First-Order Meta-Learning Algorithms. arXiv:1803.02999.
  2. 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.