Invariant Gradients variances for Out-of-distribution Generalization
| 1167 | |
| 1168 | |
| 1169 | class Fishr(Algorithm): |
| 1170 | "Invariant Gradients variances for Out-of-distribution Generalization" |
| 1171 | |
| 1172 | def __init__(self, input_shape, num_classes, num_domains, hparams): |
| 1173 | assert backpack is not None, "Install backpack with: 'pip install backpack-for-pytorch==1.3.0'" |
| 1174 | super(Fishr, self).__init__(input_shape, num_classes, num_domains, hparams) |
| 1175 | self.num_domains = num_domains |
| 1176 | |
| 1177 | self.featurizer = networks.Featurizer(input_shape, self.hparams) |
| 1178 | self.classifier = extend( |
| 1179 | networks.Classifier( |
| 1180 | self.featurizer.n_outputs, |
| 1181 | num_classes, |
| 1182 | self.hparams['nonlinear_classifier'], |
| 1183 | ) |
| 1184 | ) |
| 1185 | self.network = nn.Sequential(self.featurizer, self.classifier) |
| 1186 | |
| 1187 | self.register_buffer("update_count", torch.tensor([0])) |
| 1188 | self.bce_extended = extend(nn.CrossEntropyLoss(reduction='none')) |
| 1189 | self.ema_per_domain = [ |
| 1190 | MovingAverage(ema=self.hparams["ema"], oneminusema_correction=True) |
| 1191 | for _ in range(self.num_domains) |
| 1192 | ] |
| 1193 | self._init_optimizer() |
| 1194 | |
| 1195 | def _init_optimizer(self): |
| 1196 | self.optimizer = torch.optim.Adam( |
| 1197 | list(self.featurizer.parameters()) + list(self.classifier.parameters()), |
| 1198 | lr=self.hparams["lr"], |
| 1199 | weight_decay=self.hparams["weight_decay"], |
| 1200 | ) |
| 1201 | |
| 1202 | def update(self, minibatches, unlabeled=False): |
| 1203 | assert len(minibatches) == self.num_domains |
| 1204 | all_x = torch.cat([x for x, y in minibatches]) |
| 1205 | all_y = torch.cat([y for x, y in minibatches]) |
| 1206 | len_minibatches = [x.shape[0] for x, y in minibatches] |
| 1207 | |
| 1208 | all_z = self.featurizer(all_x) |
| 1209 | all_logits = self.classifier(all_z) |
| 1210 | |
| 1211 | penalty = self.compute_fishr_penalty(all_logits, all_y, len_minibatches) |
| 1212 | all_nll = F.cross_entropy(all_logits, all_y) |
| 1213 | |
| 1214 | penalty_weight = 0 |
| 1215 | if self.update_count >= self.hparams["penalty_anneal_iters"]: |
| 1216 | penalty_weight = self.hparams["lambda"] |
| 1217 | if self.update_count == self.hparams["penalty_anneal_iters"] != 0: |
| 1218 | # Reset Adam as in IRM or V-REx, because it may not like the sharp jump in |
| 1219 | # gradient magnitudes that happens at this step. |
| 1220 | self._init_optimizer() |
| 1221 | self.update_count += 1 |
| 1222 | |
| 1223 | objective = all_nll + penalty_weight * penalty |
| 1224 | self.optimizer.zero_grad() |
| 1225 | objective.backward() |
| 1226 | self.optimizer.step() |
nothing calls this directly
no outgoing calls
no test coverage detected