|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +from packaging.version import parse |
| 4 | +import torch |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from avalanche.training.templates import SupervisedTemplate |
| 8 | +from avalanche.training.plugins.strategy_plugin import SupervisedPlugin |
| 9 | +from avalanche.training.storage_policy import ExemplarsBuffer, ExperienceBalancedBuffer |
| 10 | +from avalanche.benchmarks.utils.data_loader import ReplayDataLoader |
| 11 | + |
| 12 | + |
| 13 | +class IL2MPlugin(SupervisedPlugin): |
| 14 | + """ |
| 15 | + Class Incremental Learning With Dual Memory (IL2M) plugin. |
| 16 | +
|
| 17 | + Technique introduced in: |
| 18 | + Belouadah, E. and Popescu, A. "IL2M: Class Incremental Learning With Dual |
| 19 | + Memory." Proceedings of the IEEE/CVF Conference on Computer Vision and |
| 20 | + Pattern Recognition. 2019. |
| 21 | +
|
| 22 | + Implementation based on FACIL, as in: |
| 23 | + https://github.com/mmasana/FACIL/blob/master/src/approach/il2m.py |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + mem_size: int = 2000, |
| 29 | + batch_size: Optional[int] = None, |
| 30 | + batch_size_mem: Optional[int] = None, |
| 31 | + storage_policy: Optional[ExemplarsBuffer] = None, |
| 32 | + ): |
| 33 | + """ |
| 34 | + :param mem_size: replay buffer size. |
| 35 | + :param batch_size: the size of the data batch. If set to `None`, it |
| 36 | + will be set equal to the strategy's batch size. |
| 37 | + :param batch_size_mem: the size of the memory batch. If its value is set |
| 38 | + to `None` (the default value), it will be automatically set equal to |
| 39 | + the data batch size. |
| 40 | + :param storage_policy: The policy that controls how to add new exemplars |
| 41 | + in memory. |
| 42 | + """ |
| 43 | + |
| 44 | + super().__init__() |
| 45 | + self.mem_size = mem_size |
| 46 | + self.batch_size = batch_size |
| 47 | + self.batch_size_mem = batch_size_mem |
| 48 | + |
| 49 | + if storage_policy is not None: # Use other storage policy |
| 50 | + self.storage_policy = storage_policy |
| 51 | + assert storage_policy.max_size == self.mem_size |
| 52 | + else: # Default |
| 53 | + self.storage_policy = ExperienceBalancedBuffer( |
| 54 | + max_size=self.mem_size, adaptive_size=True |
| 55 | + ) |
| 56 | + |
| 57 | + # to store statistics for the classes as learned in the current incremental state |
| 58 | + self.current_classes_means = [] |
| 59 | + # to store statistics for past classes as learned in the incremental state in which they were first seen |
| 60 | + self.init_classes_means = [] |
| 61 | + # to store statistics for model confidence in different states (i.e. avg top-1 pred scores) |
| 62 | + self.models_confidence = [] |
| 63 | + # to store the mapping between classes and the incremental state in which they were first seen |
| 64 | + self.classes2exp = [] |
| 65 | + # total number of classes that will be seen |
| 66 | + self.n_classes = 0 |
| 67 | + |
| 68 | + def before_training_exp( |
| 69 | + self, |
| 70 | + strategy: SupervisedTemplate, |
| 71 | + num_workers: int = 0, |
| 72 | + shuffle: bool = True, |
| 73 | + drop_last: bool = False, |
| 74 | + **kwargs |
| 75 | + ): |
| 76 | + |
| 77 | + if len(self.init_classes_means) == 0: |
| 78 | + self.n_classes = len(strategy.experience.classes_seen_so_far) + len( |
| 79 | + strategy.experience.future_classes |
| 80 | + ) |
| 81 | + self.init_classes_means = [0 for _ in range(self.n_classes)] |
| 82 | + self.classes2exp = [-1 for _ in range(self.n_classes)] |
| 83 | + |
| 84 | + if len(self.storage_policy.buffer) == 0: |
| 85 | + # first experience. We don't use the buffer, no need to change |
| 86 | + # the dataloader. |
| 87 | + return |
| 88 | + |
| 89 | + batch_size = self.batch_size |
| 90 | + if batch_size is None: |
| 91 | + batch_size = strategy.train_mb_size |
| 92 | + |
| 93 | + batch_size_mem = self.batch_size_mem |
| 94 | + if batch_size_mem is None: |
| 95 | + batch_size_mem = strategy.train_mb_size |
| 96 | + |
| 97 | + assert strategy.adapted_dataset is not None |
| 98 | + |
| 99 | + other_dataloader_args = dict() |
| 100 | + |
| 101 | + if "ffcv_args" in kwargs: |
| 102 | + other_dataloader_args["ffcv_args"] = kwargs["ffcv_args"] |
| 103 | + |
| 104 | + if "persistent_workers" in kwargs: |
| 105 | + if parse(torch.__version__) >= parse("1.7.0"): |
| 106 | + other_dataloader_args["persistent_workers"] = kwargs[ |
| 107 | + "persistent_workers" |
| 108 | + ] |
| 109 | + |
| 110 | + strategy.dataloader = ReplayDataLoader( |
| 111 | + strategy.adapted_dataset, |
| 112 | + self.storage_policy.buffer, |
| 113 | + oversample_small_tasks=True, |
| 114 | + batch_size=batch_size, |
| 115 | + batch_size_mem=batch_size_mem, |
| 116 | + num_workers=num_workers, |
| 117 | + shuffle=shuffle, |
| 118 | + drop_last=drop_last, |
| 119 | + **other_dataloader_args |
| 120 | + ) |
| 121 | + |
| 122 | + def after_training_exp(self, strategy: SupervisedTemplate, **kwargs): |
| 123 | + experience = strategy.experience |
| 124 | + self.current_classes_means = [0 for _ in range(self.n_classes)] |
| 125 | + classes_counts = [0 for _ in range(self.n_classes)] |
| 126 | + self.models_confidence.append(0) |
| 127 | + models_counts = 0 |
| 128 | + |
| 129 | + # compute the mean prediction scores that will be used to rectify scores in subsequent incremental states |
| 130 | + with torch.no_grad(): |
| 131 | + strategy.model.eval() |
| 132 | + for inputs, targets, _ in strategy.dataloader: |
| 133 | + inputs, targets = inputs.to(strategy.device), targets.to( |
| 134 | + strategy.device |
| 135 | + ) |
| 136 | + outputs = strategy.model(inputs.to(strategy.device)) |
| 137 | + scores = outputs.data.cpu().numpy() |
| 138 | + for i in range(len(targets)): |
| 139 | + target = targets[i].item() |
| 140 | + classes_counts[target] += 1 |
| 141 | + if target in experience.previous_classes: |
| 142 | + # compute the mean prediction scores for past classes of the current state |
| 143 | + self.current_classes_means[target] += scores[i, target] |
| 144 | + else: |
| 145 | + # compute the mean prediction scores for the new classes of the current state |
| 146 | + self.init_classes_means[target] += scores[i, target] |
| 147 | + # compute the mean top scores for the new classes of the current state |
| 148 | + self.models_confidence[-1] += np.max(scores[i,]) |
| 149 | + models_counts += 1 |
| 150 | + |
| 151 | + # normalize by corresponding number of samples |
| 152 | + for cls in experience.previous_classes: |
| 153 | + self.current_classes_means[cls] /= classes_counts[cls] |
| 154 | + for cls in experience.classes_in_this_experience: |
| 155 | + self.init_classes_means[cls] /= classes_counts[cls] |
| 156 | + self.models_confidence[-1] /= models_counts |
| 157 | + # store the mapping between classes and the incremental state in which they are first seen |
| 158 | + for cls in experience.classes_in_this_experience: |
| 159 | + self.classes2exp[cls] = experience.current_experience |
| 160 | + |
| 161 | + # update the buffer of exemplars |
| 162 | + self.storage_policy.post_adapt(strategy, strategy.experience) |
| 163 | + |
| 164 | + def after_eval_forward(self, strategy: SupervisedTemplate, **kwargs): |
| 165 | + old_classes = strategy.experience.previous_classes |
| 166 | + new_classes = strategy.experience.classes_in_this_experience |
| 167 | + if not old_classes: |
| 168 | + return |
| 169 | + |
| 170 | + outputs = strategy.mb_output |
| 171 | + targets = strategy.mbatch[1] |
| 172 | + |
| 173 | + # rectify predicted scores (Eq. 1 in the paper) |
| 174 | + for i in range(len(targets)): |
| 175 | + # if the top-1 class predicted by the network is a new one, rectify the score |
| 176 | + if outputs[i].argmax().item() in new_classes: |
| 177 | + for cls in old_classes: |
| 178 | + o_exp = self.classes2exp[cls] |
| 179 | + if ( |
| 180 | + self.current_classes_means[cls] == 0 |
| 181 | + ): # when evaluation is done before training |
| 182 | + continue |
| 183 | + outputs[i, cls] *= ( |
| 184 | + self.init_classes_means[cls] / self.current_classes_means[cls] |
| 185 | + ) * (self.models_confidence[-1] / self.models_confidence[o_exp]) |
| 186 | + # otherwise, rectification is not done because an old class is directly predicted |
| 187 | + |
| 188 | + |
| 189 | +__all__ = [ |
| 190 | + "IL2MPlugin", |
| 191 | +] |
0 commit comments