Reading material:¶
- Thrun, Sebastian, Explanation-Based Neural Network Learning: A Lifelong Learning Approach, Springer, 1996 (Free only copy through the Purdue Library)
- Thurn: Lifelong Learning Algorithms, Thrun, Sebastian, Pratt, Lorien (Eds.), Learning to Learn, Springer. 1998 (Free only copy through the Purdue Library)
- Machine Learning (book), Tom Michell, 1997. In particular Chapter 2.
What Meta Learning is NOT¶
- Before we talk about what Meta Learning is, let's talk about what it is not
Law of Conservation for Generalization Performance (LCG):
- When taken across all learning tasks, the generalization performance of any learner is equivalent to the performance of random guesses (Schaffer, 1994).
- This is the machine learning translation of the No Free Lunch Theorems for Search of (Macready & Wolpert, 1995).
- (Giraud-Carrier & Provost, 2005) offer a good essay on the topic.
Base-level learning: We begin by defining the term learning. According to (Chapter 1.1., Mitchell, 1997) (and also (Chapter 1.2, Thrun, 1996)), given:
- a task,
- training experience (e.g., a dataset), and
- a performance measure,
a computer program is said to learn if its performance at the task improves with experience.
Meta-level learning (Chapter 1.2, Thrun, 1996): Following Mitchell's definition, we will now define what it means for an algorithm to be capable of learning to learn. Given:
- a family of tasks, $k=1,\ldots, n$
- training experience for each of these tasks (multiple datasets), and
- a family of performance measures (e.g., one for each task),
an algorithm is said to learn to learn if its performance at each task improves with experience and with the number of tasks.
For an algorithm to fit this definition, some kind of transfer of knowledge must occur between multiple tasks that must have a positive impact on expected task performance.
Two Examples of Base-level Learning Inneficiencies¶
An extreme example: Consider two image classification tasks, one in Portuguese and one in English:
- Task 1: Given an object in an image ($\mathbb{R}^{h\times w}$), classify the object in English.
- Task 2: Given an object in an image ($\mathbb{R}^{h\times w}$), classify the object in Portuguese.
- Base-level learning:
- A base-level learner will learn a classifier for the English labels
- Imagine that the true target function is $f^1:\mathbb{R}^{h\times w} \to \mathbb{Y}$
- A base-level learner will learn a classifier for the Portuguese labels
- Imagine that the true target function is $f^2:\mathbb{R}^{h\times w} \to \mathbb{Y}$
- This is inneficient, since the harder task is to map images into (any) language.
- Language to language translation of objects is an easier task.
- A base-level learner will learn a classifier for the English labels
- Meta-level learning:
- The family of tasks $k=1,2$ are image classification in English ($k=1$) and Portuguese ($k=2$).
- Improving our ability to classify images in English ($k=1$) (with more data) should also improve our ability to classify images in Portuguese ($k=2$)
Hypothesis Space (Learning Bias)¶
In neural networks, the hypothesis space is the set of functions obtained by all combinations of parameter and hyperparameter values
For instance, for a $d$-dimensional input $x \in \mathbb{R}^d$ and $C$-dimensional output $\hat{y} \in \mathbb{R}^C$ (e.g., $\hat{y}$ is a probability distribution over $C$ classes), the hypothesis space of feedforward network (MLP) with $L-1$ hidden layers is $$H_\text{MLP} = \{\text{MLP}(W_1,\ldots,W_L) \::\: L \in \mathbb{Z}^+, h_1 \in \mathbb{Z}^+, W_1 \in \mathbb{R}^{d \times h_1}, \ldots, h_{L-1} \in \mathbb{Z}^+, W_L \in \mathbb{R}^{h_{L-1} \times C} \},$$ where $h_k$ is the number of hidden neurons at the $k$-th layer, and $W_k$ is the weight matrix of the $k$-th MLP layer.
Meta-learning and the hypothesis space¶
- Transferring knowledge across learning tasks must make an assumption about the hypothesis space of the tasks.
Figure 2: Meta-level learning-an example. The circles $H_0, H_1,\ldots$ represent different base-level hypothesis spaces. The true target functions are drawn from $F$.
Figure from Thurn: Lifelong Learning Algorithms, in Thrun, Sebastian, Pratt, Lorien (Eds.), Learning to Learn, 1998 Springer.
- Consider a set of $n$ related tasks where the true target functions $f^1,\ldots,f^n$ are randomly drawn from a set of functions $F$.
- Suppose the meta learner has seen the data $D^k = \{(x_i, f^k(x_i))\}_{i=1}^{N_k}$ of tasks $k=1,\ldots,(n-1)$.
- The meta learner needs to choose the hypothesis spaces $\{H_0, H_1 , \ldots , H_4\}$ in the figure prior to the arrival of the training examples for the n-th target function $f^n$.
- Of the hypothesis spaces shown in the figure above, $H_4$ is superior to all others.
- $H_0$ is more appropriate than $H_2$ and $H_3$ , since it includes $F$ completely while the latter ones do not.
- $H_4$ is also more appropriate than $H_0$ and $H_1$ , since it is more specific than those.
Consequently, if the meta learner is able to start learning task $n$ using $H_4$, it will likely perform better than if it started with $H_0$ or $H_1$.
The goal of (sequential) meta learning is to use the tasks $k=1,\ldots,n-1$ to improve the learning of task $n$.
Tasks and target function space¶
- We assume that the learner only encounters suppervised learning tasks, which are defined over a $d$-dimensional feature space, say, $\mathbb{R}^d$.
- To simplify, assume a binary (supervised learning) classification task with labels 1 and 0
- The k-th task (with $k = 1 , \ldots , n$) involves learning the function $f^k:\mathbb{R}^d \to \{0,1\}$.
- A similar definition can be given for regression tasks (we will not cover regression).
- The training data for the $k$-th learning task is $$ D^k = \{(x^k_i, f^k(x_i))\}_{i=1}^{N^k},$$ where $x^k$ denotes the $k$-th input and $f^k(x_i)$ its binary label.
Important Remarks¶
- Note that just merging the data $D^1,\ldots,D^{n-1}$ with $D^{n}$ and learning a single classifier is a bad idea, since $f^k, f^n \in. F$ does not necessarily mean they have similar outputs.
- For instance, $f^1(x) = 1$ if $x$ a dog image while $f^n(x) = 1$ if $x$ is a cat image.
- Another example: $f^1(x) = 1$ if $x$ a dog image while $f^n(x) = 1$ if $x$ is a black animal.
- However, we still want to use $D^1,\ldots,D^{n-1}$ with task $n$ dataset $D^n$ to support learning a hypothesis $h\in H$ such that $h \approx f^n$.
- For this reason, the datasets $D^1,\ldots,D^{n-1}$ are called the support sets of task $n$.
- The functions $f^1, f^2, \ldots, f^n$ are drawn from a family of functions, denoted by $F$. The nature of $F$ is not completely known in the beginning of meta learning.
- Each support set $D^k$, $k=1,\ldots,n$, establishes a constraint in the hypothesis space at the meta-level.
- However, $D^k$ usually does not specify $f^k$ uniquely.
- Instead, it provides a potentially small and noisy set of input-output examples of $f^k$.
- Support sets may vary in size; thus, training examples at the meta-level may vary in length.
- Each support set $D^k$ provides a positive example for the "meta-concept" $F$ (the target function space).
- Negative examples are not available at the meta-level.
Terminology¶
Following the terminology in Rendell et al. (1987), we will refer to the problem of learning a hypothesis space bias as the meta-level learning problem.
- Base-learning: The conventional learning problem, which involves learning functions, will be referred to as the base-level learning problem.
- Training examples at the base-level for task $n$ is the dataset $D^n$.
- The base-level learner is concerned with selecting a function $h$ that approximates $f^n$ from a set of hypotheses $h \in H$.
- Given a particular target function, $f^n \in F$, the ultimate goal of a base learner in the n-th learning task is to minimize the prediction error for $f^n$.
- Recognizing $F$ is a secondary goal.
- It is only useful insofar it supports learning $f^n$.
- Meta-learning: The meta-level involves learning an entire space of functions, since its result is an entire base-level hypothesis space $H$.
- Consequently, a meta-level hypothesis space is a set of sets of functions, each of which is a potential base-level hypothesis space.
- Training examples at the meta-level are support sets, $D^1,\ldots,D^n$, each one is a dataset for a different task.
Meta-learning and Representation learning¶
How can one use the support sets $D^1,\ldots,D^{n-1}$ to improve generalization for the $n$-th task?
- We first need to revisit what representation learning (deep learning) is all about.
(Detour) Structural Causal Model (SCM)¶
A Structural Causal Model (SCM) gives the relationship between deterministic functions and probability distributions:
Consider a dataset $D = \{(x_i,y_i)\}_{i=1}^N$ sampled from a joint distribution $P(X,Y)$.
(Kallenberg, 2006; Theorem 6.10) (simplified): Any conditional probability $$P(𝑌=y|𝑋=x)$$ can be represent as
$$P(𝑌=y|𝑋=x)= g'(y,x),$$
where
$$g' \text{ is a deterministic function.}$$
Representation Learning View¶
- Consider a classification task with $C \geq 2$ classes.
- Through the universal approximation theorem of neural networks, there exists
- a representation function (neural network) $\Gamma$ with parameters ${\bf W}_{\Gamma}$ and
- a link function (also a neural network) $g$ with parameters ${\bf W}_{g}$
- such that: $$P(Y=y|X=x) = g(\Gamma(x; {\bf W}_{\Gamma}); {\bf W}_{g})_y.$$
Example: For image classification, $\Gamma(x;{\bf W}_\Gamma)$ can be the convolutional layers of a CNN. While $g$ can be the remaining fully connected layers of the CNN.
Multi-task learning: Meta-learning through shared representations¶
- Consider two binary classification tasks ($n=2$).
- Consider three neural networks
- $\Gamma:\mathbb{R}^{h\times w} \times \mathbb{R}^{m'} \to \mathbb{R}^d,$ where $\Gamma$ has $m'$ neuron weights,
- $g^1:\mathbb{R}^{d} \times \mathbb{R}^{m} \to [0,1],$
- $g^2:\mathbb{R}^{d}\times \mathbb{R}^{m} \to [0,1]$, where $g^1,g^2$ have $m$ neuron weights, where $m$ is reasonably small.
Example when the inputs are the same for both tasks:
Example when the inputs are not the same for both tasks:
Task 1
Task 2
- Classical reference: Multitask Learning, Rich Caruana, in Thrun, Sebastian, Pratt, Lorien (Eds.), Learning to Learn, 1998 Springer. (Free only copy through the Purdue Library)
- Let $f^k(x)$ be the true label of $x$ on task $k \in \{1,2\}$.
- Assume there are true parameters (neuron weights) ${\bf W}^\star_{\Gamma}$, ${\bf W}^\star_{g^1} \in \mathbb{R}^m$, ${\bf W}^\star_{g^2} \in \mathbb{R}^m$ such that $$P(f^1(x) =1|X=x) = g^1(\Gamma(x; {\bf W}^\star_{\Gamma}); {\bf W}^\star_{g^1}),$$ while $$P(f^2(x)=1|X=x) = g^2(\Gamma(x; {\bf W}^\star_{\Gamma}); {\bf W}^\star_{g^2}),$$ with $g^1$ and $g^2$ as reasonably simple functions (i.e., $m$ is not large).
Defining a Single Objective Function: A Naive Approach¶
A common approach to multi-task learning is to define a single objective function that combines the losses of all tasks. In this case, we minimize the negative log-likelihood (cross-entropy) objective jointly over the two tasks: $${\bf W}^\text{opt12}_\Gamma,{\bf W}^\text{opt12}_{g^1},{\bf W}^\text{opt12}_{g^2} = \underset{{\bf W}_\Gamma,{\bf W}_g^1,{\bf W}_g^2}{\mathrm{argmin}} - \sum_{k=1}^2 \sum_{i=1}^{N_k} f^k(x^k_i) \log g^k(\Gamma(x^k_i;{\bf W}_\Gamma);{\bf W}_{g^k}) + (1-f^k(x^k_i)) \log (1 - g^k(\Gamma(x^k_i;{\bf W}_\Gamma);{\bf W}_{g^k})).$$ This approach is often referred to as "mixing" the tasks, where the gradients of the two tasks are combined and optimized simultaneously. However, this method can be problematic due to the potential for gradient interference, where the gradients from different tasks conflict with each other, impeding learning progress.
In essence, mixing the tasks means that the model is trying to optimize both tasks simultaneously, using a single set of updates that are computed by summing the gradients of the two tasks. This can lead to:
- Destructive interference: The gradients from different tasks can cancel each other out, slowing down or even preventing convergence.
- Dominance of one task over others: The task with the larger gradient magnitude can dominate the update direction, causing the model to prioritize one task over others.
While this approach may seem intuitive, we will later discuss why it is often beneficial to avoid mixing the gradients of the tasks in this way, and instead use techniques like PCGrad to mitigate gradient interference and improve overall performance.
- Define the hypothesis spaces for tasks 1 and 2 as the set of functions $$H_1 = \{g^1(\Gamma(\cdot;{\bf W}_{\Gamma});{\bf W}_{g^1})| \forall {\bf W}_{\Gamma},\forall {\bf W}_{g^1}\}$$ and $$H_2 = \{g^2(\Gamma(\cdot;{\bf W}_{\Gamma});{\bf W}_{g^2})| \forall {\bf W}_{\Gamma},\forall {\bf W}_{g^2}\}.$$
- Note 1: $g^1$ and $g^2$ could be different and then $H_1$ and $H_2$ would likely overlap but not be equal.
- Note 2: We could easily extend the above definitions to any supervised learning task.
Multi-task Learning: A Better Approach¶
Addressing Gradient Conflicts in Multi-task learning: PCGrad¶
One of the key challenges in multi-task learning is gradient interference, where gradients from different tasks conflict with each other, impeding learning progress. This issue arises when three conditions occur simultaneously, known as the "tragic triad" by Yu et al. 2020:
- Conflicting gradients: This occurs when the cosine similarity between gradients from different tasks is negative, indicating that the gradients are, in part, pointing in opposite directions.
- Large positive curvature in the loss landscape: When the loss landscape has a large positive curvature, it means that small changes in the model's parameters can result in significant increases in the loss function.
- Significant differences in gradient magnitudes: When the magnitudes of gradients from different tasks vary substantially, it can lead to unstable updates and hinder the learning process.
Reference:
- "Gradient Surgery for Multi-Task Learning", Tianhe Yu, Saurabh Kumar, Abhishek Gupta, Sergey Levine, Karol Hausman, Chelsea Finn, NeurIPS 2020.
The traditional approach to handling multiple tasks is to add their losses together. $$\text{Total Loss} = \text{(Task 1 Loss)} + \lambda \text{(Task 2 Loss)},$$ where $\lambda$ is a hyperparameter.
However, this is suboptimal due to the potential for gradient interference. When the losses are added, the resulting gradient may not accurately reflect the optimal update direction for each task, leading to conflicting gradients that can impede learning progress. Specifically, adding losses can result in:
- Destructive interference: The gradients from different tasks can cancel each other out, slowing down or even preventing convergence.
- Dominance of one task over others: The task with the larger gradient magnitude can dominate the update direction, causing the model to prioritize one task over others.
Projected Conflicting Gradients (PCGrad)¶
- PCGrad is a gradient descent approach designed to mitigate gradient interference by projecting conflicting task gradients onto the orthogonal subspace of each other (projecting on each other's normal plane).
- This method effectively removes the conflicting component of the gradients while preserving their beneficial components. When two tasks' gradients are opposed, indicated by a negative cosine similarity, PCGrad projects each task's gradient onto the orthogonal plane of the other's gradient.
For task gradients $g_i$ and $g_j$ that conflict (i.e., $\langle g_i, g_j \rangle < 0$), PCGrad modifies $g_i$ as follows: $$g_i^{PC} = g_i - \frac{\langle g_i , g_j \rangle}{||g_j||^2}g_j$$ Where $g_i^{PC}$ is the projected gradient for task $i$. If gradients don't conflict, they remain unchanged.
Figure from Yu et al., 2020
The PCGrad approach has several advantages over traditional methods:
- Reduced gradient interference: By projecting conflicting gradients onto each other's normal plane, PCGrad minimizes the destructive interference between tasks.
- Improved stability: PCGrad helps to stabilize the learning process by reducing the impact of large positive curvature and significant differences in gradient magnitudes.
- Model-agnostic: PCGrad can be easily integrated into existing multi-task and meta-learning frameworks, making it a versatile and widely applicable method.
PCGrad Algorithm¶
The PCGrad update procedure is as follows:
- Compute task gradients $g_k = \nabla_{{\bf W}_\Gamma}L_k({\bf W}_\Gamma,{\bf W}_{g^k})$ for all tasks $k$
- Initialize $g_k^{PC} = g_k$ for all tasks $k$
- For each task $T_i$:
- For each task $T_j$ (in random order):
- If $g_i^{PC} \cdot g_j < 0$ (gradients conflict):
- Set $g_i^{PC} = g_i^{PC} - \frac{g_i^{PC} \cdot g_j}{||g_j||^2}g_j$
- If $g_i^{PC} \cdot g_j < 0$ (gradients conflict):
- For each task $T_j$ (in random order):
- Return update $\Delta{\bf W}_\Gamma = \sum_i g_i^{PC}$ for the update of ${\bf W}_\Gamma$.
- The update of ${\bf W}_{g^k}$ has no conflict and can be performed via regular gradient update.
For Tasks with the Same Targets: Model-Agnostic Meta-Learning (MAML)¶
Model-Agnostic Meta-Learning (MAML) trains a model to be easy to fine-tune over tasks with the same targets. MAML seeks to find model parameters that can quickly adapt to new tasks with minimal gradient steps and limited data.
MAML Formulation¶
Consider a model represented by a parameterized function $f(x;{\bf W}) = g(\Gamma(x;{\bf W}_\Gamma);{\bf W}_g)$, with parameters ${\bf W} = ({\bf W}_\Gamma,{\bf W}_g)$. When adapting to a new task $\mathcal{T}_{i}$, the model's parameters ${\bf W}$ become ${\bf W}'_{i}$ after adaptation.
With MAML, the updated parameter vector ${\bf W}'_{i}$ is computed using one or more gradient descent updates on task $\mathcal{T}_{i}$: $$ {\bf W}'_{i} = {\bf W} - \eta \nabla_{{\bf W}}\mathcal{L}_{\mathcal{T}_{i}}\left(f_{{\bf W}}\right), $$ where $\eta$ is the learning rate and $\mathcal{L}_{\mathcal{T}_{i}}$ is the total loss of task $\mathcal{T}_{i}$ on our training data.
Let $ p\left(\mathcal{T}\right)$ be a distribution of tasks.
- The meta-objective is to optimize ${\bf W}$ such that after adaptation, the model performs well across tasks: $$ \min_{{\bf W}} \sum_{\mathcal{T}_{i} \sim p\left(\mathcal{T}\right)} \mathcal{L}_{\mathcal{T_{i}}}\left(f_{{\bf W}'_{i}}\right) = \sum_{\mathcal{T}_{i} \sim p\left(\mathcal{T}\right)} \mathcal{L}_{\mathcal{T_{i}}}\left(f_{{\bf W} - \alpha\nabla_{{\bf W}}\mathcal{L}_{\mathcal{T}_{i}}\left(f_{{\bf W}}\right)}\right) $$ Notice that the meta-optimization is performed over the model parameters ${\bf W}$, whereas the objective is computed using the updated model parameters ${\bf W}'_i$. The meta-parameters are updated using: $$ {\bf W} \leftarrow {\bf W} - \beta\nabla_{{\bf W}} \sum_{\mathcal{T}_{i} \sim p\left(\mathcal{T}\right)} \mathcal{L}_{\mathcal{T_{i}}}\left(f_{{\bf W}'_{i}}\right) $$ where $\beta$ is the meta step size.
MAML Algorithm¶
The MAML algorithm for few-shot supervised learning proceeds as follows:
- Randomly initialize ${\bf W}$
- While not done:
- Sample batch of tasks $T_i \sim p(T)$
- For each task $T_i$:
- Sample $K$ datapoints $D = \{x^{(j)}, y^{(j)}\}$ from $T_i$
- Evaluate $\nabla_{{\bf W}}L_{T_i}(\Gamma_{{\bf W}})$ using $D$
- Compute adapted parameters: ${\bf W}'_i = {\bf W} - \alpha\nabla_{{\bf W}}L_{T_i}(\Gamma_{{\bf W}})$
- Sample datapoints $D'_i = \{x^{(j)}, y^{(j)}\}$ from $T_i$ for meta-update
- Update ${\bf W} \leftarrow {\bf W} - \beta\nabla_{{\bf W}}\sum_{T_i \sim p(T)} L_{T_i}(\Gamma_{{\bf W}'_i})$ using each $D'_i$
This approach trains the model to be easy to fine-tune, enabling rapid adaptation to new tasks with limited data. MAML has been successfully applied to few-shot classification, regression, and reinforcement learning tasks.
Transfer learning: Sequential meta learning (or what is fine-tuning?)¶
Consider two binary classification tasks ($n=2$).
Assume tasks must be learned in sequence, first task 1 then task 2.
Let $f^k(x)$ be the true label of input $x$ (e.g., an image) on task $k \in \{1,2\}$.
Consider again three neural networks
- $\Gamma:\mathbb{R}^{h\times w} \times \mathbb{R}^{m'} \to \mathbb{R}^d,$ where $\Gamma$ has $m'$ neuron weights,
- $g^1:\mathbb{R}^{d} \times \mathbb{R}^{m} \to [0,1],$
- $g^2:\mathbb{R}^{d}\times \mathbb{R}^{m} \to [0,1]$, where $g^1,g^2$ have $m$ neuron weights, where $m$ is reasonably small.
- Assume there are true parameters (neuron weights) ${\bf W}^\star_{\Gamma}\in \mathbb{R}^{m'}$, ${\bf W}^\star_{g^1} \in \mathbb{R}^m$, ${\bf W}^\star_{g^2} \in \mathbb{R}^m$ such that $$P(f^1(x) =1|X=x) = g^1(\Gamma(x; {\bf W}^\star_{\Gamma}); {\bf W}^\star_{g^1}),$$ while $$P(f^2(x)=1|X=x) = g^2(\Gamma(x; {\bf W}^\star_{\Gamma}); {\bf W}^\star_{g^2}),$$ with $g^1$ and $g^2$ as reasonably simple functions (i.e., $m$ is not large).
- Suppose we are given an infinite-sized dataset $D^1=\{(x^1_i,f^1(x^1_i)\}_{i=1}^{\infty}$ for task 1 such that $${\bf W}^\star_\Gamma,{\bf W}^\star_{g^1} = \underset{{\bf W}_\Gamma,{\bf W}_g^1}{\mathrm{argmin}} - \lim_{N_1 \to \infty} \sum_{i=1}^{N_1} f^1(x^1_i) \log (g^1(\Gamma(x^1_i;{\bf W}_\Gamma);{\bf W}_{g^1})) + (1-f^1(x^1_i)) \log (1 - g^1(\Gamma(x^1_i;{\bf W}_\Gamma);{\bf W}_{g^1})). $$
- How does knowing ${\bf W}^\star_{\Gamma}$ help learn task 2?
- By reducing the searchable hypothesis space from $H_2$ to $H'_2$.
Transfer learning (case 1): Greedy Layer-Wise Pre-training¶
Greedy layer-wise pre-training is the simplest form of transfer learning.
Greedy layer-wise pre-training is by far the most widely used meta learning method.
In greedy layer-wise pre-training, we first learn $g^1(\cdot;{\bf W}^\text{opt1}_{g^1})$ and $\Gamma(\cdot; {\bf W}^\text{opt1}_{\Gamma})$ on task 1 with dataset $D^1$.
- Recall that our goal is to learn the hypothesis space $F$ by learning a $\Gamma$ representation that is common among all tasks.
- We then assume that $\Gamma(\cdot; {\bf W}^\text{opt1}_{\Gamma}) = \Gamma(\cdot; {\bf W}^\star_{\Gamma})$.
- Finally, we then learn $g^2(\cdot;{\bf W}^\text{opt2}_{g^2})$ on task 2 with dataset $D^2$ using the pre-trained $\Gamma(\cdot; {\bf W}^\text{opt1}_{\Gamma})$.
- Note: If $\Gamma(\cdot; {\bf W}^\text{opt1}_{\Gamma}) \neq \Gamma(\cdot; {\bf W}^\star_{\Gamma})$, we need to adjust the parameters of $\Gamma$.
- We will cover this case after showing the following Greedy Layer-Wise Pre-training example
Greedy Layer-Wise Pre-training Example¶
%matplotlib inline
from mycnnlib import *
data_loaders, dataset_sizes, class_names = load_data(data_dir='data/antsbees', batch_size=32)
# Get a batch of training data
inputs, classes = next(iter(data_loaders['train']))
# Make a grid from batch
out = torchvision.utils.make_grid(inputs)
imshow(out, title="Mini-batch")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
from torchvision.models import resnet18, ResNet18_Weights
Gamma = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1) # ResNet-18 pre-trained over ImageNet 1000
# => 1000 different classes, no ants or bees
out_size = Gamma.fc.in_features
Gamma.fc = nn.Identity(out_size, out_size)
Gamma = Gamma.to(device)
g = nn.Linear(out_size, 2, bias=True).to(device)
criterion = nn.CrossEntropyLoss()
# Observe that all parameters are being optimized
optimizer_ft = optim.SGD(g.parameters(), lr=0.001, momentum=0.9)
# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)
def train_model(Gamma, g, criterion, optimizer, scheduler, num_epochs=25):
since = time.time()
# early stopping state
best_model = copy.deepcopy(g.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print(f'Epoch {epoch + 1}/{num_epochs}')
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
Gamma.eval() # Set Gamma to evaluation mode
g.train() # Set g to training mode
else:
Gamma.eval() # Set Gamma to evaluation mode
g.eval() # Set g to evaluation mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in data_loaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
outputs = g(Gamma(inputs).detach()) # .detach() guarantees that gradients are not
# backpropagated to Gamma
_, preds = torch.max(outputs, 1) # predicted label
loss = criterion(outputs, labels) # loss NLL loss using the output "probabilities"
# actually, the CrossEntropyLoss() does
# the softmax for us
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step() # One optimization step
scheduler.step() # One learning rate scheduler step
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
# Early "stopping"
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model = copy.deepcopy(g.state_dict())
time_elapsed = time.time() - since
print(f'\nTraining complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')
print(f'Best val Acc: {best_acc:4f}')
# load best model weights of g obtained from early stopping
g.load_state_dict(best_model)
# returns link function g
return g
model_ft = train_model(Gamma=Gamma, g=g, criterion=criterion, optimizer=optimizer_ft, scheduler=exp_lr_scheduler, num_epochs=3)
Epoch 1/3 ---------- train Loss: 0.6930 Acc: 0.5328 val Loss: 0.5142 Acc: 0.7124 Epoch 2/3 ---------- train Loss: 0.5291 Acc: 0.7336 val Loss: 0.4666 Acc: 0.8301 Epoch 3/3 ---------- train Loss: 0.5093 Acc: 0.7787 val Loss: 0.4626 Acc: 0.8301 Training complete in 2m 43s Best val Acc: 0.830065
visualize_model(Gamma, g, data_loaders, class_names, device)
Transfer learning (case 2): Fine tuning $\Gamma$ through Bayesian multi-task learning¶
- Consider learning task 1 first, then meta-learing task 2.
- This time, we do not have infinite data in $D^1=\{(x^1_i,f^1(x^1_i)\}_{i=1}^{N_1}$. $${\bf W}^\text{opt1}_\Gamma,{\bf W}^\text{opt1}{g^1} = \underset{{\bf W}_\Gamma,{\bf W}_g^1}{\mathrm{argmin}} - \sum_{i=1}^{N_1} f^1(x_i) \log (g^1(\Gamma(x_i;{\bf W}_\Gamma);{\bf W}_{g^1})) + (1-f^1(x_i)) \log (1 - g^1(\Gamma(x_i;{\bf W}_\Gamma);{\bf W}_{g^1})). $$
- Since it is likely that $\Gamma(\cdot; {\bf W}^\text{opt1}_{\Gamma}) \neq \Gamma(\cdot; {\bf W}^\star_{\Gamma})$, we need to adjust (improve) ${\bf W}^\text{opt1}_{\Gamma}$ as we learn task 2.
The Catastrophic Forgetting Challenge¶
Catastrophic forgetting happens when we optimize an end-to-end neural network $g^1(\Gamma(x;{\bf W}^\text{opt1}_\Gamma);{\bf W}^\text{opt1}_{g^1})$ for task 1
- Test performance on task 1 is good
Then we retrain (optimize) $g^2(\Gamma(x;{\bf W}^\text{opt2}_\Gamma);{\bf W}^\text{opt2}_{g^2})$ for task 2 untill the loss at task 2 is small
- Test performance on task 2 is good
- Test performance on task 1 is likely bad now
We say the neural network $\Gamma(\cdot;{\bf W}^\text{opt2}_\Gamma)$ has forgotten about task 1 once it has learned task 2.
(Note) MAP optimization of neural networks¶
Let ${\bf W}_\Gamma$, ${\bf W}_{g^1}$ and ${\bf W}_{g^2}$ be the weights of neural networks $\Gamma, g^1$ and $g^2$, respectively.
Consider the multi-task classification learning using maximum likelihood estimation: $$ {\bf W}^\text{opt12}_\Gamma, {\bf W}^\text{opt12}_{g^1}, {\bf W}^\text{opt12}_{g^2} = \underset{{\bf W}_\Gamma,{\bf W}_g^1,{\bf W}_g^2}{\mathrm{argmin}} -\log (\text{model-likelihood}({\bf W}_\Gamma, {\bf W}_{g^1}, {\bf W}_{g^2})),\label{eqml} $$ where $$ \text{model-likelihood}({\bf W}_\Gamma, {\bf W}_{g^1}, {\bf W}_{g^2}) = \prod_{k=1}^2 \prod_{i=1}^{N_k} P(f^k(x_i) = 1 | X= x^k_i , {\bf W}_\Gamma, {\bf W}_{g^1},{\bf W}_{g^2}) = \prod_{k=1}^2 \prod_{i=1}^{N_k} (g^k(\Gamma(x^k_i ;{\bf W}_\Gamma); {\bf W}_{g^k}))^{f^k(x_i)} (1-g^k(\Gamma(x^k_i ;{\bf W}_\Gamma); {\bf W}_{g^k}))^{1-f^k(x_i)} , $$ and $N_k$ is the number of training examples for task $k$.
Note that our loss objective $$-\log (\text{model-likelihood}({\bf W}_\Gamma, {\bf W}_{g^1}, {\bf W}_{g^2}))$$ is the same as the cross-entropy (negative log-likelihood) formula given earlier for multi-task learning.
- Now we add independent standard multivariate Gaussian priors $P({\bf W}_\Gamma), P({\bf W}_{g^1}), P({\bf W}_{g^2})$ to ${\bf W}_\Gamma$, ${\bf W}_{g_1}$, and ${\bf W}_{g_2}$, respectively.
- Consider the posterior distribution of the model parameters: $$ \text{model-posterior}({\bf W}_\Gamma, {\bf W}_{g^1}, {\bf W}_{g^2}) \propto \prod_{k=1}^2 \prod_{i=1}^{N_k} P(f^k(x_i)=1, X = xˆk_i | {\bf W}_\Gamma, {\bf W}_{g^1},{\bf W}_{g^2}) P({\bf W}_\Gamma) P({\bf W}_{g^1})P({\bf W}_{g^2}), \label{eqpos} $$ where $\propto$ indicates proportional up to a constant.
- Rather the maximizing the likelihood (MLE) we will now maximize the posterior (MAP) by minimizing its negative log:
$$ {\bf W}^\text{opt12}_\Gamma, {\bf W}^\text{opt12}_{g^1}, {\bf W}^\text{opt12}_{g^2} = \underset{{\bf W}_\Gamma,{\bf W}_g^1,{\bf W}_g^2}{\mathrm{argmin}} -\log (\text{model-posterior}({\bf W}_\Gamma, {\bf W}_{g^1}, {\bf W}_{g^2})).$$
- Note that the loss objective $-\log (\text{model-posterior}({\bf W}_\Gamma, {\bf W}_{g^1}, {\bf W}_{g^2})) = -\log (\text{model-likelihood}({\bf W}_\Gamma, {\bf W}_{g^1}, {\bf W}_{g^2})) + \frac{1}{2}\Vert {\bf W}_\Gamma \Vert_2^2 + \frac{1}{2}\Vert {\bf W}_{g^1} \Vert_2^2 + \frac{1}{2}\Vert {\bf W}_{g^2} \Vert_2^2 - \frac{3}{2}\log (2 \pi)$.
- This is because if ${\bf W}$ is a standard multivariate Gaussian, then $-\log P({\bf W}) = \frac{1}{2}\Vert {\bf W} \Vert_2^2 - \frac{1}{2}\log (2 \pi)$.
- Note that the loss objective $-\log (\text{model-posterior}({\bf W}_\Gamma, {\bf W}_{g^1}, {\bf W}_{g^2})) = -\log (\text{model-likelihood}({\bf W}_\Gamma, {\bf W}_{g^1}, {\bf W}_{g^2})) + \frac{1}{2}\Vert {\bf W}_\Gamma \Vert_2^2 + \frac{1}{2}\Vert {\bf W}_{g^1} \Vert_2^2 + \frac{1}{2}\Vert {\bf W}_{g^2} \Vert_2^2 - \frac{3}{2}\log (2 \pi)$.
A Bayesian Method for Multi-task Sequential Learning¶
- Consider two distinct datasets $A$ and $B$ for the same task (for simplicity).
- We are fist given dataset $A$ to train
- Then we need to train for dataset $B$
- Let ${\bf W}$ be a vector of model parameters of a neural network $h$.
- In reality, in a neural network ${\bf W}$ is a collection of matrices and tensors. But without loss of generality we can always vectorize this data structure.
- For a dataset $A$, define $P(A|{\bf W}) = \prod_{(x,y) \in A} P(Y=y|X=x, {\bf W}) = \prod_{(x,y) \in A} h(x; {\bf W})_y$, for a neural network $h$ with softmax outputs.
- Assume $P(B,A|{\bf W})=P(B|{\bf W})P(A|{\bf W})$
- Then, $P(B,A,{\bf W}) = P(B,A|{\bf W})P({\bf W}) = P(B|{\bf W})P(A|{\bf W})P({\bf W}) = P(B|{\bf W})P({\bf W}|A)P(A)$.
- Note that $P(A)$ is constant with respect to ${\bf W}$, so we can ignore $P(A)$ in our optimization.
- Hence, the maximum likelihood optimization objective is $\hat{{\bf W}} = \arg\!\max_{{\bf W}} P(B|{\bf W})P({\bf W}|A)$.
- The negative log objective is then $$\hat{{\bf W}} = \arg\!\min_{{\bf W}} - (\log P(B|{\bf W}) + \log P({\bf W}|A)).$$
- The term $-\log P({\bf W}|A)$ is a regularization constrain over the optimization $-\log P(B|{\bf W})$ of the model over dataset $B$.
- If $P({\bf W}|A)$ had a Gaussian distribution, the term $-\log P({\bf W}|A)$ would amount to adding an L2 penalty to $\arg\!\min_{{\bf W}} - \log P(B|{\bf W})$.
Local Asymptotic Normality¶
Theorem (Local Asymptotic Normality, Le Cam (1960)): Given a large-enough dataset $A$, and under some conditions, the posterior distribution of $P({\bf W}|A)$ and $P(W)$ a "mild" prior, converges to $$ P({\bf W}|A) \stackrel{d}{=} \text{Normal}(\hat{{\bf W}_A},\frac{1}{m_k} I_{\bf W}^{-1}) $$ where $$ \hat{{\bf W}}_A = \arg\!\max_{{\bf W}} P({\bf W}|A) $$ and $$ I_{\bf W} = \mathrm{E}\bigg[{- \frac{\partial^2 \ln f(X_i,{\bf W})}{\partial W_h\,\partial W_j}}\bigg] = \mathrm{E}\bigg[\bigg(\frac{\partial \ln f(X_i,{\bf W})}{\partial W_h}\bigg)\bigg(\frac{\partial \ln f(X_i,{\bf W})}{\partial W_j}\bigg)^\texttt{T} \,\bigg] $$ is the Fisher information matrix.
- Notation: $W_h$ is the $h$-th element of ${\bf W}$ ordered as a vector in some arbitrary way.
References:
- Le Cam, L. (1960). "Locally asymptotically normal families of distributions". University of California Publications in Statistics. 3: 37–98.
Bayesian Parameter Regularization to avoid Catastrophic Forgetting¶
- Let $\hat{{\bf W}_A}$ as defined above: $$ \hat{{\bf W}}_A = \arg\!\max_{{\bf W}} P({\bf W}|A). $$
- If we assume Le Cam's Local Asymptotic Normality, then $P({\bf W}|A) \approx \text{Normal}(\hat{{\bf W}_A},I_{\bf W}^{-1})$ and the regularization $$-\log P({\bf W}|A) \approx \frac{1}{2}\Vert I_{\bf W}^{-1} ({\bf W} - \hat{\bf W}_A) \Vert_2^2.$$
The original objective was then $$\hat{{\bf W}} = \arg\!\min_{{\bf W}} -(\log P(B|{\bf W}) + \log P({\bf W}|A)) \approx \arg\!\min_{{\bf W}} -\log P(B|{\bf W}) + \frac{1}{2}\Vert I_{\bf W}^{-1} ({\bf W} - \hat{\bf W}_A) \Vert_2^2 .$$
If we assume $I_{\bf W} $ is a diagonal matrix (not true in general, but it simplifies the computation tremendously): $$\log P({\bf W}|A) \approx \sum_h \frac{1}{(I_{\bf W})_{hh}}({W}_h - \hat{W}_h)^2 .$$
This is the key insight of Kirkpatrick et al. (PNAS 2017), Overcoming catastrophic forgetting in neural networks.
### Example of Bayesian Regularization using (Diagonal) Fisher Information Matrix
import torch
from torch import autograd
import torch.nn.functional as F
from tqdm import tqdm
#------------------------------------------------------
# Get the Diagonal Fisher Information Matrix
#------------------------------------------------------
def get_diagonal_Fisher_information(model, X, Y):
FisherI_list = []
n_samples = X.shape[0]
for param in model.parameters():
FisherI_list.append(torch.zeros_like(param))
# Compute the Diagonal Fisher Information Matrix
pre_softmax_output = model(X)
loglikelihoods = F.log_softmax(pre_softmax_output, dim=1)[range(n_samples), Y]
loglikelihood = loglikelihoods.mean()
loglikelihood.backward()
for idx, param in enumerate(model.parameters()):
FisherI_list[idx] += param.grad**2
return Fisher_list
#-----------------------------------------------------------------------
# Bayesian loss funtion using Diagonal Fisher Information Matrix
#-----------------------------------------------------------------------
def Bayesian_Fisher_information_loss(reg_strength, Fisher_list, prev_opt_params, current_params):
loss = 0
for i in range(len(Fisher_list)):
loss += reg_strength/2 * torch.sum(1/Fisher_list[i] * (prev_opt_params[i]-current_params[i])**2)
return loss
#--------------------------------------------------------------------------------------------
# Bayesian optimization using Diagonal Fisher Information Matrix regularization
#--------------------------------------------------------------------------------------------
def train_Bayesian_FI(model, train_loader, optimizer, base_loss_fn, reg_strength, FisherI_list, prev_opt_params, epoch, description=""):
# Prepare model for training
model.train()
loss_train = 0
# Show training progress
pbar = tqdm(train_loader)
pbar.set_description(description)
for Xs, Ys in pbar:
Xs, Ys = Xs.to(model.device), Ys.to(model.device)
current_params = list(model.parameters())
optimizer.zero_grad()
pre_softmax_output = model(Xs)
loss_crossentropy = base_loss_fn(pre_softmax_output, Ys)
Bayesian_appx_loss = Bayesian_Fisher_information_loss(reg_strength, FisherI_list, prev_opt_params, current_params)
loss = loss_crossentropy + Bayesian_appx_loss
loss_train += loss.item()
loss.backward()
optimizer.step()
loss_train /= len(train_loader)
print('loss_train: {:.6f}'.format(loss_train))
return loss_train
Recap¶
- Meta-learning is a procedure that allows a learner to improve its generalization performance as it sees larger quantities of both data and new related tasks
- In deep learning, meta-learning relies on shared representations to narrow down the hypothesis space as we learn more tasks
- Type of meta learning:
- Multi-task learning (data for all tasks are available simultaneously)
- Tasks may share the same input
- Tasks may not share the same input
- Transfer learning (data for task $k$ appears after we learn tasks $1,\ldots,k-1$, may have different inputs)
- Multi-task learning (data for all tasks are available simultaneously)
- Given enough data for the first task, transfer learning without fine tuning is OK.
- Without a lot of data for the first task, we must fine-tune the representation
- Fine tuning in transfer learning should use a L2 norm regularization with the inverse Fisher information matrix
References¶
- Thrun, Sebastian, Learning to Learn, 1998, Springer.
- Yu et al., Gradient Surgery for Multi-Task Learning, NeurIPS 2020.
- Finn et al., Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks, ICML 2017.
- Rajeswaran et al., Meta-Learning with Implicit Gradients, NeurIPS 2019.