|
7 | 7 |
|
8 | 8 |
|
9 | 9 | def ref_clone_module(module):
|
| 10 | + """ |
| 11 | + Note: This implementation does not work for RNNs. |
| 12 | + It requires calling learner.rnn._apply(lambda x: x) before |
| 13 | + each forward call. |
| 14 | + See this issue for more details: |
| 15 | + https://github.com/learnables/learn2learn/issues/139 |
| 16 | + """ |
10 | 17 | # First, create a copy of the module.
|
11 | 18 | clone = copy.deepcopy(module)
|
12 | 19 |
|
@@ -120,6 +127,51 @@ def test_clone_module_models(self):
|
120 | 127 | for ref_p, l2l_p in zip(ref_model.parameters(), l2l_model.parameters()):
|
121 | 128 | self.assertTrue(torch.equal(ref_p, l2l_p))
|
122 | 129 |
|
| 130 | + def test_rnn_clone(self): |
| 131 | + # Tests: https://github.com/learnables/learn2learn/issues/139 |
| 132 | + # The test is mainly about whether we can clone and adapt RNNs. |
| 133 | + # See issue for details. |
| 134 | + N_STEPS = 3 |
| 135 | + for rnn_class in [ |
| 136 | + torch.nn.RNN, |
| 137 | + torch.nn.LSTM, |
| 138 | + torch.nn.GRU, |
| 139 | + ]: |
| 140 | + torch.manual_seed(1234) |
| 141 | + model = rnn_class(2, 1) |
| 142 | + maml = l2l.algorithms.MAML(model, lr=1e-3, allow_unused=False) |
| 143 | + optim = torch.optim.SGD(maml.parameters(), lr=0.001) |
| 144 | + data = torch.randn(30, 500, 2) |
| 145 | + |
| 146 | + # Adapt and measure loss |
| 147 | + learner = maml.clone() |
| 148 | + for step in range(N_STEPS): |
| 149 | + pred, hidden = learner(data) |
| 150 | + loss = pred.norm(p=2) |
| 151 | + learner.adapt(loss) |
| 152 | + pred, _ = learner(data) |
| 153 | + first_loss = pred.norm(p=2) |
| 154 | + |
| 155 | + # Take an optimization step |
| 156 | + optim.zero_grad() |
| 157 | + first_loss.backward() |
| 158 | + optim.step() |
| 159 | + first_loss = first_loss.item() |
| 160 | + |
| 161 | + # Adapt a second time |
| 162 | + learner = maml.clone() |
| 163 | + for step in range(N_STEPS): |
| 164 | + pred, hidden = learner(data) |
| 165 | + loss = pred.norm(p=2) |
| 166 | + learner.adapt(loss) |
| 167 | + pred, _ = learner(data) |
| 168 | + second_loss = pred.norm(p=2) |
| 169 | + second_loss = second_loss.item() |
| 170 | + |
| 171 | + # Ensure we did better |
| 172 | + self.assertTrue(first_loss > second_loss) |
| 173 | + |
| 174 | + |
123 | 175 | def test_module_detach(self):
|
124 | 176 | original_output = self.model(self.input)
|
125 | 177 | original_loss = self.loss_func(original_output, torch.tensor([[0., 0.]]))
|
|
0 commit comments