Upload folder using huggingface_hub
Browse files- convs/__init__.py +0 -0
- convs/augmentation.py +104 -0
- convs/cifar_resnet.py +207 -0
- convs/conv_cifar.py +77 -0
- convs/conv_imagenet.py +82 -0
- convs/linears.py +168 -0
- convs/memo_cifar_resnet.py +213 -0
- convs/memo_resnet.py +385 -0
- convs/modified_represnet.py +177 -0
- convs/resnet.py +414 -0
- convs/resnet_cbam.py +267 -0
- convs/ucir_cifar_resnet.py +204 -0
- convs/ucir_resnet.py +299 -0
- exps/blcl.json +30 -0
- exps/ewc.json +14 -0
- exps/finetune.json +13 -0
- exps/icarl.json +14 -0
- exps/lwf.json +13 -0
- exps/memo.json +30 -0
- exps/replay.json +13 -0
- main.py +55 -0
- models/__init__.py +0 -0
- models/base.py +511 -0
- models/blcl.py +455 -0
- models/der.py +230 -0
- models/ewc.py +275 -0
- models/finetune.py +231 -0
- models/foster.py +445 -0
- models/icarl.py +237 -0
- models/lwf.py +222 -0
- models/memo.py +386 -0
- models/replay.py +213 -0
- trainer.py +149 -0
- utils/__init__.py +0 -0
- utils/augmentation.py +122 -0
- utils/bayesian_weighting.py +34 -0
- utils/cluster_analysis.py +27 -0
- utils/contrastive_loss.py +98 -0
- utils/data.py +202 -0
- utils/data_manager.py +324 -0
- utils/factory.py +27 -0
- utils/inc_net.py +897 -0
- utils/ops.py +121 -0
- utils/rl_utils/ddpg.py +206 -0
- utils/rl_utils/rl_utils.py +20 -0
- utils/toolkit.py +115 -0
- utils/tsne.py +388 -0
convs/__init__.py
ADDED
|
File without changes
|
convs/augmentation.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from torchvision.utils import save_image
|
| 6 |
+
import torchvision.transforms as tvts
|
| 7 |
+
import random
|
| 8 |
+
from os import listdir
|
| 9 |
+
from os.path import isfile, join
|
| 10 |
+
import shutil
|
| 11 |
+
|
| 12 |
+
# Define a list of augmentation transformations to be applied to images
|
| 13 |
+
transforms = [
|
| 14 |
+
tvts.ColorJitter(brightness=.5, hue=.3), # Adjust brightness and hue
|
| 15 |
+
tvts.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5.)), # Apply Gaussian blur with random parameters
|
| 16 |
+
tvts.RandomAdjustSharpness(sharpness_factor=2), # Adjust image sharpness
|
| 17 |
+
tvts.RandomRotation(degrees=(0, 180)), # Rotate images randomly between 0 and 180 degrees
|
| 18 |
+
tvts.RandomHorizontalFlip(p=0.5), # Randomly flip images horizontally
|
| 19 |
+
tvts.RandomVerticalFlip(p=0.5) # Randomly flip images vertically
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
# Select a specified number of random images from a list
|
| 23 |
+
def select_random_imgs(img_list, count):
|
| 24 |
+
return random.sample(img_list, count)
|
| 25 |
+
|
| 26 |
+
# Create a new folder name by adding "augment" to the original name
|
| 27 |
+
def create_foldername(fname):
|
| 28 |
+
names = fname.split("_")
|
| 29 |
+
names.insert(2, "augment")
|
| 30 |
+
return "_".join(names)
|
| 31 |
+
|
| 32 |
+
# Save original images to a new destination folder without applying transformations
|
| 33 |
+
def save_original_imgs(source_fname, dest_fname, img_files):
|
| 34 |
+
for img in img_files:
|
| 35 |
+
img_name = img.split(".")[0]
|
| 36 |
+
img = open_PILimg(path=os.path.join(source_fname, img))
|
| 37 |
+
save_image(tvts.ToTensor()(img), os.path.join(dest_fname, "{}.jpg".format(img_name)))
|
| 38 |
+
|
| 39 |
+
# Select a specified number of random files and copy them to the destination folder
|
| 40 |
+
def select_random_files(count, source_fname, dest_fname):
|
| 41 |
+
files = os.listdir(source_fname)
|
| 42 |
+
files = select_random_imgs(files, count=count)
|
| 43 |
+
|
| 44 |
+
# Iterate through the files and copy them to the destination folder
|
| 45 |
+
for file in files:
|
| 46 |
+
source_path = os.path.join(source_fname, file)
|
| 47 |
+
destination_path = os.path.join(dest_fname, file)
|
| 48 |
+
shutil.copy(source_path, destination_path)
|
| 49 |
+
print(f"Copied {file} to {dest_fname}")
|
| 50 |
+
|
| 51 |
+
# Open an image file using PIL and convert it to RGB format
|
| 52 |
+
def open_PILimg(path):
|
| 53 |
+
return Image.open(path).convert("RGB")
|
| 54 |
+
|
| 55 |
+
# Save a PIL image to the specified path
|
| 56 |
+
def save_PILimg(path, img):
|
| 57 |
+
save_image(tvts.ToTensor()(img), "{}.jpg".format(path))
|
| 58 |
+
|
| 59 |
+
# Function to augment images in a specific folder
|
| 60 |
+
def augment_folder(root_fname, fname, augment_count=25):
|
| 61 |
+
# Get the list of all images in the folder
|
| 62 |
+
onlyfiles = os.listdir(os.path.join(root_fname, fname))
|
| 63 |
+
print("Before augmentation, number of images in {} is {}".format(root_fname, len(onlyfiles)))
|
| 64 |
+
|
| 65 |
+
# Randomly select images to be augmented
|
| 66 |
+
random_imgs = select_random_imgs(onlyfiles, len(onlyfiles))
|
| 67 |
+
augment_fname = create_foldername(root_fname)
|
| 68 |
+
|
| 69 |
+
# Create folder for augmented images if it does not exist
|
| 70 |
+
if not os.path.exists(augment_fname):
|
| 71 |
+
os.mkdir(augment_fname)
|
| 72 |
+
|
| 73 |
+
# Create a sub-folder for the specific set of images
|
| 74 |
+
save_fname = os.path.join(augment_fname, fname)
|
| 75 |
+
if not os.path.exists(save_fname):
|
| 76 |
+
os.mkdir(save_fname)
|
| 77 |
+
|
| 78 |
+
# Save the original images in the new folder
|
| 79 |
+
save_original_imgs(source_fname=os.path.join(root_fname, fname),
|
| 80 |
+
dest_fname=os.path.join(augment_fname, fname),
|
| 81 |
+
img_files=onlyfiles)
|
| 82 |
+
|
| 83 |
+
# Apply transformations and save augmented images
|
| 84 |
+
for img in random_imgs:
|
| 85 |
+
img_name = img.split(".")[0]
|
| 86 |
+
img = open_PILimg(path=os.path.join(root_fname, fname, img))
|
| 87 |
+
|
| 88 |
+
for transform in transforms:
|
| 89 |
+
transname = transform.__class__.__name__
|
| 90 |
+
transformed_imgs = [transform(img) for _ in range(augment_count)]
|
| 91 |
+
for i, trans_img in enumerate(transformed_imgs):
|
| 92 |
+
save_image(tvts.ToTensor()(trans_img), os.path.join(save_fname, "trans_img_{}_{}_{}.jpg".format(img_name, transname, i)))
|
| 93 |
+
|
| 94 |
+
print("After augmentation, number of images in {} is {}".format(save_fname, len(os.listdir(save_fname))))
|
| 95 |
+
|
| 96 |
+
# Main block to iterate over root folders ("Train" and "Test") and apply augmentations
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
root_folder = [["Train"], ["Test"]]
|
| 99 |
+
for root in root_folder:
|
| 100 |
+
# List all subfolders within the root directory
|
| 101 |
+
folders = [f for f in os.listdir(root) if os.path.isdir(os.path.join(root, f))]
|
| 102 |
+
# Apply augmentation to each subfolder
|
| 103 |
+
for folder in folders:
|
| 104 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Reference:
|
| 3 |
+
https://github.com/khurramjaved96/incremental-learning/blob/autoencoders/model/resnet32.py
|
| 4 |
+
'''
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class DownsampleA(nn.Module):
|
| 13 |
+
def __init__(self, nIn, nOut, stride):
|
| 14 |
+
super(DownsampleA, self).__init__()
|
| 15 |
+
assert stride == 2
|
| 16 |
+
self.avg = nn.AvgPool2d(kernel_size=1, stride=stride)
|
| 17 |
+
|
| 18 |
+
def forward(self, x):
|
| 19 |
+
x = self.avg(x)
|
| 20 |
+
return torch.cat((x, x.mul(0)), 1)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class DownsampleB(nn.Module):
|
| 24 |
+
def __init__(self, nIn, nOut, stride):
|
| 25 |
+
super(DownsampleB, self).__init__()
|
| 26 |
+
self.conv = nn.Conv2d(nIn, nOut, kernel_size=1, stride=stride, padding=0, bias=False)
|
| 27 |
+
self.bn = nn.BatchNorm2d(nOut)
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
x = self.conv(x)
|
| 31 |
+
x = self.bn(x)
|
| 32 |
+
return x
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class DownsampleC(nn.Module):
|
| 36 |
+
def __init__(self, nIn, nOut, stride):
|
| 37 |
+
super(DownsampleC, self).__init__()
|
| 38 |
+
assert stride != 1 or nIn != nOut
|
| 39 |
+
self.conv = nn.Conv2d(nIn, nOut, kernel_size=1, stride=stride, padding=0, bias=False)
|
| 40 |
+
|
| 41 |
+
def forward(self, x):
|
| 42 |
+
x = self.conv(x)
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class DownsampleD(nn.Module):
|
| 47 |
+
def __init__(self, nIn, nOut, stride):
|
| 48 |
+
super(DownsampleD, self).__init__()
|
| 49 |
+
assert stride == 2
|
| 50 |
+
self.conv = nn.Conv2d(nIn, nOut, kernel_size=2, stride=stride, padding=0, bias=False)
|
| 51 |
+
self.bn = nn.BatchNorm2d(nOut)
|
| 52 |
+
|
| 53 |
+
def forward(self, x):
|
| 54 |
+
x = self.conv(x)
|
| 55 |
+
x = self.bn(x)
|
| 56 |
+
return x
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ResNetBasicblock(nn.Module):
|
| 60 |
+
expansion = 1
|
| 61 |
+
|
| 62 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
| 63 |
+
super(ResNetBasicblock, self).__init__()
|
| 64 |
+
|
| 65 |
+
self.conv_a = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
|
| 66 |
+
self.bn_a = nn.BatchNorm2d(planes)
|
| 67 |
+
|
| 68 |
+
self.conv_b = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
|
| 69 |
+
self.bn_b = nn.BatchNorm2d(planes)
|
| 70 |
+
|
| 71 |
+
self.downsample = downsample
|
| 72 |
+
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
residual = x
|
| 75 |
+
|
| 76 |
+
basicblock = self.conv_a(x)
|
| 77 |
+
basicblock = self.bn_a(basicblock)
|
| 78 |
+
basicblock = F.relu(basicblock, inplace=True)
|
| 79 |
+
|
| 80 |
+
basicblock = self.conv_b(basicblock)
|
| 81 |
+
basicblock = self.bn_b(basicblock)
|
| 82 |
+
|
| 83 |
+
if self.downsample is not None:
|
| 84 |
+
residual = self.downsample(x)
|
| 85 |
+
|
| 86 |
+
return F.relu(residual + basicblock, inplace=True)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class CifarResNet(nn.Module):
|
| 90 |
+
"""
|
| 91 |
+
ResNet optimized for the Cifar Dataset, as specified in
|
| 92 |
+
https://arxiv.org/abs/1512.03385.pdf
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def __init__(self, block, depth, channels=3):
|
| 96 |
+
super(CifarResNet, self).__init__()
|
| 97 |
+
|
| 98 |
+
# Model type specifies number of layers for CIFAR-10 and CIFAR-100 model
|
| 99 |
+
assert (depth - 2) % 6 == 0, 'depth should be one of 20, 32, 44, 56, 110'
|
| 100 |
+
layer_blocks = (depth - 2) // 6
|
| 101 |
+
|
| 102 |
+
self.conv_1_3x3 = nn.Conv2d(channels, 16, kernel_size=3, stride=1, padding=1, bias=False)
|
| 103 |
+
self.bn_1 = nn.BatchNorm2d(16)
|
| 104 |
+
|
| 105 |
+
self.inplanes = 16
|
| 106 |
+
self.stage_1 = self._make_layer(block, 16, layer_blocks, 1)
|
| 107 |
+
self.stage_2 = self._make_layer(block, 32, layer_blocks, 2)
|
| 108 |
+
self.stage_3 = self._make_layer(block, 64, layer_blocks, 2)
|
| 109 |
+
self.avgpool = nn.AvgPool2d(8)
|
| 110 |
+
self.out_dim = 64 * block.expansion
|
| 111 |
+
#self.fc = nn.Linear(64*block.expansion, 10)
|
| 112 |
+
|
| 113 |
+
for m in self.modules():
|
| 114 |
+
if isinstance(m, nn.Conv2d):
|
| 115 |
+
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
| 116 |
+
m.weight.data.normal_(0, math.sqrt(2. / n))
|
| 117 |
+
# m.bias.data.zero_()
|
| 118 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 119 |
+
m.weight.data.fill_(1)
|
| 120 |
+
m.bias.data.zero_()
|
| 121 |
+
elif isinstance(m, nn.Linear):
|
| 122 |
+
nn.init.kaiming_normal_(m.weight)
|
| 123 |
+
m.bias.data.zero_()
|
| 124 |
+
|
| 125 |
+
def _make_layer(self, block, planes, blocks, stride=1):
|
| 126 |
+
downsample = None
|
| 127 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 128 |
+
downsample = DownsampleA(self.inplanes, planes * block.expansion, stride)
|
| 129 |
+
|
| 130 |
+
layers = []
|
| 131 |
+
layers.append(block(self.inplanes, planes, stride, downsample))
|
| 132 |
+
self.inplanes = planes * block.expansion
|
| 133 |
+
for i in range(1, blocks):
|
| 134 |
+
layers.append(block(self.inplanes, planes))
|
| 135 |
+
|
| 136 |
+
return nn.Sequential(*layers)
|
| 137 |
+
|
| 138 |
+
def forward(self, x):
|
| 139 |
+
x = self.conv_1_3x3(x) # [bs, 16, 32, 32]
|
| 140 |
+
x = F.relu(self.bn_1(x), inplace=True)
|
| 141 |
+
|
| 142 |
+
x_1 = self.stage_1(x) # [bs, 16, 32, 32]
|
| 143 |
+
x_2 = self.stage_2(x_1) # [bs, 32, 16, 16]
|
| 144 |
+
x_3 = self.stage_3(x_2) # [bs, 64, 8, 8]
|
| 145 |
+
|
| 146 |
+
pooled = self.avgpool(x_3) # [bs, 64, 1, 1]
|
| 147 |
+
features = pooled.view(pooled.size(0), -1) # [bs, 64]
|
| 148 |
+
|
| 149 |
+
return {
|
| 150 |
+
'fmaps': [x_1, x_2, x_3],
|
| 151 |
+
'features': features
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def last_conv(self):
|
| 156 |
+
return self.stage_3[-1].conv_b
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def resnet20mnist():
|
| 160 |
+
"""Constructs a ResNet-20 model for MNIST."""
|
| 161 |
+
model = CifarResNet(ResNetBasicblock, 20, 1)
|
| 162 |
+
return model
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def resnet32mnist():
|
| 166 |
+
"""Constructs a ResNet-32 model for MNIST."""
|
| 167 |
+
model = CifarResNet(ResNetBasicblock, 32, 1)
|
| 168 |
+
return model
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def resnet20():
|
| 172 |
+
"""Constructs a ResNet-20 model for CIFAR-10."""
|
| 173 |
+
model = CifarResNet(ResNetBasicblock, 20)
|
| 174 |
+
return model
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def resnet32():
|
| 178 |
+
"""Constructs a ResNet-32 model for CIFAR-10."""
|
| 179 |
+
model = CifarResNet(ResNetBasicblock, 32)
|
| 180 |
+
return model
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def resnet44():
|
| 184 |
+
"""Constructs a ResNet-44 model for CIFAR-10."""
|
| 185 |
+
model = CifarResNet(ResNetBasicblock, 44)
|
| 186 |
+
return model
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def resnet56():
|
| 190 |
+
"""Constructs a ResNet-56 model for CIFAR-10."""
|
| 191 |
+
model = CifarResNet(ResNetBasicblock, 56)
|
| 192 |
+
return model
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def resnet110():
|
| 196 |
+
"""Constructs a ResNet-110 model for CIFAR-10."""
|
| 197 |
+
model = CifarResNet(ResNetBasicblock, 110)
|
| 198 |
+
return model
|
| 199 |
+
|
| 200 |
+
# for auc
|
| 201 |
+
def resnet14():
|
| 202 |
+
model = CifarResNet(ResNetBasicblock, 14)
|
| 203 |
+
return model
|
| 204 |
+
|
| 205 |
+
def resnet26():
|
| 206 |
+
model = CifarResNet(ResNetBasicblock, 26)
|
| 207 |
+
return model
|
convs/conv_cifar.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
For MEMO implementations of CIFAR-ConvNet
|
| 3 |
+
Reference:
|
| 4 |
+
https://github.com/wangkiw/ICLR23-MEMO/blob/main/convs/conv_cifar.py
|
| 5 |
+
'''
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
# for cifar
|
| 11 |
+
def conv_block(in_channels, out_channels):
|
| 12 |
+
return nn.Sequential(
|
| 13 |
+
nn.Conv2d(in_channels, out_channels, 3, padding=1),
|
| 14 |
+
nn.BatchNorm2d(out_channels),
|
| 15 |
+
nn.ReLU(),
|
| 16 |
+
nn.MaxPool2d(2)
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
class ConvNet2(nn.Module):
|
| 20 |
+
def __init__(self, x_dim=3, hid_dim=64, z_dim=64):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.out_dim = 64
|
| 23 |
+
self.avgpool = nn.AvgPool2d(8)
|
| 24 |
+
self.encoder = nn.Sequential(
|
| 25 |
+
conv_block(x_dim, hid_dim),
|
| 26 |
+
conv_block(hid_dim, z_dim),
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
x = self.encoder(x)
|
| 31 |
+
x = self.avgpool(x)
|
| 32 |
+
features = x.view(x.shape[0], -1)
|
| 33 |
+
return {
|
| 34 |
+
"features":features
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
class GeneralizedConvNet2(nn.Module):
|
| 38 |
+
def __init__(self, x_dim=3, hid_dim=64, z_dim=64):
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.encoder = nn.Sequential(
|
| 41 |
+
conv_block(x_dim, hid_dim),
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
def forward(self, x):
|
| 45 |
+
base_features = self.encoder(x)
|
| 46 |
+
return base_features
|
| 47 |
+
|
| 48 |
+
class SpecializedConvNet2(nn.Module):
|
| 49 |
+
def __init__(self,hid_dim=64,z_dim=64):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.feature_dim = 64
|
| 52 |
+
self.avgpool = nn.AvgPool2d(8)
|
| 53 |
+
self.AdaptiveBlock = conv_block(hid_dim,z_dim)
|
| 54 |
+
|
| 55 |
+
def forward(self,x):
|
| 56 |
+
base_features = self.AdaptiveBlock(x)
|
| 57 |
+
pooled = self.avgpool(base_features)
|
| 58 |
+
features = pooled.view(pooled.size(0),-1)
|
| 59 |
+
return features
|
| 60 |
+
|
| 61 |
+
def conv2():
|
| 62 |
+
return ConvNet2()
|
| 63 |
+
|
| 64 |
+
def get_conv_a2fc():
|
| 65 |
+
basenet = GeneralizedConvNet2()
|
| 66 |
+
adaptivenet = SpecializedConvNet2()
|
| 67 |
+
return basenet,adaptivenet
|
| 68 |
+
|
| 69 |
+
if __name__ == '__main__':
|
| 70 |
+
a, b = get_conv_a2fc()
|
| 71 |
+
_base = sum(p.numel() for p in a.parameters())
|
| 72 |
+
_adap = sum(p.numel() for p in b.parameters())
|
| 73 |
+
print(f"conv :{_base+_adap}")
|
| 74 |
+
|
| 75 |
+
conv2 = conv2()
|
| 76 |
+
conv2_sum = sum(p.numel() for p in conv2.parameters())
|
| 77 |
+
print(f"conv2 :{conv2_sum}")
|
convs/conv_imagenet.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
For MEMO implementations of ImageNet-ConvNet
|
| 3 |
+
Reference:
|
| 4 |
+
https://github.com/wangkiw/ICLR23-MEMO/blob/main/convs/conv_imagenet.py
|
| 5 |
+
'''
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
# for imagenet
|
| 10 |
+
def first_block(in_channels, out_channels):
|
| 11 |
+
return nn.Sequential(
|
| 12 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=7, stride=2, padding=3),
|
| 13 |
+
nn.BatchNorm2d(out_channels),
|
| 14 |
+
nn.ReLU(),
|
| 15 |
+
nn.MaxPool2d(2)
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
def conv_block(in_channels, out_channels):
|
| 19 |
+
return nn.Sequential(
|
| 20 |
+
nn.Conv2d(in_channels, out_channels, 3, padding=1),
|
| 21 |
+
nn.BatchNorm2d(out_channels),
|
| 22 |
+
nn.ReLU(),
|
| 23 |
+
nn.MaxPool2d(2)
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
class ConvNet(nn.Module):
|
| 27 |
+
def __init__(self, x_dim=3, hid_dim=128, z_dim=512):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.block1 = first_block(x_dim, hid_dim)
|
| 30 |
+
self.block2 = conv_block(hid_dim, hid_dim)
|
| 31 |
+
self.block3 = conv_block(hid_dim, hid_dim)
|
| 32 |
+
self.block4 = conv_block(hid_dim, z_dim)
|
| 33 |
+
self.avgpool = nn.AvgPool2d(7)
|
| 34 |
+
self.out_dim = 512
|
| 35 |
+
|
| 36 |
+
def forward(self, x):
|
| 37 |
+
x = self.block1(x)
|
| 38 |
+
x = self.block2(x)
|
| 39 |
+
x = self.block3(x)
|
| 40 |
+
x = self.block4(x)
|
| 41 |
+
|
| 42 |
+
x = self.avgpool(x)
|
| 43 |
+
features = x.view(x.shape[0], -1)
|
| 44 |
+
|
| 45 |
+
return {
|
| 46 |
+
"features": features
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
class GeneralizedConvNet(nn.Module):
|
| 50 |
+
def __init__(self, x_dim=3, hid_dim=128, z_dim=512):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.block1 = first_block(x_dim, hid_dim)
|
| 53 |
+
self.block2 = conv_block(hid_dim, hid_dim)
|
| 54 |
+
self.block3 = conv_block(hid_dim, hid_dim)
|
| 55 |
+
|
| 56 |
+
def forward(self, x):
|
| 57 |
+
x = self.block1(x)
|
| 58 |
+
x = self.block2(x)
|
| 59 |
+
x = self.block3(x)
|
| 60 |
+
return x
|
| 61 |
+
|
| 62 |
+
class SpecializedConvNet(nn.Module):
|
| 63 |
+
def __init__(self, hid_dim=128,z_dim=512):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.block4 = conv_block(hid_dim, z_dim)
|
| 66 |
+
self.avgpool = nn.AvgPool2d(7)
|
| 67 |
+
self.feature_dim = 512
|
| 68 |
+
|
| 69 |
+
def forward(self, x):
|
| 70 |
+
x = self.block4(x)
|
| 71 |
+
x = self.avgpool(x)
|
| 72 |
+
features = x.view(x.shape[0], -1)
|
| 73 |
+
return features
|
| 74 |
+
|
| 75 |
+
def conv4():
|
| 76 |
+
model = ConvNet()
|
| 77 |
+
return model
|
| 78 |
+
|
| 79 |
+
def conv_a2fc_imagenet():
|
| 80 |
+
_base = GeneralizedConvNet()
|
| 81 |
+
_adaptive_net = SpecializedConvNet()
|
| 82 |
+
return _base, _adaptive_net
|
convs/linears.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Reference:
|
| 3 |
+
https://github.com/hshustc/CVPR19_Incremental_Learning/blob/master/cifar100-class-incremental/modified_linear.py
|
| 4 |
+
'''
|
| 5 |
+
import math
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SimpleLinear(nn.Module):
|
| 12 |
+
'''
|
| 13 |
+
Reference:
|
| 14 |
+
https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/linear.py
|
| 15 |
+
'''
|
| 16 |
+
def __init__(self, in_features, out_features, bias=True):
|
| 17 |
+
super(SimpleLinear, self).__init__()
|
| 18 |
+
self.in_features = in_features
|
| 19 |
+
self.out_features = out_features
|
| 20 |
+
self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
|
| 21 |
+
if bias:
|
| 22 |
+
self.bias = nn.Parameter(torch.Tensor(out_features))
|
| 23 |
+
else:
|
| 24 |
+
self.register_parameter('bias', None)
|
| 25 |
+
self.reset_parameters()
|
| 26 |
+
|
| 27 |
+
def reset_parameters(self):
|
| 28 |
+
nn.init.kaiming_uniform_(self.weight, nonlinearity='linear')
|
| 29 |
+
nn.init.constant_(self.bias, 0)
|
| 30 |
+
|
| 31 |
+
def forward(self, input):
|
| 32 |
+
#print('input shape is -------->',input.shape)
|
| 33 |
+
return {'logits': F.linear(input, self.weight, self.bias)}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CosineLinear(nn.Module):
|
| 37 |
+
def __init__(self, in_features, out_features, nb_proxy=1, to_reduce=False, sigma=True):
|
| 38 |
+
super(CosineLinear, self).__init__()
|
| 39 |
+
self.in_features = in_features
|
| 40 |
+
self.out_features = out_features * nb_proxy
|
| 41 |
+
self.nb_proxy = nb_proxy
|
| 42 |
+
self.to_reduce = to_reduce
|
| 43 |
+
self.weight = nn.Parameter(torch.Tensor(self.out_features, in_features))
|
| 44 |
+
if sigma:
|
| 45 |
+
self.sigma = nn.Parameter(torch.Tensor(1))
|
| 46 |
+
else:
|
| 47 |
+
self.register_parameter('sigma', None)
|
| 48 |
+
self.reset_parameters()
|
| 49 |
+
|
| 50 |
+
def reset_parameters(self):
|
| 51 |
+
stdv = 1. / math.sqrt(self.weight.size(1))
|
| 52 |
+
self.weight.data.uniform_(-stdv, stdv)
|
| 53 |
+
if self.sigma is not None:
|
| 54 |
+
self.sigma.data.fill_(1)
|
| 55 |
+
|
| 56 |
+
def forward(self, input):
|
| 57 |
+
out = F.linear(F.normalize(input, p=2, dim=1), F.normalize(self.weight, p=2, dim=1))
|
| 58 |
+
|
| 59 |
+
if self.to_reduce:
|
| 60 |
+
# Reduce_proxy
|
| 61 |
+
out = reduce_proxies(out, self.nb_proxy)
|
| 62 |
+
|
| 63 |
+
if self.sigma is not None:
|
| 64 |
+
out = self.sigma * out
|
| 65 |
+
|
| 66 |
+
return {'logits': out}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class SplitCosineLinear(nn.Module):
|
| 70 |
+
def __init__(self, in_features, out_features1, out_features2, nb_proxy=1, sigma=True):
|
| 71 |
+
super(SplitCosineLinear, self).__init__()
|
| 72 |
+
self.in_features = in_features
|
| 73 |
+
self.out_features = (out_features1 + out_features2) * nb_proxy
|
| 74 |
+
self.nb_proxy = nb_proxy
|
| 75 |
+
self.fc1 = CosineLinear(in_features, out_features1, nb_proxy, False, False)
|
| 76 |
+
self.fc2 = CosineLinear(in_features, out_features2, nb_proxy, False, False)
|
| 77 |
+
if sigma:
|
| 78 |
+
self.sigma = nn.Parameter(torch.Tensor(1))
|
| 79 |
+
self.sigma.data.fill_(1)
|
| 80 |
+
else:
|
| 81 |
+
self.register_parameter('sigma', None)
|
| 82 |
+
|
| 83 |
+
def forward(self, x):
|
| 84 |
+
out1 = self.fc1(x)
|
| 85 |
+
out2 = self.fc2(x)
|
| 86 |
+
|
| 87 |
+
out = torch.cat((out1['logits'], out2['logits']), dim=1) # concatenate along the channel
|
| 88 |
+
|
| 89 |
+
# Reduce_proxy
|
| 90 |
+
out = reduce_proxies(out, self.nb_proxy)
|
| 91 |
+
|
| 92 |
+
if self.sigma is not None:
|
| 93 |
+
out = self.sigma * out
|
| 94 |
+
|
| 95 |
+
return {
|
| 96 |
+
'old_scores': reduce_proxies(out1['logits'], self.nb_proxy),
|
| 97 |
+
'new_scores': reduce_proxies(out2['logits'], self.nb_proxy),
|
| 98 |
+
'logits': out
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def reduce_proxies(out, nb_proxy):
|
| 103 |
+
if nb_proxy == 1:
|
| 104 |
+
return out
|
| 105 |
+
bs = out.shape[0]
|
| 106 |
+
nb_classes = out.shape[1] / nb_proxy
|
| 107 |
+
assert nb_classes.is_integer(), 'Shape error'
|
| 108 |
+
nb_classes = int(nb_classes)
|
| 109 |
+
|
| 110 |
+
simi_per_class = out.view(bs, nb_classes, nb_proxy)
|
| 111 |
+
attentions = F.softmax(simi_per_class, dim=-1)
|
| 112 |
+
|
| 113 |
+
return (attentions * simi_per_class).sum(-1)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
'''
|
| 117 |
+
class CosineLinear(nn.Module):
|
| 118 |
+
def __init__(self, in_features, out_features, sigma=True):
|
| 119 |
+
super(CosineLinear, self).__init__()
|
| 120 |
+
self.in_features = in_features
|
| 121 |
+
self.out_features = out_features
|
| 122 |
+
self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
|
| 123 |
+
if sigma:
|
| 124 |
+
self.sigma = nn.Parameter(torch.Tensor(1))
|
| 125 |
+
else:
|
| 126 |
+
self.register_parameter('sigma', None)
|
| 127 |
+
self.reset_parameters()
|
| 128 |
+
|
| 129 |
+
def reset_parameters(self):
|
| 130 |
+
stdv = 1. / math.sqrt(self.weight.size(1))
|
| 131 |
+
self.weight.data.uniform_(-stdv, stdv)
|
| 132 |
+
if self.sigma is not None:
|
| 133 |
+
self.sigma.data.fill_(1)
|
| 134 |
+
|
| 135 |
+
def forward(self, input):
|
| 136 |
+
out = F.linear(F.normalize(input, p=2, dim=1), F.normalize(self.weight, p=2, dim=1))
|
| 137 |
+
if self.sigma is not None:
|
| 138 |
+
out = self.sigma * out
|
| 139 |
+
return {'logits': out}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class SplitCosineLinear(nn.Module):
|
| 143 |
+
def __init__(self, in_features, out_features1, out_features2, sigma=True):
|
| 144 |
+
super(SplitCosineLinear, self).__init__()
|
| 145 |
+
self.in_features = in_features
|
| 146 |
+
self.out_features = out_features1 + out_features2
|
| 147 |
+
self.fc1 = CosineLinear(in_features, out_features1, False)
|
| 148 |
+
self.fc2 = CosineLinear(in_features, out_features2, False)
|
| 149 |
+
if sigma:
|
| 150 |
+
self.sigma = nn.Parameter(torch.Tensor(1))
|
| 151 |
+
self.sigma.data.fill_(1)
|
| 152 |
+
else:
|
| 153 |
+
self.register_parameter('sigma', None)
|
| 154 |
+
|
| 155 |
+
def forward(self, x):
|
| 156 |
+
out1 = self.fc1(x)
|
| 157 |
+
out2 = self.fc2(x)
|
| 158 |
+
|
| 159 |
+
out = torch.cat((out1['logits'], out2['logits']), dim=1) # concatenate along the channel
|
| 160 |
+
if self.sigma is not None:
|
| 161 |
+
out = self.sigma * out
|
| 162 |
+
|
| 163 |
+
return {
|
| 164 |
+
'old_scores': out1['logits'],
|
| 165 |
+
'new_scores': out2['logits'],
|
| 166 |
+
'logits': out
|
| 167 |
+
}
|
| 168 |
+
'''
|
convs/memo_cifar_resnet.py
ADDED
|
@@ -0,0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
For MEMO implementations of CIFAR-ResNet
|
| 3 |
+
Reference:
|
| 4 |
+
https://github.com/khurramjaved96/incremental-learning/blob/autoencoders/model/resnet32.py
|
| 5 |
+
'''
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
class DownsampleA(nn.Module):
|
| 14 |
+
"""
|
| 15 |
+
A downsampling block that uses average pooling.
|
| 16 |
+
"""
|
| 17 |
+
def __init__(self, nIn, nOut, stride):
|
| 18 |
+
super(DownsampleA, self).__init__()
|
| 19 |
+
assert stride == 2
|
| 20 |
+
self.avg = nn.AvgPool2d(kernel_size=1, stride=stride)
|
| 21 |
+
|
| 22 |
+
def forward(self, x):
|
| 23 |
+
x = self.avg(x)
|
| 24 |
+
return torch.cat((x, x.mul(0)), 1)
|
| 25 |
+
|
| 26 |
+
class ResNetBasicblock(nn.Module):
|
| 27 |
+
"""
|
| 28 |
+
Basic block for ResNet Memo.
|
| 29 |
+
"""
|
| 30 |
+
expansion = 1
|
| 31 |
+
|
| 32 |
+
def __init__(self, inplanes, planes, stride=1, nconv=2, downsample=None):
|
| 33 |
+
super(ResNetBasicblock, self).__init__()
|
| 34 |
+
self.nconv = nconv
|
| 35 |
+
self.conv_a = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
|
| 36 |
+
self.bn_a = nn.BatchNorm2d(planes)
|
| 37 |
+
if self.nconv == 2:
|
| 38 |
+
self.conv_b = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
|
| 39 |
+
self.bn_b = nn.BatchNorm2d(planes)
|
| 40 |
+
|
| 41 |
+
self.downsample = downsample
|
| 42 |
+
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
residual = x
|
| 45 |
+
|
| 46 |
+
basicblock = self.conv_a(x)
|
| 47 |
+
basicblock = self.bn_a(basicblock)
|
| 48 |
+
basicblock = F.relu(basicblock, inplace=True)
|
| 49 |
+
logging.debug('basicblock ---> {}'.format(basicblock.shape))
|
| 50 |
+
if self.nconv == 2:
|
| 51 |
+
basicblock = self.conv_b(basicblock)
|
| 52 |
+
basicblock = self.bn_b(basicblock)
|
| 53 |
+
logging.debug('basicblock in if block ---> {}'.format(basicblock.shape))
|
| 54 |
+
|
| 55 |
+
if self.downsample is not None:
|
| 56 |
+
residual = self.downsample(x)
|
| 57 |
+
logging.debug('basicblock in downsample ---> {}'.format(basicblock.shape))
|
| 58 |
+
|
| 59 |
+
logging.debug('Final residual ---> {}'.format(residual.shape))
|
| 60 |
+
logging.debug('Final basicblock ---> {}'.format(basicblock.shape))
|
| 61 |
+
return F.relu(residual + basicblock, inplace=True)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class GeneralizedResNet_cifar(nn.Module):
|
| 66 |
+
"""
|
| 67 |
+
Generalized ResNet for Memo.
|
| 68 |
+
"""
|
| 69 |
+
def __init__(self, block, depth, channels=3):
|
| 70 |
+
super(GeneralizedResNet_cifar, self).__init__()
|
| 71 |
+
assert (depth - 2) % 6 == 0, 'depth should be one of 20, 32, 44, 56, 110'
|
| 72 |
+
layer_blocks = (depth - 2) // 6
|
| 73 |
+
self.conv_1_3x3 = nn.Conv2d(channels, 16, kernel_size=3, stride=1, padding=1, bias=False)
|
| 74 |
+
self.bn_1 = nn.BatchNorm2d(16)
|
| 75 |
+
|
| 76 |
+
self.inplanes = 16
|
| 77 |
+
self.stage_1 = self._make_layer(block, 16, layer_blocks, 1)
|
| 78 |
+
self.stage_2 = self._make_layer(block, 32, layer_blocks, 2)
|
| 79 |
+
|
| 80 |
+
self.out_dim = 64 * block.expansion
|
| 81 |
+
|
| 82 |
+
for m in self.modules():
|
| 83 |
+
if isinstance(m, nn.Conv2d):
|
| 84 |
+
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
| 85 |
+
m.weight.data.normal_(0, math.sqrt(2. / n))
|
| 86 |
+
# m.bias.data.zero_()
|
| 87 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 88 |
+
m.weight.data.fill_(1)
|
| 89 |
+
m.bias.data.zero_()
|
| 90 |
+
elif isinstance(m, nn.Linear):
|
| 91 |
+
nn.init.kaiming_normal_(m.weight)
|
| 92 |
+
m.bias.data.zero_()
|
| 93 |
+
|
| 94 |
+
def _make_layer(self, block, planes, blocks, stride=1):
|
| 95 |
+
downsample = None
|
| 96 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 97 |
+
downsample = DownsampleA(self.inplanes, planes * block.expansion, stride)
|
| 98 |
+
|
| 99 |
+
layers = []
|
| 100 |
+
layers.append(block(self.inplanes, planes, stride=stride, downsample=downsample))
|
| 101 |
+
self.inplanes = planes * block.expansion
|
| 102 |
+
for i in range(1, blocks):
|
| 103 |
+
layers.append(block(self.inplanes, planes))
|
| 104 |
+
|
| 105 |
+
return nn.Sequential(*layers)
|
| 106 |
+
|
| 107 |
+
def forward(self, x):
|
| 108 |
+
x = self.conv_1_3x3(x) # [bs, 16, 32, 32]
|
| 109 |
+
logging.debug("GB:conv_1_3x3 --> {}".format(x.shape))
|
| 110 |
+
x = F.relu(self.bn_1(x), inplace=True)
|
| 111 |
+
|
| 112 |
+
x_1 = self.stage_1(x) # [bs, 16, 32, 32]
|
| 113 |
+
logging.debug("GB:stage_1 --> {}".format(x_1.shape))
|
| 114 |
+
x_2 = self.stage_2(x_1) # [bs, 32, 16, 16]
|
| 115 |
+
logging.debug("GB:stage_2 --> {}".format(x_2.shape))
|
| 116 |
+
return x_2
|
| 117 |
+
|
| 118 |
+
class SpecializedResNet_cifar(nn.Module):
|
| 119 |
+
"""
|
| 120 |
+
Specialized ResNet for Memo.
|
| 121 |
+
"""
|
| 122 |
+
def __init__(self, block, depth, nconv=[2,2], inplanes=32, feature_dim=64):
|
| 123 |
+
super(SpecializedResNet_cifar, self).__init__()
|
| 124 |
+
self.inplanes = inplanes
|
| 125 |
+
self.feature_dim = feature_dim
|
| 126 |
+
layer_blocks = (depth - 2) // 6
|
| 127 |
+
self.final_stage = self._make_layer(block, 64, layer_blocks, nconv, 2)
|
| 128 |
+
self.avgpool = nn.AvgPool2d(8)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
for m in self.modules():
|
| 132 |
+
if isinstance(m, nn.Conv2d):
|
| 133 |
+
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
| 134 |
+
m.weight.data.normal_(0, math.sqrt(2. / n))
|
| 135 |
+
# m.bias.data.zero_()
|
| 136 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 137 |
+
m.weight.data.fill_(1)
|
| 138 |
+
m.bias.data.zero_()
|
| 139 |
+
elif isinstance(m, nn.Linear):
|
| 140 |
+
nn.init.kaiming_normal_(m.weight)
|
| 141 |
+
m.bias.data.zero_()
|
| 142 |
+
|
| 143 |
+
def _make_layer(self, block, planes, blocks, nconv, stride=2):
|
| 144 |
+
downsample = None
|
| 145 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 146 |
+
downsample = DownsampleA(self.inplanes, planes * block.expansion, stride)
|
| 147 |
+
layers = []
|
| 148 |
+
layers.append(block(self.inplanes, planes, stride=stride, downsample=downsample))
|
| 149 |
+
self.inplanes = planes * block.expansion
|
| 150 |
+
for i in range(1, blocks - 2):
|
| 151 |
+
layers.append(block(self.inplanes, planes))
|
| 152 |
+
layers.append(block(self.inplanes, planes, nconv=nconv[0]))
|
| 153 |
+
if len(nconv)>1:
|
| 154 |
+
layers.append(block(self.inplanes, planes, nconv=nconv[1]))
|
| 155 |
+
return nn.Sequential(*layers)
|
| 156 |
+
|
| 157 |
+
def forward(self, base_feature_map):
|
| 158 |
+
final_feature_map = self.final_stage(base_feature_map)
|
| 159 |
+
logging.debug("SB:final_stage --> {}".format(final_feature_map.shape))
|
| 160 |
+
pooled = self.avgpool(final_feature_map)
|
| 161 |
+
logging.debug("SB:pooled --> {}".format(pooled.shape))
|
| 162 |
+
features = pooled.view(pooled.size(0), -1) #bs x 64
|
| 163 |
+
logging.debug("SB:features --> {}".format(features.shape))
|
| 164 |
+
return features
|
| 165 |
+
|
| 166 |
+
#For cifar & MEMO
|
| 167 |
+
def get_resnet8_a2fc():
|
| 168 |
+
basenet = GeneralizedResNet_cifar(ResNetBasicblock,8)
|
| 169 |
+
adaptivenet = SpecializedResNet_cifar(ResNetBasicblock,8)
|
| 170 |
+
return basenet,adaptivenet
|
| 171 |
+
|
| 172 |
+
def get_resnet14_a2fc():
|
| 173 |
+
basenet = GeneralizedResNet_cifar(ResNetBasicblock,14)
|
| 174 |
+
adaptivenet = SpecializedResNet_cifar(ResNetBasicblock,14)
|
| 175 |
+
return basenet,adaptivenet
|
| 176 |
+
|
| 177 |
+
def get_resnet20_a2fc():
|
| 178 |
+
basenet = GeneralizedResNet_cifar(ResNetBasicblock,20)
|
| 179 |
+
adaptivenet = SpecializedResNet_cifar(ResNetBasicblock,20)
|
| 180 |
+
return basenet,adaptivenet
|
| 181 |
+
|
| 182 |
+
def get_resnet26_a2fc():
|
| 183 |
+
basenet = GeneralizedResNet_cifar(ResNetBasicblock,26)
|
| 184 |
+
adaptivenet = SpecializedResNet_cifar(ResNetBasicblock,26)
|
| 185 |
+
return basenet,adaptivenet
|
| 186 |
+
|
| 187 |
+
def get_resnet32_a2fc(args):
|
| 188 |
+
"""
|
| 189 |
+
Returns a pair of base and adaptive networks for ResNet-32 architecture.
|
| 190 |
+
Args:
|
| 191 |
+
args (dict): A dictionary containing parameters such as 'curr' task index and 'layers'.
|
| 192 |
+
"""
|
| 193 |
+
logging.debug('Curr Task : {}'.format(args['curr']))
|
| 194 |
+
nconv = args['layers'][args['curr']] if args['curr'] > -1 else [2, 2]
|
| 195 |
+
logging.debug('Curr Task {}: nconv {}'.format(args['curr'], nconv))
|
| 196 |
+
basenet = GeneralizedResNet_cifar(ResNetBasicblock,32)
|
| 197 |
+
adaptivenet = SpecializedResNet_cifar(ResNetBasicblock,32,nconv=nconv)
|
| 198 |
+
return basenet,adaptivenet
|
| 199 |
+
|
| 200 |
+
def get_resnet56_a2fc(args):
|
| 201 |
+
"""
|
| 202 |
+
Returns a pair of base and adaptive networks for ResNet-56 architecture.
|
| 203 |
+
Args:
|
| 204 |
+
args (dict): A dictionary containing parameters such as 'curr' task index and 'layers'.
|
| 205 |
+
"""
|
| 206 |
+
logging.debug('Curr Task : {}'.format(args['curr']))
|
| 207 |
+
nconv = args['layers'][args['curr']] if args['curr'] > -1 else [2, 2]
|
| 208 |
+
logging.debug('Curr Task {}: nconv {}'.format(args['curr'], nconv))
|
| 209 |
+
basenet = GeneralizedResNet_cifar(ResNetBasicblock,32)
|
| 210 |
+
adaptivenet = SpecializedResNet_cifar(ResNetBasicblock,56,nconv=nconv)
|
| 211 |
+
return basenet,adaptivenet
|
| 212 |
+
|
| 213 |
+
|
convs/memo_resnet.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
| 1 |
+
'''
|
| 2 |
+
For MEMO implementations of ImageNet-ResNet
|
| 3 |
+
Reference:
|
| 4 |
+
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
|
| 5 |
+
'''
|
| 6 |
+
import logging
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
try:
|
| 10 |
+
from torchvision.models.utils import load_state_dict_from_url
|
| 11 |
+
except:
|
| 12 |
+
from torch.hub import load_state_dict_from_url
|
| 13 |
+
|
| 14 |
+
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
|
| 15 |
+
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
|
| 16 |
+
'wide_resnet50_2', 'wide_resnet101_2']
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
model_urls = {
|
| 20 |
+
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
|
| 21 |
+
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
|
| 22 |
+
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
|
| 23 |
+
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
|
| 24 |
+
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
|
| 25 |
+
'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
|
| 26 |
+
'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
|
| 27 |
+
'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
|
| 28 |
+
'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
|
| 33 |
+
"""3x3 convolution with padding"""
|
| 34 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
| 35 |
+
padding=dilation, groups=groups, bias=False, dilation=dilation)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def conv1x1(in_planes, out_planes, stride=1):
|
| 39 |
+
"""1x1 convolution"""
|
| 40 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class BasicBlock(nn.Module):
|
| 44 |
+
expansion = 1
|
| 45 |
+
__constants__ = ['downsample']
|
| 46 |
+
|
| 47 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
|
| 48 |
+
base_width=64, dilation=1, norm_layer=None, nconv=2):
|
| 49 |
+
super(BasicBlock, self).__init__()
|
| 50 |
+
if norm_layer is None:
|
| 51 |
+
norm_layer = nn.BatchNorm2d
|
| 52 |
+
if groups != 1 or base_width != 64:
|
| 53 |
+
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
|
| 54 |
+
if dilation > 1:
|
| 55 |
+
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
|
| 56 |
+
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
|
| 57 |
+
self.nconv = nconv
|
| 58 |
+
self.conv1 = conv3x3(inplanes, planes, stride)
|
| 59 |
+
self.bn1 = norm_layer(planes)
|
| 60 |
+
self.relu = nn.ReLU(inplace=True)
|
| 61 |
+
self.downsample = downsample
|
| 62 |
+
self.stride = stride
|
| 63 |
+
if self.nconv == 2:
|
| 64 |
+
self.conv2 = conv3x3(planes, planes)
|
| 65 |
+
self.bn2 = norm_layer(planes)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def forward(self, x):
|
| 69 |
+
identity = x
|
| 70 |
+
|
| 71 |
+
out = self.conv1(x)
|
| 72 |
+
out = self.bn1(out)
|
| 73 |
+
out = self.relu(out)
|
| 74 |
+
|
| 75 |
+
if self.nconv == 2:
|
| 76 |
+
out = self.conv2(out)
|
| 77 |
+
out = self.bn2(out)
|
| 78 |
+
|
| 79 |
+
if self.downsample is not None:
|
| 80 |
+
identity = self.downsample(x)
|
| 81 |
+
|
| 82 |
+
out = out + identity
|
| 83 |
+
out = self.relu(out)
|
| 84 |
+
|
| 85 |
+
return out
|
| 86 |
+
|
| 87 |
+
class BasicBlock1Conv(nn.Module):
|
| 88 |
+
expansion = 1
|
| 89 |
+
__constants__ = ['downsample']
|
| 90 |
+
|
| 91 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
|
| 92 |
+
base_width=64, dilation=1, norm_layer=None):
|
| 93 |
+
super(BasicBlock1Conv, self).__init__()
|
| 94 |
+
if norm_layer is None:
|
| 95 |
+
norm_layer = nn.BatchNorm2d
|
| 96 |
+
if groups != 1 or base_width != 64:
|
| 97 |
+
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
|
| 98 |
+
if dilation > 1:
|
| 99 |
+
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
|
| 100 |
+
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
|
| 101 |
+
self.conv1 = conv3x3(inplanes, planes, stride)
|
| 102 |
+
self.bn1 = norm_layer(planes)
|
| 103 |
+
self.relu = nn.ReLU(inplace=True)
|
| 104 |
+
|
| 105 |
+
self.downsample = downsample
|
| 106 |
+
self.stride = stride
|
| 107 |
+
|
| 108 |
+
def forward(self, x):
|
| 109 |
+
identity = x
|
| 110 |
+
out = self.conv1(x)
|
| 111 |
+
out = self.bn1(out)
|
| 112 |
+
if self.downsample is not None:
|
| 113 |
+
identity = self.downsample(x)
|
| 114 |
+
out += identity
|
| 115 |
+
out = self.relu(out)
|
| 116 |
+
return out
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class Bottleneck(nn.Module):
|
| 120 |
+
expansion = 4
|
| 121 |
+
__constants__ = ['downsample']
|
| 122 |
+
|
| 123 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
|
| 124 |
+
base_width=64, dilation=1, norm_layer=None):
|
| 125 |
+
super(Bottleneck, self).__init__()
|
| 126 |
+
if norm_layer is None:
|
| 127 |
+
norm_layer = nn.BatchNorm2d
|
| 128 |
+
width = int(planes * (base_width / 64.)) * groups
|
| 129 |
+
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
|
| 130 |
+
self.conv1 = conv1x1(inplanes, width)
|
| 131 |
+
self.bn1 = norm_layer(width)
|
| 132 |
+
self.conv2 = conv3x3(width, width, stride, groups, dilation)
|
| 133 |
+
self.bn2 = norm_layer(width)
|
| 134 |
+
self.conv3 = conv1x1(width, planes * self.expansion)
|
| 135 |
+
self.bn3 = norm_layer(planes * self.expansion)
|
| 136 |
+
self.relu = nn.ReLU(inplace=True)
|
| 137 |
+
self.downsample = downsample
|
| 138 |
+
self.stride = stride
|
| 139 |
+
|
| 140 |
+
def forward(self, x):
|
| 141 |
+
identity = x
|
| 142 |
+
|
| 143 |
+
out = self.conv1(x)
|
| 144 |
+
out = self.bn1(out)
|
| 145 |
+
out = self.relu(out)
|
| 146 |
+
|
| 147 |
+
out = self.conv2(out)
|
| 148 |
+
out = self.bn2(out)
|
| 149 |
+
out = self.relu(out)
|
| 150 |
+
|
| 151 |
+
out = self.conv3(out)
|
| 152 |
+
out = self.bn3(out)
|
| 153 |
+
|
| 154 |
+
if self.downsample is not None:
|
| 155 |
+
identity = self.downsample(x)
|
| 156 |
+
|
| 157 |
+
out += identity
|
| 158 |
+
out = self.relu(out)
|
| 159 |
+
|
| 160 |
+
return out
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class GeneralizedResNet_imagenet(nn.Module):
|
| 164 |
+
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
|
| 165 |
+
groups=1, width_per_group=64, replace_stride_with_dilation=None,
|
| 166 |
+
norm_layer=None):
|
| 167 |
+
super(GeneralizedResNet_imagenet, self).__init__()
|
| 168 |
+
if norm_layer is None:
|
| 169 |
+
norm_layer = nn.BatchNorm2d
|
| 170 |
+
self._norm_layer = norm_layer
|
| 171 |
+
self.inplanes = 64
|
| 172 |
+
self.dilation = 1
|
| 173 |
+
if replace_stride_with_dilation is None:
|
| 174 |
+
# each element in the tuple indicates if we should replace
|
| 175 |
+
# the 2x2 stride with a dilated convolution instead
|
| 176 |
+
replace_stride_with_dilation = [False, False, False]
|
| 177 |
+
if len(replace_stride_with_dilation) != 3:
|
| 178 |
+
raise ValueError("replace_stride_with_dilation should be None "
|
| 179 |
+
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
|
| 180 |
+
self.groups = groups
|
| 181 |
+
self.base_width = width_per_group
|
| 182 |
+
self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, # stride=2 -> stride=1 for cifar
|
| 183 |
+
bias=False)
|
| 184 |
+
self.bn1 = norm_layer(self.inplanes)
|
| 185 |
+
self.relu = nn.ReLU(inplace=True)
|
| 186 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) # Removed in _forward_impl for cifar
|
| 187 |
+
logging.debug("Making layer 1")
|
| 188 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
| 189 |
+
logging.debug("Making layer 2")
|
| 190 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
|
| 191 |
+
dilate=replace_stride_with_dilation[0])
|
| 192 |
+
|
| 193 |
+
logging.debug("Making layer 3")
|
| 194 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
|
| 195 |
+
dilate=replace_stride_with_dilation[1])
|
| 196 |
+
self.out_dim = 512 * block.expansion
|
| 197 |
+
|
| 198 |
+
for m in self.modules():
|
| 199 |
+
if isinstance(m, nn.Conv2d):
|
| 200 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 201 |
+
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
|
| 202 |
+
nn.init.constant_(m.weight, 1)
|
| 203 |
+
nn.init.constant_(m.bias, 0)
|
| 204 |
+
|
| 205 |
+
# Zero-initialize the last BN in each residual branch,
|
| 206 |
+
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
|
| 207 |
+
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
|
| 208 |
+
if zero_init_residual:
|
| 209 |
+
for m in self.modules():
|
| 210 |
+
if isinstance(m, Bottleneck):
|
| 211 |
+
nn.init.constant_(m.bn3.weight, 0)
|
| 212 |
+
elif isinstance(m, BasicBlock):
|
| 213 |
+
nn.init.constant_(m.bn2.weight, 0)
|
| 214 |
+
|
| 215 |
+
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
|
| 216 |
+
norm_layer = self._norm_layer
|
| 217 |
+
downsample = None
|
| 218 |
+
previous_dilation = self.dilation
|
| 219 |
+
if dilate:
|
| 220 |
+
self.dilation *= stride
|
| 221 |
+
stride = 1
|
| 222 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 223 |
+
downsample = nn.Sequential(
|
| 224 |
+
conv1x1(self.inplanes, planes * block.expansion, stride),
|
| 225 |
+
norm_layer(planes * block.expansion),
|
| 226 |
+
)
|
| 227 |
+
layers = []
|
| 228 |
+
logging.debug("(inplanes: {}, planes: {}) for first layer".format(self.inplanes, planes))
|
| 229 |
+
|
| 230 |
+
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
|
| 231 |
+
self.base_width, previous_dilation, norm_layer))
|
| 232 |
+
self.inplanes = planes * block.expansion
|
| 233 |
+
logging.debug("self.inplanes changed to {}".format(self.inplanes))
|
| 234 |
+
for _ in range(1, blocks):
|
| 235 |
+
logging.debug("(inplanes: {}, planes: {}) for next layer -->".format(self.inplanes, planes))
|
| 236 |
+
layers.append(block(self.inplanes, planes, groups=self.groups,
|
| 237 |
+
base_width=self.base_width, dilation=self.dilation,
|
| 238 |
+
norm_layer=norm_layer))
|
| 239 |
+
return nn.Sequential(*layers)
|
| 240 |
+
def _forward_impl(self, x):
|
| 241 |
+
x = self.conv1(x)
|
| 242 |
+
logging.debug("GB:conv1 --> {}".format(x.shape))
|
| 243 |
+
x = self.bn1(x)
|
| 244 |
+
x = self.relu(x)
|
| 245 |
+
x = self.maxpool(x)
|
| 246 |
+
logging.debug("GB:maxpool --> {}".format(x.shape))
|
| 247 |
+
x_1 = self.layer1(x)
|
| 248 |
+
logging.debug("GB:x_1 --> {}".format(x_1.shape))
|
| 249 |
+
x_2 = self.layer2(x_1)
|
| 250 |
+
logging.debug("GB:x_2 --> {}".format(x_2.shape))
|
| 251 |
+
|
| 252 |
+
x_3 = self.layer3(x_2)
|
| 253 |
+
logging.debug("GB:x_3 --> {}".format(x_3.shape))
|
| 254 |
+
return x_3
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def forward(self, x):
|
| 258 |
+
return self._forward_impl(x)
|
| 259 |
+
|
| 260 |
+
class SpecializedResNet_imagenet(nn.Module):
|
| 261 |
+
def __init__(self, block, layers, nconv, num_classes=1000, zero_init_residual=False,
|
| 262 |
+
groups=1, width_per_group=64, replace_stride_with_dilation=None,
|
| 263 |
+
norm_layer=None):
|
| 264 |
+
super(SpecializedResNet_imagenet, self).__init__()
|
| 265 |
+
if norm_layer is None:
|
| 266 |
+
norm_layer = nn.BatchNorm2d
|
| 267 |
+
self._norm_layer = norm_layer
|
| 268 |
+
|
| 269 |
+
self.feature_dim = 512 * block.expansion
|
| 270 |
+
self.inplanes = 256 * block.expansion
|
| 271 |
+
self.dilation = 1
|
| 272 |
+
if replace_stride_with_dilation is None:
|
| 273 |
+
replace_stride_with_dilation = [False, False, False]
|
| 274 |
+
if len(replace_stride_with_dilation) != 3:
|
| 275 |
+
raise ValueError("replace_stride_with_dilation should be None "
|
| 276 |
+
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
|
| 277 |
+
self.groups = groups
|
| 278 |
+
self.base_width = width_per_group
|
| 279 |
+
|
| 280 |
+
logging.debug("Making layer 4")
|
| 281 |
+
self.layer4 = self._make_layer(block, 512, layers[3], nconv=nconv, stride=2,
|
| 282 |
+
dilate=replace_stride_with_dilation[2])
|
| 283 |
+
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
|
| 284 |
+
self.out_dim = 512 * block.expansion
|
| 285 |
+
|
| 286 |
+
for m in self.modules():
|
| 287 |
+
if isinstance(m, nn.Conv2d):
|
| 288 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 289 |
+
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
|
| 290 |
+
nn.init.constant_(m.weight, 1)
|
| 291 |
+
nn.init.constant_(m.bias, 0)
|
| 292 |
+
|
| 293 |
+
def _make_layer(self, block, planes, blocks, nconv, stride=1, dilate=False):
|
| 294 |
+
norm_layer = self._norm_layer
|
| 295 |
+
downsample = None
|
| 296 |
+
previous_dilation = self.dilation
|
| 297 |
+
if dilate:
|
| 298 |
+
self.dilation *= stride
|
| 299 |
+
stride = 1
|
| 300 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 301 |
+
downsample = nn.Sequential(
|
| 302 |
+
conv1x1(self.inplanes, planes * block.expansion, stride),
|
| 303 |
+
norm_layer(planes * block.expansion),
|
| 304 |
+
)
|
| 305 |
+
layers = []
|
| 306 |
+
logging.debug("(inplanes: {}, planes: {}) for first layer".format(self.inplanes, planes))
|
| 307 |
+
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
|
| 308 |
+
self.base_width, previous_dilation, norm_layer, nconv[0]))
|
| 309 |
+
self.inplanes = planes * block.expansion
|
| 310 |
+
for _ in range(1, blocks):
|
| 311 |
+
logging.debug("(inplanes: {}, planes: {}) for next layer".format(self.inplanes, planes))
|
| 312 |
+
layers.append(block(self.inplanes, planes, groups=self.groups,
|
| 313 |
+
base_width=self.base_width, dilation=self.dilation,
|
| 314 |
+
norm_layer=norm_layer, nconv=nconv[1]))
|
| 315 |
+
|
| 316 |
+
return nn.Sequential(*layers)
|
| 317 |
+
|
| 318 |
+
def forward(self, x):
|
| 319 |
+
logging.debug("SB:x --> {}".format(x.shape))
|
| 320 |
+
x_4 = self.layer4(x) # [bs, 512, 4, 4]
|
| 321 |
+
logging.debug("SB:x_4 --> {}".format(x_4.shape))
|
| 322 |
+
pooled = self.avgpool(x_4) # [bs, 512, 1, 1]
|
| 323 |
+
logging.debug("SB:pooled --> {}".format(pooled.shape))
|
| 324 |
+
features = torch.flatten(pooled, 1) # [bs, 512]
|
| 325 |
+
logging.debug("SB:features --> {}".format(features.shape))
|
| 326 |
+
return features
|
| 327 |
+
|
| 328 |
+
def get_resnet10_imagenet():
|
| 329 |
+
basenet = GeneralizedResNet_imagenet(BasicBlock,[1, 1, 1, 1])
|
| 330 |
+
adaptivenet = SpecializedResNet_imagenet(BasicBlock, [1, 1, 1, 1])
|
| 331 |
+
return basenet,adaptivenet
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def get_resnet18_imagenet(args):
|
| 335 |
+
logging.debug('Curr Task : {}'.format(args['curr']))
|
| 336 |
+
|
| 337 |
+
nconv = args['layers'][args['curr']] if args['curr'] > -1 else [2, 2]
|
| 338 |
+
logging.debug('Curr Task {}: nconv {}'.format(args['curr'], nconv))
|
| 339 |
+
basenet = GeneralizedResNet_imagenet(BasicBlock,[2, 2, 2, 2])
|
| 340 |
+
adaptivenet = SpecializedResNet_imagenet(BasicBlock, layers=[2,2,2,len(nconv)], nconv=nconv)
|
| 341 |
+
return basenet,adaptivenet
|
| 342 |
+
|
| 343 |
+
def get_resnet26_imagenet():
|
| 344 |
+
basenet = GeneralizedResNet_imagenet(Bottleneck,[2, 2, 2, 2])
|
| 345 |
+
adaptivenet = SpecializedResNet_imagenet(Bottleneck, [2, 2, 2, 2])
|
| 346 |
+
return basenet,adaptivenet
|
| 347 |
+
|
| 348 |
+
def get_resnet34_imagenet():
|
| 349 |
+
basenet = GeneralizedResNet_imagenet(BasicBlock,[3, 4, 6, 3])
|
| 350 |
+
adaptivenet = SpecializedResNet_imagenet(BasicBlock, [3, 4, 6, 3])
|
| 351 |
+
return basenet,adaptivenet
|
| 352 |
+
|
| 353 |
+
def get_resnet50_imagenet():
|
| 354 |
+
basenet = GeneralizedResNet_imagenet(Bottleneck,[3, 4, 6, 3])
|
| 355 |
+
adaptivenet = SpecializedResNet_imagenet(Bottleneck, [3, 4, 6, 3])
|
| 356 |
+
return basenet,adaptivenet
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
if __name__ == '__main__':
|
| 360 |
+
model2imagenet = 3*224*224
|
| 361 |
+
|
| 362 |
+
a, b = get_resnet10_imagenet()
|
| 363 |
+
_base = sum(p.numel() for p in a.parameters())
|
| 364 |
+
_adap = sum(p.numel() for p in b.parameters())
|
| 365 |
+
print(f"resnet10 #params:{_base+_adap}")
|
| 366 |
+
|
| 367 |
+
a, b = get_resnet18_imagenet()
|
| 368 |
+
_base = sum(p.numel() for p in a.parameters())
|
| 369 |
+
_adap = sum(p.numel() for p in b.parameters())
|
| 370 |
+
print(f"resnet18 #params:{_base+_adap}")
|
| 371 |
+
|
| 372 |
+
a, b = get_resnet26_imagenet()
|
| 373 |
+
_base = sum(p.numel() for p in a.parameters())
|
| 374 |
+
_adap = sum(p.numel() for p in b.parameters())
|
| 375 |
+
print(f"resnet26 #params:{_base+_adap}")
|
| 376 |
+
|
| 377 |
+
a, b = get_resnet34_imagenet()
|
| 378 |
+
_base = sum(p.numel() for p in a.parameters())
|
| 379 |
+
_adap = sum(p.numel() for p in b.parameters())
|
| 380 |
+
print(f"resnet34 #params:{_base+_adap}")
|
| 381 |
+
|
| 382 |
+
a, b = get_resnet50_imagenet()
|
| 383 |
+
_base = sum(p.numel() for p in a.parameters())
|
| 384 |
+
_adap = sum(p.numel() for p in b.parameters())
|
| 385 |
+
print(f"resnet50 #params:{_base+_adap}")
|
convs/modified_represnet.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ResNet', 'resnet18_rep', 'resnet34_rep' ]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def conv3x3(in_planes, out_planes, stride=1):
|
| 11 |
+
"3x3 convolution with padding"
|
| 12 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
| 13 |
+
padding=1, bias=True)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def conv1x1(in_planes, out_planes, stride=1):
|
| 17 |
+
"""1x1 convolution"""
|
| 18 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=True)
|
| 19 |
+
|
| 20 |
+
class conv_block(nn.Module):
|
| 21 |
+
|
| 22 |
+
def __init__(self, in_planes, planes, mode, stride=1):
|
| 23 |
+
super(conv_block, self).__init__()
|
| 24 |
+
self.conv = conv3x3(in_planes, planes, stride)
|
| 25 |
+
self.mode = mode
|
| 26 |
+
if mode == 'parallel_adapters':
|
| 27 |
+
self.adapter = conv1x1(in_planes, planes, stride)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def re_init_conv(self):
|
| 31 |
+
nn.init.kaiming_normal_(self.adapter.weight, mode='fan_out', nonlinearity='relu')
|
| 32 |
+
return
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
y = self.conv(x)
|
| 35 |
+
if self.mode == 'parallel_adapters':
|
| 36 |
+
y = y + self.adapter(x)
|
| 37 |
+
|
| 38 |
+
return y
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class BasicBlock(nn.Module):
|
| 42 |
+
expansion = 1
|
| 43 |
+
|
| 44 |
+
def __init__(self, inplanes, planes, mode, stride=1, downsample=None):
|
| 45 |
+
super(BasicBlock, self).__init__()
|
| 46 |
+
self.conv1 = conv_block(inplanes, planes, mode, stride)
|
| 47 |
+
self.norm1 = nn.BatchNorm2d(planes)
|
| 48 |
+
self.relu = nn.ReLU(inplace=True)
|
| 49 |
+
self.conv2 = conv_block(planes, planes, mode)
|
| 50 |
+
self.norm2 = nn.BatchNorm2d(planes)
|
| 51 |
+
self.mode = mode
|
| 52 |
+
|
| 53 |
+
self.downsample = downsample
|
| 54 |
+
self.stride = stride
|
| 55 |
+
|
| 56 |
+
def forward(self, x):
|
| 57 |
+
residual = x
|
| 58 |
+
out = self.conv1(x)
|
| 59 |
+
out = self.norm1(out)
|
| 60 |
+
out = self.relu(out)
|
| 61 |
+
out = self.conv2(out)
|
| 62 |
+
out = self.norm2(out)
|
| 63 |
+
if self.downsample is not None:
|
| 64 |
+
residual = self.downsample(x)
|
| 65 |
+
out += residual
|
| 66 |
+
out = self.relu(out)
|
| 67 |
+
return out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class ResNet(nn.Module):
|
| 71 |
+
|
| 72 |
+
def __init__(self, block, layers, num_classes=100, args = None):
|
| 73 |
+
self.inplanes = 64
|
| 74 |
+
super(ResNet, self).__init__()
|
| 75 |
+
assert args is not None
|
| 76 |
+
self.mode = args["mode"]
|
| 77 |
+
|
| 78 |
+
if 'cifar' in args["dataset"]:
|
| 79 |
+
self.conv1 = nn.Sequential(nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False),
|
| 80 |
+
nn.BatchNorm2d(self.inplanes), nn.ReLU(inplace=True))
|
| 81 |
+
print("use cifar")
|
| 82 |
+
elif 'imagenet' in args["dataset"]:
|
| 83 |
+
if args["init_cls"] == args["increment"]:
|
| 84 |
+
self.conv1 = nn.Sequential(
|
| 85 |
+
nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False),
|
| 86 |
+
nn.BatchNorm2d(self.inplanes),
|
| 87 |
+
nn.ReLU(inplace=True),
|
| 88 |
+
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
|
| 89 |
+
)
|
| 90 |
+
else:
|
| 91 |
+
# Following PODNET implmentation
|
| 92 |
+
self.conv1 = nn.Sequential(
|
| 93 |
+
nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False),
|
| 94 |
+
nn.BatchNorm2d(self.inplanes),
|
| 95 |
+
nn.ReLU(inplace=True),
|
| 96 |
+
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
| 101 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
|
| 102 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
|
| 103 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
|
| 104 |
+
self.feature = nn.AvgPool2d(4, stride=1)
|
| 105 |
+
self.out_dim = 512
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
for m in self.modules():
|
| 109 |
+
if isinstance(m, nn.Conv2d):
|
| 110 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 111 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 112 |
+
nn.init.constant_(m.weight, 1)
|
| 113 |
+
nn.init.constant_(m.bias, 0)
|
| 114 |
+
|
| 115 |
+
def _make_layer(self, block, planes, blocks, stride=1):
|
| 116 |
+
downsample = None
|
| 117 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 118 |
+
downsample = nn.Sequential(
|
| 119 |
+
nn.Conv2d(self.inplanes, planes * block.expansion,
|
| 120 |
+
kernel_size=1, stride=stride, bias=True),
|
| 121 |
+
)
|
| 122 |
+
layers = []
|
| 123 |
+
layers.append(block(self.inplanes, planes, self.mode, stride, downsample))
|
| 124 |
+
self.inplanes = planes * block.expansion
|
| 125 |
+
for i in range(1, blocks):
|
| 126 |
+
layers.append(block(self.inplanes, planes, self.mode))
|
| 127 |
+
|
| 128 |
+
return nn.Sequential(*layers)
|
| 129 |
+
|
| 130 |
+
def switch(self, mode='normal'):
|
| 131 |
+
for name, module in self.named_modules():
|
| 132 |
+
if hasattr(module, 'mode'):
|
| 133 |
+
module.mode = mode
|
| 134 |
+
def re_init_params(self):
|
| 135 |
+
for name, module in self.named_modules():
|
| 136 |
+
if hasattr(module, 're_init_conv'):
|
| 137 |
+
module.re_init_conv()
|
| 138 |
+
def forward(self, x):
|
| 139 |
+
x = self.conv1(x)
|
| 140 |
+
|
| 141 |
+
x = self.layer1(x)
|
| 142 |
+
x = self.layer2(x)
|
| 143 |
+
x = self.layer3(x)
|
| 144 |
+
x = self.layer4(x)
|
| 145 |
+
dim = x.size()[-1]
|
| 146 |
+
pool = nn.AvgPool2d(dim, stride=1)
|
| 147 |
+
x = pool(x)
|
| 148 |
+
x = x.view(x.size(0), -1)
|
| 149 |
+
return {"features": x}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def resnet18_rep(pretrained=False, **kwargs):
|
| 153 |
+
"""Constructs a ResNet-18 model.
|
| 154 |
+
Args:
|
| 155 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 156 |
+
"""
|
| 157 |
+
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
|
| 158 |
+
if pretrained:
|
| 159 |
+
pretrained_state_dict = model_zoo.load_url(model_urls['resnet18'])
|
| 160 |
+
now_state_dict = model.state_dict()
|
| 161 |
+
now_state_dict.update(pretrained_state_dict)
|
| 162 |
+
model.load_state_dict(now_state_dict)
|
| 163 |
+
return model
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def resnet34_rep(pretrained=False, **kwargs):
|
| 167 |
+
"""Constructs a ResNet-34 model.
|
| 168 |
+
Args:
|
| 169 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 170 |
+
"""
|
| 171 |
+
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
|
| 172 |
+
if pretrained:
|
| 173 |
+
pretrained_state_dict = model_zoo.load_url(model_urls['resnet34'])
|
| 174 |
+
now_state_dict = model.state_dict()
|
| 175 |
+
now_state_dict.update(pretrained_state_dict)
|
| 176 |
+
model.load_state_dict(now_state_dict)
|
| 177 |
+
return model
|
convs/resnet.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Reference:
|
| 3 |
+
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
|
| 4 |
+
'''
|
| 5 |
+
import logging
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
try:
|
| 9 |
+
from torchvision.models.utils import load_state_dict_from_url
|
| 10 |
+
except:
|
| 11 |
+
from torch.hub import load_state_dict_from_url
|
| 12 |
+
|
| 13 |
+
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
|
| 14 |
+
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
|
| 15 |
+
'wide_resnet50_2', 'wide_resnet101_2']
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
model_urls = {
|
| 19 |
+
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
|
| 20 |
+
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
|
| 21 |
+
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
|
| 22 |
+
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
|
| 23 |
+
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
|
| 24 |
+
'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
|
| 25 |
+
'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
|
| 26 |
+
'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
|
| 27 |
+
'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
|
| 32 |
+
"""3x3 convolution with padding"""
|
| 33 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
| 34 |
+
padding=dilation, groups=groups, bias=False, dilation=dilation)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def conv1x1(in_planes, out_planes, stride=1):
|
| 38 |
+
"""1x1 convolution"""
|
| 39 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class BasicBlock(nn.Module):
|
| 43 |
+
expansion = 1
|
| 44 |
+
__constants__ = ['downsample']
|
| 45 |
+
|
| 46 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
|
| 47 |
+
base_width=64, dilation=1, norm_layer=None):
|
| 48 |
+
super(BasicBlock, self).__init__()
|
| 49 |
+
if norm_layer is None:
|
| 50 |
+
norm_layer = nn.BatchNorm2d
|
| 51 |
+
if groups != 1 or base_width != 64:
|
| 52 |
+
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
|
| 53 |
+
if dilation > 1:
|
| 54 |
+
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
|
| 55 |
+
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
|
| 56 |
+
self.conv1 = conv3x3(inplanes, planes, stride)
|
| 57 |
+
self.bn1 = norm_layer(planes)
|
| 58 |
+
self.relu = nn.ReLU(inplace=True)
|
| 59 |
+
self.conv2 = conv3x3(planes, planes)
|
| 60 |
+
self.bn2 = norm_layer(planes)
|
| 61 |
+
self.downsample = downsample
|
| 62 |
+
self.stride = stride
|
| 63 |
+
|
| 64 |
+
def forward(self, x):
|
| 65 |
+
identity = x
|
| 66 |
+
|
| 67 |
+
out = self.conv1(x)
|
| 68 |
+
out = self.bn1(out)
|
| 69 |
+
out = self.relu(out)
|
| 70 |
+
|
| 71 |
+
out = self.conv2(out)
|
| 72 |
+
out = self.bn2(out)
|
| 73 |
+
|
| 74 |
+
if self.downsample is not None:
|
| 75 |
+
identity = self.downsample(x)
|
| 76 |
+
|
| 77 |
+
out += identity
|
| 78 |
+
out = self.relu(out)
|
| 79 |
+
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class Bottleneck(nn.Module):
|
| 84 |
+
expansion = 4
|
| 85 |
+
__constants__ = ['downsample']
|
| 86 |
+
|
| 87 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
|
| 88 |
+
base_width=64, dilation=1, norm_layer=None):
|
| 89 |
+
super(Bottleneck, self).__init__()
|
| 90 |
+
if norm_layer is None:
|
| 91 |
+
norm_layer = nn.BatchNorm2d
|
| 92 |
+
width = int(planes * (base_width / 64.)) * groups
|
| 93 |
+
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
|
| 94 |
+
self.conv1 = conv1x1(inplanes, width)
|
| 95 |
+
self.bn1 = norm_layer(width)
|
| 96 |
+
self.conv2 = conv3x3(width, width, stride, groups, dilation)
|
| 97 |
+
self.bn2 = norm_layer(width)
|
| 98 |
+
self.conv3 = conv1x1(width, planes * self.expansion)
|
| 99 |
+
self.bn3 = norm_layer(planes * self.expansion)
|
| 100 |
+
self.relu = nn.ReLU(inplace=True)
|
| 101 |
+
self.downsample = downsample
|
| 102 |
+
self.stride = stride
|
| 103 |
+
|
| 104 |
+
def forward(self, x):
|
| 105 |
+
identity = x
|
| 106 |
+
|
| 107 |
+
out = self.conv1(x)
|
| 108 |
+
out = self.bn1(out)
|
| 109 |
+
out = self.relu(out)
|
| 110 |
+
|
| 111 |
+
out = self.conv2(out)
|
| 112 |
+
out = self.bn2(out)
|
| 113 |
+
out = self.relu(out)
|
| 114 |
+
|
| 115 |
+
out = self.conv3(out)
|
| 116 |
+
out = self.bn3(out)
|
| 117 |
+
|
| 118 |
+
if self.downsample is not None:
|
| 119 |
+
identity = self.downsample(x)
|
| 120 |
+
|
| 121 |
+
out += identity
|
| 122 |
+
out = self.relu(out)
|
| 123 |
+
|
| 124 |
+
return out
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class ResNet(nn.Module):
|
| 131 |
+
|
| 132 |
+
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
|
| 133 |
+
groups=1, width_per_group=64, replace_stride_with_dilation=None,
|
| 134 |
+
norm_layer=None,args=None):
|
| 135 |
+
super(ResNet, self).__init__()
|
| 136 |
+
if norm_layer is None:
|
| 137 |
+
norm_layer = nn.BatchNorm2d
|
| 138 |
+
self._norm_layer = norm_layer
|
| 139 |
+
|
| 140 |
+
self.inplanes = 64
|
| 141 |
+
self.dilation = 1
|
| 142 |
+
if replace_stride_with_dilation is None:
|
| 143 |
+
# each element in the tuple indicates if we should replace
|
| 144 |
+
# the 2x2 stride with a dilated convolution instead
|
| 145 |
+
replace_stride_with_dilation = [False, False, False]
|
| 146 |
+
if len(replace_stride_with_dilation) != 3:
|
| 147 |
+
raise ValueError("replace_stride_with_dilation should be None "
|
| 148 |
+
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
|
| 149 |
+
self.groups = groups
|
| 150 |
+
self.base_width = width_per_group
|
| 151 |
+
|
| 152 |
+
assert args is not None, "you should pass args to resnet"
|
| 153 |
+
if 'cifar' in args["dataset"]:
|
| 154 |
+
if args["model_name"] == "memo":
|
| 155 |
+
self.conv1 = nn.Sequential(
|
| 156 |
+
nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False),
|
| 157 |
+
nn.BatchNorm2d(self.inplanes),
|
| 158 |
+
nn.ReLU(inplace=True),
|
| 159 |
+
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
|
| 160 |
+
)
|
| 161 |
+
else:
|
| 162 |
+
self.conv1 = nn.Sequential(
|
| 163 |
+
nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False),
|
| 164 |
+
nn.BatchNorm2d(self.inplanes),
|
| 165 |
+
nn.ReLU(inplace=True))
|
| 166 |
+
elif 'imagenet' in args["dataset"]:
|
| 167 |
+
if args["init_cls"] == args["increment"]:
|
| 168 |
+
self.conv1 = nn.Sequential(
|
| 169 |
+
nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False),
|
| 170 |
+
nn.BatchNorm2d(self.inplanes),
|
| 171 |
+
nn.ReLU(inplace=True),
|
| 172 |
+
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
|
| 173 |
+
)
|
| 174 |
+
else:
|
| 175 |
+
self.conv1 = nn.Sequential(
|
| 176 |
+
nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False),
|
| 177 |
+
nn.BatchNorm2d(self.inplanes),
|
| 178 |
+
nn.ReLU(inplace=True),
|
| 179 |
+
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
| 185 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
|
| 186 |
+
dilate=replace_stride_with_dilation[0])
|
| 187 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
|
| 188 |
+
dilate=replace_stride_with_dilation[1])
|
| 189 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
|
| 190 |
+
dilate=replace_stride_with_dilation[2])
|
| 191 |
+
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
|
| 192 |
+
self.out_dim = 512 * block.expansion
|
| 193 |
+
#self.fc = nn.Linear(512 * block.expansion, num_classes) # Removed in _forward_impl
|
| 194 |
+
|
| 195 |
+
for m in self.modules():
|
| 196 |
+
if isinstance(m, nn.Conv2d):
|
| 197 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 198 |
+
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
|
| 199 |
+
nn.init.constant_(m.weight, 1)
|
| 200 |
+
nn.init.constant_(m.bias, 0)
|
| 201 |
+
|
| 202 |
+
# Zero-initialize the last BN in each residual branch,
|
| 203 |
+
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
|
| 204 |
+
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
|
| 205 |
+
if zero_init_residual:
|
| 206 |
+
for m in self.modules():
|
| 207 |
+
if isinstance(m, Bottleneck):
|
| 208 |
+
nn.init.constant_(m.bn3.weight, 0)
|
| 209 |
+
elif isinstance(m, BasicBlock):
|
| 210 |
+
nn.init.constant_(m.bn2.weight, 0)
|
| 211 |
+
|
| 212 |
+
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
|
| 213 |
+
norm_layer = self._norm_layer
|
| 214 |
+
downsample = None
|
| 215 |
+
previous_dilation = self.dilation
|
| 216 |
+
if dilate:
|
| 217 |
+
self.dilation *= stride
|
| 218 |
+
stride = 1
|
| 219 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 220 |
+
downsample = nn.Sequential(
|
| 221 |
+
conv1x1(self.inplanes, planes * block.expansion, stride),
|
| 222 |
+
norm_layer(planes * block.expansion),
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
layers = []
|
| 226 |
+
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
|
| 227 |
+
self.base_width, previous_dilation, norm_layer))
|
| 228 |
+
self.inplanes = planes * block.expansion
|
| 229 |
+
for _ in range(1, blocks):
|
| 230 |
+
layers.append(block(self.inplanes, planes, groups=self.groups,
|
| 231 |
+
base_width=self.base_width, dilation=self.dilation,
|
| 232 |
+
norm_layer=norm_layer))
|
| 233 |
+
|
| 234 |
+
return nn.Sequential(*layers)
|
| 235 |
+
|
| 236 |
+
def _forward_impl(self, x):
|
| 237 |
+
# See note [TorchScript super()]
|
| 238 |
+
#print("Input data shape------->", x.shape)
|
| 239 |
+
x = self.conv1(x) # [bs, 64, 32, 32]
|
| 240 |
+
#print('x-->', x.shape)
|
| 241 |
+
x_1 = self.layer1(x) # [bs, 128, 32, 32]
|
| 242 |
+
#print('x_1-->', x_1.shape)
|
| 243 |
+
x_2 = self.layer2(x_1) # [bs, 256, 16, 16]
|
| 244 |
+
#print('x_2-->', x_2.shape)
|
| 245 |
+
x_3 = self.layer3(x_2) # [bs, 512, 8, 8]
|
| 246 |
+
#print('x_3-->', x_3.shape)
|
| 247 |
+
x_4 = self.layer4(x_3) # [bs, 512, 4, 4]
|
| 248 |
+
|
| 249 |
+
#print('x_4-->', x_4.shape)
|
| 250 |
+
|
| 251 |
+
pooled = self.avgpool(x_4) # [bs, 512, 1, 1]
|
| 252 |
+
features = torch.flatten(pooled, 1) # [bs, 512]
|
| 253 |
+
#x = self.fc(features)
|
| 254 |
+
#print("final x ------>", x.shape)
|
| 255 |
+
|
| 256 |
+
return {
|
| 257 |
+
'fmaps': [x_1, x_2, x_3, x_4],
|
| 258 |
+
'features': features
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
def forward(self, x):
|
| 262 |
+
return self._forward_impl(x)
|
| 263 |
+
|
| 264 |
+
@property
|
| 265 |
+
def last_conv(self):
|
| 266 |
+
if hasattr(self.layer4[-1], 'conv3'):
|
| 267 |
+
return self.layer4[-1].conv3
|
| 268 |
+
else:
|
| 269 |
+
return self.layer4[-1].conv2
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _resnet(arch, block, layers, pretrained, progress, **kwargs):
|
| 273 |
+
model = ResNet(block, layers, **kwargs)
|
| 274 |
+
#print(model)
|
| 275 |
+
logging.info("************loading the trained network*************")
|
| 276 |
+
if pretrained:
|
| 277 |
+
state_dict = load_state_dict_from_url(model_urls[arch],
|
| 278 |
+
progress=progress)
|
| 279 |
+
#print(state_dict.keys())
|
| 280 |
+
#print(state_dict.keys())
|
| 281 |
+
del state_dict['fc.weight']
|
| 282 |
+
del state_dict['fc.bias']
|
| 283 |
+
#model.load_state_dict(state_dict)
|
| 284 |
+
#print(model)
|
| 285 |
+
|
| 286 |
+
#newmodel = torch.nn.Sequential(*(list(model.children())[:-1]))
|
| 287 |
+
#print(newmodel)
|
| 288 |
+
return model
|
| 289 |
+
|
| 290 |
+
def resnet10(pretrained=False, progress=True, **kwargs):
|
| 291 |
+
"""
|
| 292 |
+
For MEMO implementations of ResNet-10
|
| 293 |
+
"""
|
| 294 |
+
return _resnet('resnet10', BasicBlock, [1, 1, 1, 1], pretrained, progress,
|
| 295 |
+
**kwargs)
|
| 296 |
+
|
| 297 |
+
def resnet26(pretrained=False, progress=True, **kwargs):
|
| 298 |
+
"""
|
| 299 |
+
For MEMO implementations of ResNet-26
|
| 300 |
+
"""
|
| 301 |
+
return _resnet('resnet26', Bottleneck, [2, 2, 2, 2], pretrained, progress,
|
| 302 |
+
**kwargs)
|
| 303 |
+
|
| 304 |
+
def resnet18(pretrained=False, progress=True, **kwargs):
|
| 305 |
+
r"""ResNet-18 model from
|
| 306 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 307 |
+
Args:
|
| 308 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 309 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 310 |
+
"""
|
| 311 |
+
return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
|
| 312 |
+
**kwargs)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def resnet34(pretrained=False, progress=True, **kwargs):
|
| 316 |
+
r"""ResNet-34 model from
|
| 317 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 318 |
+
Args:
|
| 319 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 320 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 321 |
+
"""
|
| 322 |
+
return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
|
| 323 |
+
**kwargs)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def resnet50(pretrained=False, progress=True, **kwargs):
|
| 327 |
+
r"""ResNet-50 model from
|
| 328 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 329 |
+
Args:
|
| 330 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 331 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 332 |
+
"""
|
| 333 |
+
return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
|
| 334 |
+
**kwargs)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def resnet101(pretrained=False, progress=True, **kwargs):
|
| 338 |
+
r"""ResNet-101 model from
|
| 339 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 340 |
+
Args:
|
| 341 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 342 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 343 |
+
"""
|
| 344 |
+
return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
|
| 345 |
+
**kwargs)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def resnet152(pretrained=False, progress=True, **kwargs):
|
| 349 |
+
r"""ResNet-152 model from
|
| 350 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 351 |
+
Args:
|
| 352 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 353 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 354 |
+
"""
|
| 355 |
+
return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
|
| 356 |
+
**kwargs)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
|
| 360 |
+
r"""ResNeXt-50 32x4d model from
|
| 361 |
+
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
|
| 362 |
+
Args:
|
| 363 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 364 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 365 |
+
"""
|
| 366 |
+
kwargs['groups'] = 32
|
| 367 |
+
kwargs['width_per_group'] = 4
|
| 368 |
+
return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
|
| 369 |
+
pretrained, progress, **kwargs)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
|
| 373 |
+
r"""ResNeXt-101 32x8d model from
|
| 374 |
+
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
|
| 375 |
+
Args:
|
| 376 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 377 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 378 |
+
"""
|
| 379 |
+
kwargs['groups'] = 32
|
| 380 |
+
kwargs['width_per_group'] = 8
|
| 381 |
+
return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
|
| 382 |
+
pretrained, progress, **kwargs)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
|
| 386 |
+
r"""Wide ResNet-50-2 model from
|
| 387 |
+
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
|
| 388 |
+
The model is the same as ResNet except for the bottleneck number of channels
|
| 389 |
+
which is twice larger in every block. The number of channels in outer 1x1
|
| 390 |
+
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
|
| 391 |
+
channels, and in Wide ResNet-50-2 has 2048-1024-2048.
|
| 392 |
+
Args:
|
| 393 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 394 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 395 |
+
"""
|
| 396 |
+
kwargs['width_per_group'] = 64 * 2
|
| 397 |
+
return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
|
| 398 |
+
pretrained, progress, **kwargs)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
|
| 402 |
+
r"""Wide ResNet-101-2 model from
|
| 403 |
+
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
|
| 404 |
+
The model is the same as ResNet except for the bottleneck number of channels
|
| 405 |
+
which is twice larger in every block. The number of channels in outer 1x1
|
| 406 |
+
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
|
| 407 |
+
channels, and in Wide ResNet-50-2 has 2048-1024-2048.
|
| 408 |
+
Args:
|
| 409 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 410 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 411 |
+
"""
|
| 412 |
+
kwargs['width_per_group'] = 64 * 2
|
| 413 |
+
return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
|
| 414 |
+
pretrained, progress, **kwargs)
|
convs/resnet_cbam.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import math
|
| 4 |
+
import torch.utils.model_zoo as model_zoo
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
__all__ = ['ResNet', 'resnet18_cbam', 'resnet34_cbam', 'resnet50_cbam', 'resnet101_cbam',
|
| 8 |
+
'resnet152_cbam']
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
model_urls = {
|
| 12 |
+
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
|
| 13 |
+
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
|
| 14 |
+
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
|
| 15 |
+
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
|
| 16 |
+
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def conv3x3(in_planes, out_planes, stride=1):
|
| 21 |
+
"3x3 convolution with padding"
|
| 22 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
| 23 |
+
padding=1, bias=False)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ChannelAttention(nn.Module):
|
| 27 |
+
def __init__(self, in_planes, ratio=16):
|
| 28 |
+
super(ChannelAttention, self).__init__()
|
| 29 |
+
self.avg_pool = nn.AdaptiveAvgPool2d(1)
|
| 30 |
+
self.max_pool = nn.AdaptiveMaxPool2d(1)
|
| 31 |
+
|
| 32 |
+
self.fc1 = nn.Conv2d(in_planes, in_planes // 16, 1, bias=False)
|
| 33 |
+
self.relu1 = nn.ReLU()
|
| 34 |
+
self.fc2 = nn.Conv2d(in_planes // 16, in_planes, 1, bias=False)
|
| 35 |
+
|
| 36 |
+
self.sigmoid = nn.Sigmoid()
|
| 37 |
+
|
| 38 |
+
def forward(self, x):
|
| 39 |
+
avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x))))
|
| 40 |
+
max_out = self.fc2(self.relu1(self.fc1(self.max_pool(x))))
|
| 41 |
+
out = avg_out + max_out
|
| 42 |
+
return self.sigmoid(out)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class SpatialAttention(nn.Module):
|
| 46 |
+
def __init__(self, kernel_size=7):
|
| 47 |
+
super(SpatialAttention, self).__init__()
|
| 48 |
+
|
| 49 |
+
assert kernel_size in (3, 7), 'kernel size must be 3 or 7'
|
| 50 |
+
padding = 3 if kernel_size == 7 else 1
|
| 51 |
+
|
| 52 |
+
self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)
|
| 53 |
+
self.sigmoid = nn.Sigmoid()
|
| 54 |
+
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
avg_out = torch.mean(x, dim=1, keepdim=True)
|
| 57 |
+
max_out, _ = torch.max(x, dim=1, keepdim=True)
|
| 58 |
+
x = torch.cat([avg_out, max_out], dim=1)
|
| 59 |
+
x = self.conv1(x)
|
| 60 |
+
return self.sigmoid(x)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class BasicBlock(nn.Module):
|
| 64 |
+
expansion = 1
|
| 65 |
+
|
| 66 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
| 67 |
+
super(BasicBlock, self).__init__()
|
| 68 |
+
self.conv1 = conv3x3(inplanes, planes, stride)
|
| 69 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
| 70 |
+
self.relu = nn.ReLU(inplace=True)
|
| 71 |
+
self.conv2 = conv3x3(planes, planes)
|
| 72 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
| 73 |
+
|
| 74 |
+
self.ca = ChannelAttention(planes)
|
| 75 |
+
self.sa = SpatialAttention()
|
| 76 |
+
|
| 77 |
+
self.downsample = downsample
|
| 78 |
+
self.stride = stride
|
| 79 |
+
|
| 80 |
+
def forward(self, x):
|
| 81 |
+
residual = x
|
| 82 |
+
out = self.conv1(x)
|
| 83 |
+
out = self.bn1(out)
|
| 84 |
+
out = self.relu(out)
|
| 85 |
+
out = self.conv2(out)
|
| 86 |
+
out = self.bn2(out)
|
| 87 |
+
if self.downsample is not None:
|
| 88 |
+
residual = self.downsample(x)
|
| 89 |
+
out += residual
|
| 90 |
+
out = self.relu(out)
|
| 91 |
+
return out
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class Bottleneck(nn.Module):
|
| 95 |
+
expansion = 4
|
| 96 |
+
|
| 97 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
| 98 |
+
super(Bottleneck, self).__init__()
|
| 99 |
+
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
|
| 100 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
| 101 |
+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
|
| 102 |
+
padding=1, bias=False)
|
| 103 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
| 104 |
+
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
|
| 105 |
+
self.bn3 = nn.BatchNorm2d(planes * 4)
|
| 106 |
+
self.relu = nn.ReLU(inplace=True)
|
| 107 |
+
self.ca = ChannelAttention(planes * 4)
|
| 108 |
+
self.sa = SpatialAttention()
|
| 109 |
+
self.downsample = downsample
|
| 110 |
+
self.stride = stride
|
| 111 |
+
|
| 112 |
+
def forward(self, x):
|
| 113 |
+
residual = x
|
| 114 |
+
out = self.conv1(x)
|
| 115 |
+
out = self.bn1(out)
|
| 116 |
+
out = self.relu(out)
|
| 117 |
+
out = self.conv2(out)
|
| 118 |
+
out = self.bn2(out)
|
| 119 |
+
out = self.relu(out)
|
| 120 |
+
out = self.conv3(out)
|
| 121 |
+
out = self.bn3(out)
|
| 122 |
+
out = self.ca(out) * out
|
| 123 |
+
out = self.sa(out) * out
|
| 124 |
+
if self.downsample is not None:
|
| 125 |
+
residual = self.downsample(x)
|
| 126 |
+
out += residual
|
| 127 |
+
out = self.relu(out)
|
| 128 |
+
return out
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class ResNet(nn.Module):
|
| 132 |
+
|
| 133 |
+
def __init__(self, block, layers, num_classes=100, args=None):
|
| 134 |
+
self.inplanes = 64
|
| 135 |
+
super(ResNet, self).__init__()
|
| 136 |
+
assert args is not None, "you should pass args to resnet"
|
| 137 |
+
if 'cifar' in args["dataset"]:
|
| 138 |
+
self.conv1 = nn.Sequential(nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False),
|
| 139 |
+
nn.BatchNorm2d(self.inplanes), nn.ReLU(inplace=True))
|
| 140 |
+
elif 'imagenet' in args["dataset"]:
|
| 141 |
+
if args["init_cls"] == args["increment"]:
|
| 142 |
+
self.conv1 = nn.Sequential(
|
| 143 |
+
nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False),
|
| 144 |
+
nn.BatchNorm2d(self.inplanes),
|
| 145 |
+
nn.ReLU(inplace=True),
|
| 146 |
+
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
|
| 147 |
+
)
|
| 148 |
+
else:
|
| 149 |
+
self.conv1 = nn.Sequential(
|
| 150 |
+
nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False),
|
| 151 |
+
nn.BatchNorm2d(self.inplanes),
|
| 152 |
+
nn.ReLU(inplace=True),
|
| 153 |
+
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
|
| 154 |
+
)
|
| 155 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
| 156 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
|
| 157 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
|
| 158 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
|
| 159 |
+
self.feature = nn.AvgPool2d(4, stride=1)
|
| 160 |
+
# self.fc = nn.Linear(512 * block.expansion, num_classes)
|
| 161 |
+
self.out_dim = 512 * block.expansion
|
| 162 |
+
|
| 163 |
+
for m in self.modules():
|
| 164 |
+
if isinstance(m, nn.Conv2d):
|
| 165 |
+
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
| 166 |
+
m.weight.data.normal_(0, math.sqrt(2. / n))
|
| 167 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 168 |
+
m.weight.data.fill_(1)
|
| 169 |
+
m.bias.data.zero_()
|
| 170 |
+
|
| 171 |
+
def _make_layer(self, block, planes, blocks, stride=1):
|
| 172 |
+
downsample = None
|
| 173 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 174 |
+
downsample = nn.Sequential(
|
| 175 |
+
nn.Conv2d(self.inplanes, planes * block.expansion,
|
| 176 |
+
kernel_size=1, stride=stride, bias=False),
|
| 177 |
+
nn.BatchNorm2d(planes * block.expansion),
|
| 178 |
+
)
|
| 179 |
+
layers = []
|
| 180 |
+
layers.append(block(self.inplanes, planes, stride, downsample))
|
| 181 |
+
self.inplanes = planes * block.expansion
|
| 182 |
+
for i in range(1, blocks):
|
| 183 |
+
layers.append(block(self.inplanes, planes))
|
| 184 |
+
|
| 185 |
+
return nn.Sequential(*layers)
|
| 186 |
+
|
| 187 |
+
def forward(self, x):
|
| 188 |
+
x = self.conv1(x)
|
| 189 |
+
|
| 190 |
+
x = self.layer1(x)
|
| 191 |
+
x = self.layer2(x)
|
| 192 |
+
x = self.layer3(x)
|
| 193 |
+
x = self.layer4(x)
|
| 194 |
+
dim = x.size()[-1]
|
| 195 |
+
pool = nn.AvgPool2d(dim, stride=1)
|
| 196 |
+
x = pool(x)
|
| 197 |
+
x = x.view(x.size(0), -1)
|
| 198 |
+
return {"features": x}
|
| 199 |
+
|
| 200 |
+
def resnet18_cbam(pretrained=False, **kwargs):
|
| 201 |
+
"""Constructs a ResNet-18 model.
|
| 202 |
+
Args:
|
| 203 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 204 |
+
"""
|
| 205 |
+
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
|
| 206 |
+
if pretrained:
|
| 207 |
+
pretrained_state_dict = model_zoo.load_url(model_urls['resnet18'])
|
| 208 |
+
now_state_dict = model.state_dict()
|
| 209 |
+
now_state_dict.update(pretrained_state_dict)
|
| 210 |
+
model.load_state_dict(now_state_dict)
|
| 211 |
+
return model
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def resnet34_cbam(pretrained=False, **kwargs):
|
| 215 |
+
"""Constructs a ResNet-34 model.
|
| 216 |
+
Args:
|
| 217 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 218 |
+
"""
|
| 219 |
+
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
|
| 220 |
+
if pretrained:
|
| 221 |
+
pretrained_state_dict = model_zoo.load_url(model_urls['resnet34'])
|
| 222 |
+
now_state_dict = model.state_dict()
|
| 223 |
+
now_state_dict.update(pretrained_state_dict)
|
| 224 |
+
model.load_state_dict(now_state_dict)
|
| 225 |
+
return model
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def resnet50_cbam(pretrained=False, **kwargs):
|
| 229 |
+
"""Constructs a ResNet-50 model.
|
| 230 |
+
Args:
|
| 231 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 232 |
+
"""
|
| 233 |
+
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
|
| 234 |
+
if pretrained:
|
| 235 |
+
pretrained_state_dict = model_zoo.load_url(model_urls['resnet50'])
|
| 236 |
+
now_state_dict = model.state_dict()
|
| 237 |
+
now_state_dict.update(pretrained_state_dict)
|
| 238 |
+
model.load_state_dict(now_state_dict)
|
| 239 |
+
return model
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def resnet101_cbam(pretrained=False, **kwargs):
|
| 243 |
+
"""Constructs a ResNet-101 model.
|
| 244 |
+
Args:
|
| 245 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 246 |
+
"""
|
| 247 |
+
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
|
| 248 |
+
if pretrained:
|
| 249 |
+
pretrained_state_dict = model_zoo.load_url(model_urls['resnet101'])
|
| 250 |
+
now_state_dict = model.state_dict()
|
| 251 |
+
now_state_dict.update(pretrained_state_dict)
|
| 252 |
+
model.load_state_dict(now_state_dict)
|
| 253 |
+
return model
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def resnet152_cbam(pretrained=False, **kwargs):
|
| 257 |
+
"""Constructs a ResNet-152 model.
|
| 258 |
+
Args:
|
| 259 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 260 |
+
"""
|
| 261 |
+
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
|
| 262 |
+
if pretrained:
|
| 263 |
+
pretrained_state_dict = model_zoo.load_url(model_urls['resnet152'])
|
| 264 |
+
now_state_dict = model.state_dict()
|
| 265 |
+
now_state_dict.update(pretrained_state_dict)
|
| 266 |
+
model.load_state_dict(now_state_dict)
|
| 267 |
+
return model
|
convs/ucir_cifar_resnet.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Reference:
|
| 3 |
+
https://github.com/khurramjaved96/incremental-learning/blob/autoencoders/model/resnet32.py
|
| 4 |
+
https://github.com/hshustc/CVPR19_Incremental_Learning/blob/master/cifar100-class-incremental/modified_resnet_cifar.py
|
| 5 |
+
'''
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
# from convs.modified_linear import CosineLinear
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class DownsampleA(nn.Module):
|
| 13 |
+
def __init__(self, nIn, nOut, stride):
|
| 14 |
+
super(DownsampleA, self).__init__()
|
| 15 |
+
assert stride == 2
|
| 16 |
+
self.avg = nn.AvgPool2d(kernel_size=1, stride=stride)
|
| 17 |
+
|
| 18 |
+
def forward(self, x):
|
| 19 |
+
x = self.avg(x)
|
| 20 |
+
return torch.cat((x, x.mul(0)), 1)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class DownsampleB(nn.Module):
|
| 24 |
+
def __init__(self, nIn, nOut, stride):
|
| 25 |
+
super(DownsampleB, self).__init__()
|
| 26 |
+
self.conv = nn.Conv2d(nIn, nOut, kernel_size=1, stride=stride, padding=0, bias=False)
|
| 27 |
+
self.bn = nn.BatchNorm2d(nOut)
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
x = self.conv(x)
|
| 31 |
+
x = self.bn(x)
|
| 32 |
+
return x
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class DownsampleC(nn.Module):
|
| 36 |
+
def __init__(self, nIn, nOut, stride):
|
| 37 |
+
super(DownsampleC, self).__init__()
|
| 38 |
+
assert stride != 1 or nIn != nOut
|
| 39 |
+
self.conv = nn.Conv2d(nIn, nOut, kernel_size=1, stride=stride, padding=0, bias=False)
|
| 40 |
+
|
| 41 |
+
def forward(self, x):
|
| 42 |
+
x = self.conv(x)
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class DownsampleD(nn.Module):
|
| 47 |
+
def __init__(self, nIn, nOut, stride):
|
| 48 |
+
super(DownsampleD, self).__init__()
|
| 49 |
+
assert stride == 2
|
| 50 |
+
self.conv = nn.Conv2d(nIn, nOut, kernel_size=2, stride=stride, padding=0, bias=False)
|
| 51 |
+
self.bn = nn.BatchNorm2d(nOut)
|
| 52 |
+
|
| 53 |
+
def forward(self, x):
|
| 54 |
+
x = self.conv(x)
|
| 55 |
+
x = self.bn(x)
|
| 56 |
+
return x
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ResNetBasicblock(nn.Module):
|
| 60 |
+
expansion = 1
|
| 61 |
+
|
| 62 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, last=False):
|
| 63 |
+
super(ResNetBasicblock, self).__init__()
|
| 64 |
+
|
| 65 |
+
self.conv_a = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
|
| 66 |
+
self.bn_a = nn.BatchNorm2d(planes)
|
| 67 |
+
|
| 68 |
+
self.conv_b = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
|
| 69 |
+
self.bn_b = nn.BatchNorm2d(planes)
|
| 70 |
+
|
| 71 |
+
self.downsample = downsample
|
| 72 |
+
self.last = last
|
| 73 |
+
|
| 74 |
+
def forward(self, x):
|
| 75 |
+
residual = x
|
| 76 |
+
|
| 77 |
+
basicblock = self.conv_a(x)
|
| 78 |
+
basicblock = self.bn_a(basicblock)
|
| 79 |
+
basicblock = F.relu(basicblock, inplace=True)
|
| 80 |
+
|
| 81 |
+
basicblock = self.conv_b(basicblock)
|
| 82 |
+
basicblock = self.bn_b(basicblock)
|
| 83 |
+
|
| 84 |
+
if self.downsample is not None:
|
| 85 |
+
residual = self.downsample(x)
|
| 86 |
+
|
| 87 |
+
out = residual + basicblock
|
| 88 |
+
if not self.last:
|
| 89 |
+
out = F.relu(out, inplace=True)
|
| 90 |
+
|
| 91 |
+
return out
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class CifarResNet(nn.Module):
|
| 95 |
+
"""
|
| 96 |
+
ResNet optimized for the Cifar Dataset, as specified in
|
| 97 |
+
https://arxiv.org/abs/1512.03385.pdf
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def __init__(self, block, depth, channels=3):
|
| 101 |
+
super(CifarResNet, self).__init__()
|
| 102 |
+
|
| 103 |
+
# Model type specifies number of layers for CIFAR-10 and CIFAR-100 model
|
| 104 |
+
assert (depth - 2) % 6 == 0, 'depth should be one of 20, 32, 44, 56, 110'
|
| 105 |
+
layer_blocks = (depth - 2) // 6
|
| 106 |
+
|
| 107 |
+
self.conv_1_3x3 = nn.Conv2d(channels, 16, kernel_size=3, stride=1, padding=1, bias=False)
|
| 108 |
+
self.bn_1 = nn.BatchNorm2d(16)
|
| 109 |
+
|
| 110 |
+
self.inplanes = 16
|
| 111 |
+
self.stage_1 = self._make_layer(block, 16, layer_blocks, 1)
|
| 112 |
+
self.stage_2 = self._make_layer(block, 32, layer_blocks, 2)
|
| 113 |
+
self.stage_3 = self._make_layer(block, 64, layer_blocks, 2, last_phase=True)
|
| 114 |
+
self.avgpool = nn.AvgPool2d(8)
|
| 115 |
+
self.out_dim = 64 * block.expansion
|
| 116 |
+
# self.fc = CosineLinear(64*block.expansion, 10)
|
| 117 |
+
|
| 118 |
+
for m in self.modules():
|
| 119 |
+
if isinstance(m, nn.Conv2d):
|
| 120 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 121 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 122 |
+
nn.init.constant_(m.weight, 1)
|
| 123 |
+
nn.init.constant_(m.bias, 0)
|
| 124 |
+
|
| 125 |
+
def _make_layer(self, block, planes, blocks, stride=1, last_phase=False):
|
| 126 |
+
downsample = None
|
| 127 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 128 |
+
downsample = DownsampleB(self.inplanes, planes * block.expansion, stride) # DownsampleA => DownsampleB
|
| 129 |
+
|
| 130 |
+
layers = []
|
| 131 |
+
layers.append(block(self.inplanes, planes, stride, downsample))
|
| 132 |
+
self.inplanes = planes * block.expansion
|
| 133 |
+
if last_phase:
|
| 134 |
+
for i in range(1, blocks-1):
|
| 135 |
+
layers.append(block(self.inplanes, planes))
|
| 136 |
+
layers.append(block(self.inplanes, planes, last=True))
|
| 137 |
+
else:
|
| 138 |
+
for i in range(1, blocks):
|
| 139 |
+
layers.append(block(self.inplanes, planes))
|
| 140 |
+
|
| 141 |
+
return nn.Sequential(*layers)
|
| 142 |
+
|
| 143 |
+
def forward(self, x):
|
| 144 |
+
x = self.conv_1_3x3(x) # [bs, 16, 32, 32]
|
| 145 |
+
x = F.relu(self.bn_1(x), inplace=True)
|
| 146 |
+
|
| 147 |
+
x_1 = self.stage_1(x) # [bs, 16, 32, 32]
|
| 148 |
+
x_2 = self.stage_2(x_1) # [bs, 32, 16, 16]
|
| 149 |
+
x_3 = self.stage_3(x_2) # [bs, 64, 8, 8]
|
| 150 |
+
|
| 151 |
+
pooled = self.avgpool(x_3) # [bs, 64, 1, 1]
|
| 152 |
+
features = pooled.view(pooled.size(0), -1) # [bs, 64]
|
| 153 |
+
# out = self.fc(vector)
|
| 154 |
+
|
| 155 |
+
return {
|
| 156 |
+
'fmaps': [x_1, x_2, x_3],
|
| 157 |
+
'features': features
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def last_conv(self):
|
| 162 |
+
return self.stage_3[-1].conv_b
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def resnet20mnist():
|
| 166 |
+
"""Constructs a ResNet-20 model for MNIST."""
|
| 167 |
+
model = CifarResNet(ResNetBasicblock, 20, 1)
|
| 168 |
+
return model
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def resnet32mnist():
|
| 172 |
+
"""Constructs a ResNet-32 model for MNIST."""
|
| 173 |
+
model = CifarResNet(ResNetBasicblock, 32, 1)
|
| 174 |
+
return model
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def resnet20():
|
| 178 |
+
"""Constructs a ResNet-20 model for CIFAR-10."""
|
| 179 |
+
model = CifarResNet(ResNetBasicblock, 20)
|
| 180 |
+
return model
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def resnet32():
|
| 184 |
+
"""Constructs a ResNet-32 model for CIFAR-10."""
|
| 185 |
+
model = CifarResNet(ResNetBasicblock, 32)
|
| 186 |
+
return model
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def resnet44():
|
| 190 |
+
"""Constructs a ResNet-44 model for CIFAR-10."""
|
| 191 |
+
model = CifarResNet(ResNetBasicblock, 44)
|
| 192 |
+
return model
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def resnet56():
|
| 196 |
+
"""Constructs a ResNet-56 model for CIFAR-10."""
|
| 197 |
+
model = CifarResNet(ResNetBasicblock, 56)
|
| 198 |
+
return model
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def resnet110():
|
| 202 |
+
"""Constructs a ResNet-110 model for CIFAR-10."""
|
| 203 |
+
model = CifarResNet(ResNetBasicblock, 110)
|
| 204 |
+
return model
|
convs/ucir_resnet.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Reference:
|
| 3 |
+
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
|
| 4 |
+
'''
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
try:
|
| 8 |
+
from torchvision.models.utils import load_state_dict_from_url
|
| 9 |
+
except:
|
| 10 |
+
from torch.hub import load_state_dict_from_url
|
| 11 |
+
|
| 12 |
+
__all__ = ['resnet50']
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
model_urls = {
|
| 16 |
+
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
|
| 17 |
+
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
|
| 18 |
+
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
|
| 19 |
+
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
|
| 20 |
+
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
|
| 21 |
+
'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
|
| 22 |
+
'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
|
| 23 |
+
'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
|
| 24 |
+
'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
|
| 29 |
+
"""3x3 convolution with padding"""
|
| 30 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
| 31 |
+
padding=dilation, groups=groups, bias=False, dilation=dilation)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def conv1x1(in_planes, out_planes, stride=1):
|
| 35 |
+
"""1x1 convolution"""
|
| 36 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class BasicBlock(nn.Module):
|
| 40 |
+
expansion = 1
|
| 41 |
+
__constants__ = ['downsample']
|
| 42 |
+
|
| 43 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
|
| 44 |
+
base_width=64, dilation=1, norm_layer=None, last=False):
|
| 45 |
+
super(BasicBlock, self).__init__()
|
| 46 |
+
if norm_layer is None:
|
| 47 |
+
norm_layer = nn.BatchNorm2d
|
| 48 |
+
if groups != 1 or base_width != 64:
|
| 49 |
+
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
|
| 50 |
+
if dilation > 1:
|
| 51 |
+
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
|
| 52 |
+
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
|
| 53 |
+
self.conv1 = conv3x3(inplanes, planes, stride)
|
| 54 |
+
self.bn1 = norm_layer(planes)
|
| 55 |
+
self.relu = nn.ReLU(inplace=True)
|
| 56 |
+
self.conv2 = conv3x3(planes, planes)
|
| 57 |
+
self.bn2 = norm_layer(planes)
|
| 58 |
+
self.downsample = downsample
|
| 59 |
+
self.stride = stride
|
| 60 |
+
self.last = last
|
| 61 |
+
|
| 62 |
+
def forward(self, x):
|
| 63 |
+
identity = x
|
| 64 |
+
|
| 65 |
+
out = self.conv1(x)
|
| 66 |
+
out = self.bn1(out)
|
| 67 |
+
out = self.relu(out)
|
| 68 |
+
|
| 69 |
+
out = self.conv2(out)
|
| 70 |
+
out = self.bn2(out)
|
| 71 |
+
|
| 72 |
+
if self.downsample is not None:
|
| 73 |
+
identity = self.downsample(x)
|
| 74 |
+
|
| 75 |
+
out += identity
|
| 76 |
+
if not self.last:
|
| 77 |
+
out = self.relu(out)
|
| 78 |
+
|
| 79 |
+
return out
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class Bottleneck(nn.Module):
|
| 83 |
+
expansion = 4
|
| 84 |
+
__constants__ = ['downsample']
|
| 85 |
+
|
| 86 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
|
| 87 |
+
base_width=64, dilation=1, norm_layer=None, last=False):
|
| 88 |
+
super(Bottleneck, self).__init__()
|
| 89 |
+
if norm_layer is None:
|
| 90 |
+
norm_layer = nn.BatchNorm2d
|
| 91 |
+
width = int(planes * (base_width / 64.)) * groups
|
| 92 |
+
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
|
| 93 |
+
self.conv1 = conv1x1(inplanes, width)
|
| 94 |
+
self.bn1 = norm_layer(width)
|
| 95 |
+
self.conv2 = conv3x3(width, width, stride, groups, dilation)
|
| 96 |
+
self.bn2 = norm_layer(width)
|
| 97 |
+
self.conv3 = conv1x1(width, planes * self.expansion)
|
| 98 |
+
self.bn3 = norm_layer(planes * self.expansion)
|
| 99 |
+
self.relu = nn.ReLU(inplace=True)
|
| 100 |
+
self.downsample = downsample
|
| 101 |
+
self.stride = stride
|
| 102 |
+
self.last = last
|
| 103 |
+
|
| 104 |
+
def forward(self, x):
|
| 105 |
+
identity = x
|
| 106 |
+
|
| 107 |
+
out = self.conv1(x)
|
| 108 |
+
out = self.bn1(out)
|
| 109 |
+
out = self.relu(out)
|
| 110 |
+
|
| 111 |
+
out = self.conv2(out)
|
| 112 |
+
out = self.bn2(out)
|
| 113 |
+
out = self.relu(out)
|
| 114 |
+
|
| 115 |
+
out = self.conv3(out)
|
| 116 |
+
out = self.bn3(out)
|
| 117 |
+
|
| 118 |
+
if self.downsample is not None:
|
| 119 |
+
identity = self.downsample(x)
|
| 120 |
+
|
| 121 |
+
out += identity
|
| 122 |
+
if not self.last:
|
| 123 |
+
out = self.relu(out)
|
| 124 |
+
|
| 125 |
+
return out
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class ResNet(nn.Module):
|
| 129 |
+
|
| 130 |
+
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
|
| 131 |
+
groups=1, width_per_group=64, replace_stride_with_dilation=None,
|
| 132 |
+
norm_layer=None, args=None):
|
| 133 |
+
super(ResNet, self).__init__()
|
| 134 |
+
if norm_layer is None:
|
| 135 |
+
norm_layer = nn.BatchNorm2d
|
| 136 |
+
self._norm_layer = norm_layer
|
| 137 |
+
|
| 138 |
+
self.inplanes = 64
|
| 139 |
+
self.dilation = 1
|
| 140 |
+
if replace_stride_with_dilation is None:
|
| 141 |
+
# each element in the tuple indicates if we should replace
|
| 142 |
+
# the 2x2 stride with a dilated convolution instead
|
| 143 |
+
replace_stride_with_dilation = [False, False, False]
|
| 144 |
+
if len(replace_stride_with_dilation) != 3:
|
| 145 |
+
raise ValueError("replace_stride_with_dilation should be None "
|
| 146 |
+
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
|
| 147 |
+
self.groups = groups
|
| 148 |
+
self.base_width = width_per_group
|
| 149 |
+
|
| 150 |
+
assert args is not None, "you should pass args to resnet"
|
| 151 |
+
if 'cifar' in args["dataset"]:
|
| 152 |
+
self.conv1 = nn.Sequential(nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False),
|
| 153 |
+
nn.BatchNorm2d(self.inplanes), nn.ReLU(inplace=True))
|
| 154 |
+
elif 'imagenet' in args["dataset"]:
|
| 155 |
+
if args["init_cls"] == args["increment"]:
|
| 156 |
+
self.conv1 = nn.Sequential(
|
| 157 |
+
nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False),
|
| 158 |
+
nn.BatchNorm2d(self.inplanes),
|
| 159 |
+
nn.ReLU(inplace=True),
|
| 160 |
+
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
|
| 161 |
+
)
|
| 162 |
+
else:
|
| 163 |
+
self.conv1 = nn.Sequential(
|
| 164 |
+
nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False),
|
| 165 |
+
nn.BatchNorm2d(self.inplanes),
|
| 166 |
+
nn.ReLU(inplace=True),
|
| 167 |
+
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
| 171 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
|
| 172 |
+
dilate=replace_stride_with_dilation[0])
|
| 173 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
|
| 174 |
+
dilate=replace_stride_with_dilation[1])
|
| 175 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
|
| 176 |
+
dilate=replace_stride_with_dilation[2], last_phase=True)
|
| 177 |
+
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
|
| 178 |
+
self.out_dim = 512 * block.expansion
|
| 179 |
+
self.fc = nn.Linear(512 * block.expansion, num_classes) # Removed in _forward_impl
|
| 180 |
+
|
| 181 |
+
for m in self.modules():
|
| 182 |
+
if isinstance(m, nn.Conv2d):
|
| 183 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 184 |
+
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
|
| 185 |
+
nn.init.constant_(m.weight, 1)
|
| 186 |
+
nn.init.constant_(m.bias, 0)
|
| 187 |
+
|
| 188 |
+
# Zero-initialize the last BN in each residual branch,
|
| 189 |
+
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
|
| 190 |
+
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
|
| 191 |
+
if zero_init_residual:
|
| 192 |
+
for m in self.modules():
|
| 193 |
+
if isinstance(m, Bottleneck):
|
| 194 |
+
nn.init.constant_(m.bn3.weight, 0)
|
| 195 |
+
elif isinstance(m, BasicBlock):
|
| 196 |
+
nn.init.constant_(m.bn2.weight, 0)
|
| 197 |
+
|
| 198 |
+
def _make_layer(self, block, planes, blocks, stride=1, dilate=False, last_phase=False):
|
| 199 |
+
norm_layer = self._norm_layer
|
| 200 |
+
downsample = None
|
| 201 |
+
previous_dilation = self.dilation
|
| 202 |
+
if dilate:
|
| 203 |
+
self.dilation *= stride
|
| 204 |
+
stride = 1
|
| 205 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 206 |
+
downsample = nn.Sequential(
|
| 207 |
+
conv1x1(self.inplanes, planes * block.expansion, stride),
|
| 208 |
+
norm_layer(planes * block.expansion),
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
layers = []
|
| 212 |
+
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
|
| 213 |
+
self.base_width, previous_dilation, norm_layer))
|
| 214 |
+
self.inplanes = planes * block.expansion
|
| 215 |
+
if last_phase:
|
| 216 |
+
for _ in range(1, blocks-1):
|
| 217 |
+
layers.append(block(self.inplanes, planes, groups=self.groups,
|
| 218 |
+
base_width=self.base_width, dilation=self.dilation,
|
| 219 |
+
norm_layer=norm_layer))
|
| 220 |
+
layers.append(block(self.inplanes, planes, groups=self.groups,
|
| 221 |
+
base_width=self.base_width, dilation=self.dilation,
|
| 222 |
+
norm_layer=norm_layer, last=True))
|
| 223 |
+
else:
|
| 224 |
+
for _ in range(1, blocks):
|
| 225 |
+
layers.append(block(self.inplanes, planes, groups=self.groups,
|
| 226 |
+
base_width=self.base_width, dilation=self.dilation,
|
| 227 |
+
norm_layer=norm_layer))
|
| 228 |
+
|
| 229 |
+
return nn.Sequential(*layers)
|
| 230 |
+
|
| 231 |
+
def _forward_impl(self, x):
|
| 232 |
+
# See note [TorchScript super()]
|
| 233 |
+
x = self.conv1(x) # [bs, 64, 32, 32]
|
| 234 |
+
|
| 235 |
+
x_1 = self.layer1(x) # [bs, 128, 32, 32]
|
| 236 |
+
x_2 = self.layer2(x_1) # [bs, 256, 16, 16]
|
| 237 |
+
x_3 = self.layer3(x_2) # [bs, 512, 8, 8]
|
| 238 |
+
x_4 = self.layer4(x_3) # [bs, 512, 4, 4]
|
| 239 |
+
|
| 240 |
+
pooled = self.avgpool(x_4) # [bs, 512, 1, 1]
|
| 241 |
+
features = torch.flatten(pooled, 1) # [bs, 512]
|
| 242 |
+
# x = self.fc(x)
|
| 243 |
+
|
| 244 |
+
return {
|
| 245 |
+
'fmaps': [x_1, x_2, x_3, x_4],
|
| 246 |
+
'features': features
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
def forward(self, x):
|
| 250 |
+
return self._forward_impl(x)
|
| 251 |
+
|
| 252 |
+
@property
|
| 253 |
+
def last_conv(self):
|
| 254 |
+
if hasattr(self.layer4[-1], 'conv3'):
|
| 255 |
+
return self.layer4[-1].conv3
|
| 256 |
+
else:
|
| 257 |
+
return self.layer4[-1].conv2
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _resnet(arch, block, layers, pretrained, progress, **kwargs):
|
| 261 |
+
model = ResNet(block, layers, **kwargs)
|
| 262 |
+
if pretrained:
|
| 263 |
+
state_dict = load_state_dict_from_url(model_urls[arch],
|
| 264 |
+
progress=progress)
|
| 265 |
+
model.load_state_dict(state_dict)
|
| 266 |
+
return model
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def resnet18(pretrained=False, progress=True, **kwargs):
|
| 270 |
+
r"""ResNet-18 model from
|
| 271 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 272 |
+
Args:
|
| 273 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 274 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 275 |
+
"""
|
| 276 |
+
return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
|
| 277 |
+
**kwargs)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def resnet34(pretrained=False, progress=True, **kwargs):
|
| 281 |
+
r"""ResNet-34 model from
|
| 282 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 283 |
+
Args:
|
| 284 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 285 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 286 |
+
"""
|
| 287 |
+
return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
|
| 288 |
+
**kwargs)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def resnet50(pretrained=False, progress=True, **kwargs):
|
| 292 |
+
r"""ResNet-50 model from
|
| 293 |
+
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
|
| 294 |
+
Args:
|
| 295 |
+
pretrained (bool): If True, returns a model pre-trained on ImageNet
|
| 296 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 297 |
+
"""
|
| 298 |
+
return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
|
| 299 |
+
**kwargs)
|
exps/blcl.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prefix": "benchmark",
|
| 3 |
+
"memory_size": 2000,
|
| 4 |
+
"memory_per_class":20,
|
| 5 |
+
"fixed_memory": false,
|
| 6 |
+
"shuffle": true,
|
| 7 |
+
"init_cls": 4,
|
| 8 |
+
"increment": 2,
|
| 9 |
+
"model_name": "blcl",
|
| 10 |
+
"train_base": true,
|
| 11 |
+
"train_adaptive": false,
|
| 12 |
+
"debug": false,
|
| 13 |
+
"skip": false,
|
| 14 |
+
"device": ["0"],
|
| 15 |
+
"seed":[1993],
|
| 16 |
+
"scheduler": "steplr",
|
| 17 |
+
"init_epoch": 300,
|
| 18 |
+
"t_max": null,
|
| 19 |
+
"init_lr" : 0.1,
|
| 20 |
+
"init_weight_decay" : 5e-4,
|
| 21 |
+
"init_lr_decay" : 0.1,
|
| 22 |
+
"init_milestones" : [60,120,170],
|
| 23 |
+
"milestones" : [80,120,150],
|
| 24 |
+
"epochs":300,
|
| 25 |
+
"lrate" : 0.1,
|
| 26 |
+
"batch_size" : 64,
|
| 27 |
+
"weight_decay" : 2e-4,
|
| 28 |
+
"lrate_decay" : 0.1,
|
| 29 |
+
"alpha_aux" : 1.0
|
| 30 |
+
}
|
exps/ewc.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prefix": "reproduce",
|
| 3 |
+
"memory_size": 2000,
|
| 4 |
+
"memory_per_class": 20,
|
| 5 |
+
"fixed_memory": false,
|
| 6 |
+
"shuffle": true,
|
| 7 |
+
"init_cls": 4,
|
| 8 |
+
"increment": 2,
|
| 9 |
+
"model_name": "ewc",
|
| 10 |
+
"convnet_type": "resnet32",
|
| 11 |
+
"device": ["0"],
|
| 12 |
+
"seed": [1993]
|
| 13 |
+
}
|
| 14 |
+
|
exps/finetune.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prefix": "reproduce",
|
| 3 |
+
"memory_size": 2000,
|
| 4 |
+
"memory_per_class": 20,
|
| 5 |
+
"fixed_memory": false,
|
| 6 |
+
"shuffle": true,
|
| 7 |
+
"init_cls": 4,
|
| 8 |
+
"increment": 2,
|
| 9 |
+
"model_name": "finetune",
|
| 10 |
+
"convnet_type": "resnet32",
|
| 11 |
+
"device": ["0"],
|
| 12 |
+
"seed": [1993]
|
| 13 |
+
}
|
exps/icarl.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prefix": "reproduce",
|
| 3 |
+
"memory_size": 2000,
|
| 4 |
+
"memory_per_class": 20,
|
| 5 |
+
"fixed_memory": false,
|
| 6 |
+
"shuffle": true,
|
| 7 |
+
"init_cls": 4,
|
| 8 |
+
"increment": 2,
|
| 9 |
+
"model_name": "icarl",
|
| 10 |
+
"convnet_type": "resnet32",
|
| 11 |
+
"device": ["0"],
|
| 12 |
+
"seed": [1993]
|
| 13 |
+
}
|
| 14 |
+
|
exps/lwf.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prefix": "reproduce",
|
| 3 |
+
"memory_size": 2000,
|
| 4 |
+
"memory_per_class": 20,
|
| 5 |
+
"fixed_memory": false,
|
| 6 |
+
"shuffle": true,
|
| 7 |
+
"init_cls": 4,
|
| 8 |
+
"increment": 2,
|
| 9 |
+
"model_name": "lwf",
|
| 10 |
+
"convnet_type": "resnet32",
|
| 11 |
+
"device": ["0"],
|
| 12 |
+
"seed": [1993]
|
| 13 |
+
}
|
exps/memo.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prefix": "benchmark",
|
| 3 |
+
"memory_size": 2000,
|
| 4 |
+
"memory_per_class":20,
|
| 5 |
+
"fixed_memory": false,
|
| 6 |
+
"shuffle": true,
|
| 7 |
+
"init_cls": 4,
|
| 8 |
+
"increment": 2,
|
| 9 |
+
"model_name": "memo",
|
| 10 |
+
"train_base": true,
|
| 11 |
+
"train_adaptive": false,
|
| 12 |
+
"debug": false,
|
| 13 |
+
"skip": false,
|
| 14 |
+
"device": ["0"],
|
| 15 |
+
"seed":[1993],
|
| 16 |
+
"scheduler": "steplr",
|
| 17 |
+
"init_epoch": 300,
|
| 18 |
+
"t_max": null,
|
| 19 |
+
"init_lr" : 0.1,
|
| 20 |
+
"init_weight_decay" : 5e-4,
|
| 21 |
+
"init_lr_decay" : 0.1,
|
| 22 |
+
"init_milestones" : [60,120,170],
|
| 23 |
+
"milestones" : [80,120,150],
|
| 24 |
+
"epochs":300,
|
| 25 |
+
"lrate" : 0.1,
|
| 26 |
+
"batch_size" : 64,
|
| 27 |
+
"weight_decay" : 2e-4,
|
| 28 |
+
"lrate_decay" : 0.1,
|
| 29 |
+
"alpha_aux" : 1.0
|
| 30 |
+
}
|
exps/replay.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prefix": "reproduce",
|
| 3 |
+
"memory_size": 2000,
|
| 4 |
+
"memory_per_class": 20,
|
| 5 |
+
"fixed_memory": false,
|
| 6 |
+
"shuffle": true,
|
| 7 |
+
"init_cls": 4,
|
| 8 |
+
"increment": 2,
|
| 9 |
+
"model_name": "replay",
|
| 10 |
+
"convnet_type": "resnet32",
|
| 11 |
+
"device": ["0"],
|
| 12 |
+
"seed": [1993]
|
| 13 |
+
}
|
main.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import argparse
|
| 3 |
+
from trainer import train
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
def string_to_list(args):
|
| 7 |
+
"""
|
| 8 |
+
Convert a JSON string to a Python list.
|
| 9 |
+
|
| 10 |
+
Args:
|
| 11 |
+
args (str): JSON string representing a list.
|
| 12 |
+
|
| 13 |
+
Returns:
|
| 14 |
+
list: Parsed list from the JSON string.
|
| 15 |
+
"""
|
| 16 |
+
return json.loads(args)
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
"""
|
| 20 |
+
Function to set up the training process.
|
| 21 |
+
Parses command line arguments, loads configuration from a JSON file, and starts the training.
|
| 22 |
+
"""
|
| 23 |
+
# Parse command-line arguments
|
| 24 |
+
args = setup_parser().parse_args()
|
| 25 |
+
param = load_json(args.config)
|
| 26 |
+
args = vars(args)
|
| 27 |
+
args.update(param)
|
| 28 |
+
train(args)
|
| 29 |
+
|
| 30 |
+
def load_json(settings_path):
|
| 31 |
+
"""
|
| 32 |
+
Load parameters from a JSON file.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
settings_path (str): Path to the JSON configuration file.
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
dict: Configuration parameters loaded from the JSON file.
|
| 39 |
+
"""
|
| 40 |
+
with open(settings_path) as data_file:
|
| 41 |
+
param = json.load(data_file)
|
| 42 |
+
return param
|
| 43 |
+
|
| 44 |
+
def setup_parser():
|
| 45 |
+
parser = argparse.ArgumentParser(description='Reproduce of multiple continual learning algorthms.')
|
| 46 |
+
parser.add_argument('--config', type=str, default='./exps/finetune.json', help='Json file of settings.')
|
| 47 |
+
parser.add_argument('--dataset', default="gnss", help="Kind of dataset", type=str)
|
| 48 |
+
parser.add_argument('--summary_file', type=str, default='run_new',help='path for the tensorboard experiment')
|
| 49 |
+
parser.add_argument('--layers', help='delimited list input', type=string_to_list)
|
| 50 |
+
parser.add_argument('--type', default="normal", help='Type of memo models (normal or avg)', type=str)
|
| 51 |
+
parser.add_argument('--convnet_type', default="memo_resnet32", help="Kind of resnet", type=str)
|
| 52 |
+
return parser
|
| 53 |
+
|
| 54 |
+
if __name__ == '__main__':
|
| 55 |
+
main()
|
models/__init__.py
ADDED
|
File without changes
|
models/base.py
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import logging
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.utils.data import DataLoader
|
| 7 |
+
from utils.toolkit import tensor2numpy, accuracy
|
| 8 |
+
from scipy.spatial.distance import cdist
|
| 9 |
+
import os
|
| 10 |
+
from sklearn.metrics import confusion_matrix
|
| 11 |
+
import seaborn as sn
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
import os
|
| 15 |
+
import shutil
|
| 16 |
+
from sklearn.metrics import f1_score, recall_score, precision_score
|
| 17 |
+
import matplotlib
|
| 18 |
+
import matplotlib.pyplot as plt
|
| 19 |
+
plt.rcParams["font.family"] = "serif"
|
| 20 |
+
|
| 21 |
+
EPSILON = 1e-8
|
| 22 |
+
batch_size = 64
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class BaseLearner(object):
|
| 26 |
+
def __init__(self, args):
|
| 27 |
+
self.args = args
|
| 28 |
+
self.curr_acc = None
|
| 29 |
+
self._cur_task = -1
|
| 30 |
+
self._known_classes = 0
|
| 31 |
+
self._total_classes = 0
|
| 32 |
+
self._network = None
|
| 33 |
+
self._old_network = None
|
| 34 |
+
self._data_memory, self._targets_memory = np.array([]), np.array([])
|
| 35 |
+
self.topk = 3
|
| 36 |
+
self._memory_size = args["memory_size"]
|
| 37 |
+
self._memory_per_class = args.get("memory_per_class", None)
|
| 38 |
+
self._fixed_memory = args.get("fixed_memory", False)
|
| 39 |
+
self._device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 40 |
+
#self._device = args["device"][0]
|
| 41 |
+
self._multiple_gpus = args["device"]
|
| 42 |
+
self._predictions_folder = os.path.join('predictions', args["summary_file"])
|
| 43 |
+
|
| 44 |
+
if os.path.exists(self._predictions_folder):
|
| 45 |
+
|
| 46 |
+
shutil.rmtree(self._predictions_folder)
|
| 47 |
+
|
| 48 |
+
os.mkdir(self._predictions_folder)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def exemplar_size(self):
|
| 54 |
+
assert len(self._data_memory) == len(
|
| 55 |
+
self._targets_memory
|
| 56 |
+
), "Exemplar size error."
|
| 57 |
+
return len(self._targets_memory)
|
| 58 |
+
|
| 59 |
+
@property
|
| 60 |
+
def samples_per_class(self):
|
| 61 |
+
if self._fixed_memory:
|
| 62 |
+
return self._memory_per_class
|
| 63 |
+
else:
|
| 64 |
+
assert self._total_classes != 0, "Total classes is 0"
|
| 65 |
+
return self._memory_size // self._total_classes
|
| 66 |
+
|
| 67 |
+
@property
|
| 68 |
+
def feature_dim(self):
|
| 69 |
+
if isinstance(self._network, nn.DataParallel):
|
| 70 |
+
return self._network.module.feature_dim
|
| 71 |
+
else:
|
| 72 |
+
return self._network.feature_dim
|
| 73 |
+
|
| 74 |
+
def build_rehearsal_memory(self, data_manager, per_class):
|
| 75 |
+
if self._fixed_memory:
|
| 76 |
+
self._construct_exemplar_unified(data_manager, per_class)
|
| 77 |
+
else:
|
| 78 |
+
self._reduce_exemplar(data_manager, per_class)
|
| 79 |
+
self._construct_exemplar(data_manager, per_class)
|
| 80 |
+
|
| 81 |
+
def save_checkpoint(self):
|
| 82 |
+
|
| 83 |
+
torch.save(self._network.state_dict(), os.path.join(self._predictions_folder, "state_dict_task_{}.pth".format(self._cur_task)))
|
| 84 |
+
|
| 85 |
+
def save_model(self):
|
| 86 |
+
self._network.cpu()
|
| 87 |
+
model_scripted = torch.jit.script(self._network)
|
| 88 |
+
model_scripted.save(os.path.join(self._predictions_folder, 'model_task_{}.pt'.format(self._cur_task)))
|
| 89 |
+
|
| 90 |
+
def after_task(self):
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
def _evaluate(self, y_pred, y_true):
|
| 94 |
+
ret = {}
|
| 95 |
+
grouped = accuracy(y_pred.T[0], y_true, self._known_classes)
|
| 96 |
+
ret["grouped"] = grouped
|
| 97 |
+
ret["top1"] = grouped["total"]
|
| 98 |
+
ret["top{}".format(self.topk)] = np.around(
|
| 99 |
+
(y_pred.T == np.tile(y_true, (self.topk, 1))).sum() * 100 / len(y_true),
|
| 100 |
+
decimals=2,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
return ret
|
| 104 |
+
|
| 105 |
+
def eval_task(self, save_conf=False):
|
| 106 |
+
y_pred, y_true = self._eval_cnn(self.test_loader)
|
| 107 |
+
cnn_accy = self._evaluate(y_pred, y_true)
|
| 108 |
+
|
| 109 |
+
if hasattr(self, "_class_means"):
|
| 110 |
+
y_pred, y_true = self._eval_nme(self.test_loader, self._class_means)
|
| 111 |
+
nme_accy = self._evaluate(y_pred, y_true)
|
| 112 |
+
else:
|
| 113 |
+
nme_accy = None
|
| 114 |
+
|
| 115 |
+
if save_conf:
|
| 116 |
+
_pred = y_pred.T[0]
|
| 117 |
+
_pred_path = os.path.join(self.args['logfilename'], "pred.npy")
|
| 118 |
+
_target_path = os.path.join(self.args['logfilename'], "target.npy")
|
| 119 |
+
np.save(_pred_path, _pred)
|
| 120 |
+
np.save(_target_path, y_true)
|
| 121 |
+
|
| 122 |
+
_save_dir = os.path.join(f"./results/conf_matrix/{self.args['prefix']}")
|
| 123 |
+
os.makedirs(_save_dir, exist_ok=True)
|
| 124 |
+
_save_path = os.path.join(_save_dir, f"{self.args['csv_name']}.csv")
|
| 125 |
+
with open(_save_path, "a+") as f:
|
| 126 |
+
f.write(f"{self.args['time_str']},{self.args['model_name']},{_pred_path},{_target_path} \n")
|
| 127 |
+
|
| 128 |
+
return cnn_accy, nme_accy
|
| 129 |
+
|
| 130 |
+
def incremental_train(self):
|
| 131 |
+
pass
|
| 132 |
+
|
| 133 |
+
def _train(self):
|
| 134 |
+
pass
|
| 135 |
+
|
| 136 |
+
def _get_memory(self):
|
| 137 |
+
if len(self._data_memory) == 0:
|
| 138 |
+
return None
|
| 139 |
+
else:
|
| 140 |
+
return (self._data_memory, self._targets_memory)
|
| 141 |
+
|
| 142 |
+
def _compute_accuracy(self, model, loader):
|
| 143 |
+
model.eval()
|
| 144 |
+
y_pred = [] # save predction
|
| 145 |
+
y_true = [] # save ground truth
|
| 146 |
+
|
| 147 |
+
correct, total = 0, 0
|
| 148 |
+
for i, (_, inputs, targets) in enumerate(loader):
|
| 149 |
+
inputs = inputs.to(self._device)
|
| 150 |
+
with torch.no_grad():
|
| 151 |
+
outputs = model(inputs)["logits"]
|
| 152 |
+
predicts = torch.max(outputs, dim=1)[1]
|
| 153 |
+
|
| 154 |
+
correct += (predicts.cpu() == targets).sum()
|
| 155 |
+
total += len(targets)
|
| 156 |
+
|
| 157 |
+
y_pred.extend(predicts.data.cpu().numpy()) # save prediction
|
| 158 |
+
y_true.extend(targets.data.cpu().numpy()) # save ground truth
|
| 159 |
+
|
| 160 |
+
true_targets = np.array(y_true)
|
| 161 |
+
pred_targets = np.array(y_pred)
|
| 162 |
+
|
| 163 |
+
uq_true, count_true = np.unique(true_targets, return_counts=True)
|
| 164 |
+
uq_pred, count_pred = np.unique(pred_targets, return_counts=True)
|
| 165 |
+
logging.debug('Task: {}\tUnique True samples after each epoch: {}\tCounts: {}'.format(self._cur_task, uq_true, count_true))
|
| 166 |
+
logging.debug('Task: {}\tUnique Predicted samples after each epoch: {}\tCounts: {}'.format(self._cur_task, uq_pred, count_pred))
|
| 167 |
+
|
| 168 |
+
correct_new = (true_targets == pred_targets).sum()
|
| 169 |
+
|
| 170 |
+
logging.info('#### Task: {} Test ACC after each epoch: {} ####'.format(self._cur_task,
|
| 171 |
+
np.around(correct_new * 100 / len(y_pred), decimals=2)))
|
| 172 |
+
return np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 173 |
+
|
| 174 |
+
def _createConfusionMatrix(self, model, loader):
|
| 175 |
+
"""
|
| 176 |
+
Creates and visualizes the confusion matrix for evaluating the model's performance.
|
| 177 |
+
|
| 178 |
+
Parameters:
|
| 179 |
+
model (torch.nn.Module): The trained model for which the confusion matrix is being generated.
|
| 180 |
+
loader (torch.utils.data.DataLoader): The data loader for the dataset to be evaluated.
|
| 181 |
+
|
| 182 |
+
Returns:
|
| 183 |
+
matplotlib.figure.Figure: A figure containing the confusion matrix visualization.
|
| 184 |
+
|
| 185 |
+
Computes various evaluation metrics including accuracy, F1-score, precision, and recall.
|
| 186 |
+
Additionally, it saves the predictions and embeddings for further analysis.
|
| 187 |
+
"""
|
| 188 |
+
model.eval()
|
| 189 |
+
y_pred = [] # save predction
|
| 190 |
+
y_true = [] # save ground truth
|
| 191 |
+
embeddings = []
|
| 192 |
+
correct, total = 0, 0
|
| 193 |
+
# iterate over data
|
| 194 |
+
for i, (_, inputs, targets) in enumerate(loader):
|
| 195 |
+
inputs = inputs.to(self._device)
|
| 196 |
+
with torch.no_grad():
|
| 197 |
+
outputs = model(inputs)["logits"]
|
| 198 |
+
embedding = model(inputs)["features"]
|
| 199 |
+
predicts = torch.max(outputs, dim=1)[1]
|
| 200 |
+
correct += (predicts.cpu() == targets).sum()
|
| 201 |
+
total += len(targets)
|
| 202 |
+
|
| 203 |
+
y_pred.extend(predicts.data.cpu().numpy()) # save prediction
|
| 204 |
+
y_true.extend(targets.data.cpu().numpy()) # save ground truth
|
| 205 |
+
embeddings.extend(embedding.data.cpu().numpy()) # save the embeddings
|
| 206 |
+
np.save(os.path.join(self._predictions_folder,
|
| 207 |
+
'predictions_task_{}_tr_pr.npy'.format(self._cur_task)), np.array(list(zip(y_true, y_pred))))
|
| 208 |
+
assert np.stack(embeddings).shape[0] == len(embeddings), "embeddings are not of the desired shape"
|
| 209 |
+
np.save(os.path.join(self._predictions_folder,
|
| 210 |
+
'embeddings_task_{}.npy'.format(self._cur_task)), np.stack(embeddings))
|
| 211 |
+
self.save_checkpoint()
|
| 212 |
+
self.curr_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 213 |
+
|
| 214 |
+
logging.info('Task: {}\tTest ACC on Inference data ----> {}'.format(self._cur_task, self.curr_acc))
|
| 215 |
+
|
| 216 |
+
# constant for classes
|
| 217 |
+
classes = tuple(map(str, np.unique(y_true)))
|
| 218 |
+
f1_scores = f1_score(y_true, y_pred, average=None)
|
| 219 |
+
recall_scores = recall_score(y_true, y_pred, average=None)
|
| 220 |
+
precision_scores = precision_score(y_true, y_pred, average=None)
|
| 221 |
+
mat_size = len(classes)
|
| 222 |
+
f1_matrix = np.zeros((mat_size, mat_size), float)
|
| 223 |
+
precision_matrix = np.zeros((mat_size, mat_size), float)
|
| 224 |
+
recall_matrix = np.zeros((mat_size, mat_size), float)
|
| 225 |
+
|
| 226 |
+
np.fill_diagonal(f1_matrix, f1_scores)
|
| 227 |
+
np.fill_diagonal(precision_matrix, precision_scores)
|
| 228 |
+
np.fill_diagonal(recall_matrix, recall_scores)
|
| 229 |
+
|
| 230 |
+
# print the count of each testing label
|
| 231 |
+
uq_lbls, lbls_counts = np.unique(y_true, return_counts=True)
|
| 232 |
+
logging.info('Testing on the classes {}\tCount of each class {}'.format(uq_lbls, lbls_counts))
|
| 233 |
+
|
| 234 |
+
# Build confusion matrix
|
| 235 |
+
cf_matrix = confusion_matrix(y_true, y_pred)
|
| 236 |
+
|
| 237 |
+
group_counts = ['{0:0.0f}'.format(value) for value in cf_matrix.flatten()]
|
| 238 |
+
group_f1 = ['{0:0.4f}'.format(value) for value in f1_matrix.flatten()]
|
| 239 |
+
group_precision = ['{0:0.4f}'.format(value) for value in precision_matrix.flatten()]
|
| 240 |
+
group_recall = ['{0:0.4f}'.format(value) for value in recall_matrix.flatten()]
|
| 241 |
+
|
| 242 |
+
percentages = cf_matrix / np.sum(cf_matrix, axis=1)[:, None]
|
| 243 |
+
group_percentages = ['{0:.2%}'.format(value) for value in percentages.flatten()]
|
| 244 |
+
|
| 245 |
+
labels = ['{}\n{}\n{} {}'.format(v2, v3, v4, v5) for v2, v3, v4, v5 in zip(group_counts, group_f1, group_precision, group_recall)]
|
| 246 |
+
labels = np.asarray(labels).reshape(len(classes), len(classes))
|
| 247 |
+
|
| 248 |
+
df_cm = pd.DataFrame(cf_matrix , index=[i for i in classes],
|
| 249 |
+
columns=[i for i in classes])
|
| 250 |
+
|
| 251 |
+
plt.figure(figsize=(15, 15))
|
| 252 |
+
return sn.heatmap(df_cm, annot=labels, fmt='',
|
| 253 |
+
cmap="rainbow",
|
| 254 |
+
norm=matplotlib.colors.LogNorm(),
|
| 255 |
+
linewidths=0.3,
|
| 256 |
+
linecolor='black',
|
| 257 |
+
annot_kws={"color":"black"}
|
| 258 |
+
).get_figure()
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _eval_cnn(self, loader):
|
| 262 |
+
self._network.eval()
|
| 263 |
+
y_pred, y_true = [], []
|
| 264 |
+
for _, (_, inputs, targets) in enumerate(loader):
|
| 265 |
+
inputs = inputs.to(self._device)
|
| 266 |
+
with torch.no_grad():
|
| 267 |
+
outputs = self._network(inputs)["logits"]
|
| 268 |
+
predicts = torch.topk(
|
| 269 |
+
outputs, k=self.topk, dim=1, largest=True, sorted=True
|
| 270 |
+
)[
|
| 271 |
+
1
|
| 272 |
+
] # [bs, topk]
|
| 273 |
+
y_pred.append(predicts.cpu().numpy())
|
| 274 |
+
y_true.append(targets.cpu().numpy())
|
| 275 |
+
|
| 276 |
+
return np.concatenate(y_pred), np.concatenate(y_true) # [N, topk]
|
| 277 |
+
|
| 278 |
+
def _eval_nme(self, loader, class_means):
|
| 279 |
+
self._network.eval()
|
| 280 |
+
vectors, y_true = self._extract_vectors(loader)
|
| 281 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 282 |
+
|
| 283 |
+
dists = cdist(class_means, vectors, "sqeuclidean") # [nb_classes, N]
|
| 284 |
+
scores = dists.T # [N, nb_classes], choose the one with the smallest distance
|
| 285 |
+
|
| 286 |
+
return np.argsort(scores, axis=1)[:, : self.topk], y_true # [N, topk]
|
| 287 |
+
|
| 288 |
+
def _extract_vectors(self, loader):
|
| 289 |
+
self._network.eval()
|
| 290 |
+
vectors, targets = [], []
|
| 291 |
+
for _, _inputs, _targets in loader:
|
| 292 |
+
_targets = _targets.numpy()
|
| 293 |
+
if isinstance(self._network, nn.DataParallel):
|
| 294 |
+
_vectors = tensor2numpy(
|
| 295 |
+
self._network.module.extract_vector(_inputs.to(self._device))
|
| 296 |
+
)
|
| 297 |
+
else:
|
| 298 |
+
_vectors = tensor2numpy(
|
| 299 |
+
self._network.extract_vector(_inputs.to(self._device))
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
vectors.append(_vectors)
|
| 303 |
+
targets.append(_targets)
|
| 304 |
+
|
| 305 |
+
return np.concatenate(vectors), np.concatenate(targets)
|
| 306 |
+
|
| 307 |
+
def _reduce_exemplar(self, data_manager, m):
|
| 308 |
+
logging.info("Reducing exemplars...({} per classes)".format(m))
|
| 309 |
+
dummy_data, dummy_targets = copy.deepcopy(self._data_memory), copy.deepcopy(
|
| 310 |
+
self._targets_memory
|
| 311 |
+
)
|
| 312 |
+
self._class_means = np.zeros((self._total_classes, self.feature_dim))
|
| 313 |
+
self._data_memory, self._targets_memory = np.array([]), np.array([])
|
| 314 |
+
|
| 315 |
+
for class_idx in range(self._known_classes):
|
| 316 |
+
mask = np.where(dummy_targets == class_idx)[0]
|
| 317 |
+
dd, dt = dummy_data[mask][:m], dummy_targets[mask][:m]
|
| 318 |
+
self._data_memory = (
|
| 319 |
+
np.concatenate((self._data_memory, dd))
|
| 320 |
+
if len(self._data_memory) != 0
|
| 321 |
+
else dd
|
| 322 |
+
)
|
| 323 |
+
self._targets_memory = (
|
| 324 |
+
np.concatenate((self._targets_memory, dt))
|
| 325 |
+
if len(self._targets_memory) != 0
|
| 326 |
+
else dt
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
# Exemplar mean
|
| 330 |
+
idx_dataset = data_manager.get_dataset(
|
| 331 |
+
[], source="train", mode="test", appendent=(dd, dt)
|
| 332 |
+
)
|
| 333 |
+
idx_loader = DataLoader(
|
| 334 |
+
idx_dataset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 335 |
+
)
|
| 336 |
+
vectors, _ = self._extract_vectors(idx_loader)
|
| 337 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 338 |
+
mean = np.mean(vectors, axis=0)
|
| 339 |
+
mean = mean / np.linalg.norm(mean)
|
| 340 |
+
|
| 341 |
+
self._class_means[class_idx, :] = mean
|
| 342 |
+
|
| 343 |
+
def _construct_exemplar(self, data_manager, m):
|
| 344 |
+
logging.info("Constructing exemplars...({} per classes)".format(m))
|
| 345 |
+
for class_idx in range(self._known_classes, self._total_classes):
|
| 346 |
+
data, targets, idx_dataset = data_manager.get_dataset(
|
| 347 |
+
np.arange(class_idx, class_idx + 1),
|
| 348 |
+
source="train",
|
| 349 |
+
mode="test",
|
| 350 |
+
ret_data=True,
|
| 351 |
+
)
|
| 352 |
+
idx_loader = DataLoader(
|
| 353 |
+
idx_dataset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 354 |
+
)
|
| 355 |
+
vectors, _ = self._extract_vectors(idx_loader)
|
| 356 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 357 |
+
class_mean = np.mean(vectors, axis=0)
|
| 358 |
+
|
| 359 |
+
# Select
|
| 360 |
+
selected_exemplars = []
|
| 361 |
+
exemplar_vectors = [] # [n, feature_dim]
|
| 362 |
+
for k in range(1, m + 1):
|
| 363 |
+
S = np.sum(
|
| 364 |
+
exemplar_vectors, axis=0
|
| 365 |
+
) # [feature_dim] sum of selected exemplars vectors
|
| 366 |
+
mu_p = (vectors + S) / k # [n, feature_dim] sum to all vectors
|
| 367 |
+
i = np.argmin(np.sqrt(np.sum((class_mean - mu_p) ** 2, axis=1)))
|
| 368 |
+
selected_exemplars.append(
|
| 369 |
+
np.array(data[i])
|
| 370 |
+
) # New object to avoid passing by inference
|
| 371 |
+
exemplar_vectors.append(
|
| 372 |
+
np.array(vectors[i])
|
| 373 |
+
) # New object to avoid passing by inference
|
| 374 |
+
|
| 375 |
+
vectors = np.delete(
|
| 376 |
+
vectors, i, axis=0
|
| 377 |
+
) # Remove it to avoid duplicative selection
|
| 378 |
+
data = np.delete(
|
| 379 |
+
data, i, axis=0
|
| 380 |
+
) # Remove it to avoid duplicative selection
|
| 381 |
+
|
| 382 |
+
# uniques = np.unique(selected_exemplars, axis=0)
|
| 383 |
+
# print('Unique elements: {}'.format(len(uniques)))
|
| 384 |
+
selected_exemplars = np.array(selected_exemplars)
|
| 385 |
+
exemplar_targets = np.full(m, class_idx)
|
| 386 |
+
self._data_memory = (
|
| 387 |
+
np.concatenate((self._data_memory, selected_exemplars))
|
| 388 |
+
if len(self._data_memory) != 0
|
| 389 |
+
else selected_exemplars
|
| 390 |
+
)
|
| 391 |
+
self._targets_memory = (
|
| 392 |
+
np.concatenate((self._targets_memory, exemplar_targets))
|
| 393 |
+
if len(self._targets_memory) != 0
|
| 394 |
+
else exemplar_targets
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
# Exemplar mean
|
| 398 |
+
idx_dataset = data_manager.get_dataset(
|
| 399 |
+
[],
|
| 400 |
+
source="train",
|
| 401 |
+
mode="test",
|
| 402 |
+
appendent=(selected_exemplars, exemplar_targets),
|
| 403 |
+
)
|
| 404 |
+
idx_loader = DataLoader(
|
| 405 |
+
idx_dataset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 406 |
+
)
|
| 407 |
+
vectors, _ = self._extract_vectors(idx_loader)
|
| 408 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 409 |
+
mean = np.mean(vectors, axis=0)
|
| 410 |
+
mean = mean / np.linalg.norm(mean)
|
| 411 |
+
|
| 412 |
+
self._class_means[class_idx, :] = mean
|
| 413 |
+
|
| 414 |
+
def _construct_exemplar_unified(self, data_manager, m):
|
| 415 |
+
logging.info(
|
| 416 |
+
"Constructing exemplars for new classes...({} per classes)".format(m)
|
| 417 |
+
)
|
| 418 |
+
_class_means = np.zeros((self._total_classes, self.feature_dim))
|
| 419 |
+
|
| 420 |
+
# Calculate the means of old classes with newly trained network
|
| 421 |
+
for class_idx in range(self._known_classes):
|
| 422 |
+
mask = np.where(self._targets_memory == class_idx)[0]
|
| 423 |
+
class_data, class_targets = (
|
| 424 |
+
self._data_memory[mask],
|
| 425 |
+
self._targets_memory[mask],
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
class_dset = data_manager.get_dataset(
|
| 429 |
+
[], source="train", mode="test", appendent=(class_data, class_targets)
|
| 430 |
+
)
|
| 431 |
+
class_loader = DataLoader(
|
| 432 |
+
class_dset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 433 |
+
)
|
| 434 |
+
vectors, _ = self._extract_vectors(class_loader)
|
| 435 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 436 |
+
mean = np.mean(vectors, axis=0)
|
| 437 |
+
mean = mean / np.linalg.norm(mean)
|
| 438 |
+
|
| 439 |
+
_class_means[class_idx, :] = mean
|
| 440 |
+
|
| 441 |
+
# Construct exemplars for new classes and calculate the means
|
| 442 |
+
for class_idx in range(self._known_classes, self._total_classes):
|
| 443 |
+
data, targets, class_dset = data_manager.get_dataset(
|
| 444 |
+
np.arange(class_idx, class_idx + 1),
|
| 445 |
+
source="train",
|
| 446 |
+
mode="test",
|
| 447 |
+
ret_data=True,
|
| 448 |
+
)
|
| 449 |
+
class_loader = DataLoader(
|
| 450 |
+
class_dset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
vectors, _ = self._extract_vectors(class_loader)
|
| 454 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 455 |
+
class_mean = np.mean(vectors, axis=0)
|
| 456 |
+
|
| 457 |
+
# Select
|
| 458 |
+
selected_exemplars = []
|
| 459 |
+
exemplar_vectors = []
|
| 460 |
+
for k in range(1, m + 1):
|
| 461 |
+
S = np.sum(
|
| 462 |
+
exemplar_vectors, axis=0
|
| 463 |
+
) # [feature_dim] sum of selected exemplars vectors
|
| 464 |
+
mu_p = (vectors + S) / k # [n, feature_dim] sum to all vectors
|
| 465 |
+
i = np.argmin(np.sqrt(np.sum((class_mean - mu_p) ** 2, axis=1)))
|
| 466 |
+
|
| 467 |
+
selected_exemplars.append(
|
| 468 |
+
np.array(data[i])
|
| 469 |
+
) # New object to avoid passing by inference
|
| 470 |
+
exemplar_vectors.append(
|
| 471 |
+
np.array(vectors[i])
|
| 472 |
+
) # New object to avoid passing by inference
|
| 473 |
+
|
| 474 |
+
vectors = np.delete(
|
| 475 |
+
vectors, i, axis=0
|
| 476 |
+
) # Remove it to avoid duplicative selection
|
| 477 |
+
data = np.delete(
|
| 478 |
+
data, i, axis=0
|
| 479 |
+
) # Remove it to avoid duplicative selection
|
| 480 |
+
|
| 481 |
+
selected_exemplars = np.array(selected_exemplars)
|
| 482 |
+
exemplar_targets = np.full(m, class_idx)
|
| 483 |
+
self._data_memory = (
|
| 484 |
+
np.concatenate((self._data_memory, selected_exemplars))
|
| 485 |
+
if len(self._data_memory) != 0
|
| 486 |
+
else selected_exemplars
|
| 487 |
+
)
|
| 488 |
+
self._targets_memory = (
|
| 489 |
+
np.concatenate((self._targets_memory, exemplar_targets))
|
| 490 |
+
if len(self._targets_memory) != 0
|
| 491 |
+
else exemplar_targets
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
# Exemplar mean
|
| 495 |
+
exemplar_dset = data_manager.get_dataset(
|
| 496 |
+
[],
|
| 497 |
+
source="train",
|
| 498 |
+
mode="test",
|
| 499 |
+
appendent=(selected_exemplars, exemplar_targets),
|
| 500 |
+
)
|
| 501 |
+
exemplar_loader = DataLoader(
|
| 502 |
+
exemplar_dset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 503 |
+
)
|
| 504 |
+
vectors, _ = self._extract_vectors(exemplar_loader)
|
| 505 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 506 |
+
mean = np.mean(vectors, axis=0)
|
| 507 |
+
mean = mean / np.linalg.norm(mean)
|
| 508 |
+
|
| 509 |
+
_class_means[class_idx, :] = mean
|
| 510 |
+
|
| 511 |
+
self._class_means = _class_means
|
models/blcl.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
import copy
|
| 7 |
+
from torch import optim
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
from torch.utils.data import DataLoader
|
| 10 |
+
from models.base import BaseLearner
|
| 11 |
+
from utils.inc_net import AdaptiveNet
|
| 12 |
+
from utils.toolkit import count_parameters, target2onehot, tensor2numpy
|
| 13 |
+
from utils.contrastive_loss import DMLLossCosine, DMLLossCosine
|
| 14 |
+
from utils.bayesian_weighting import AutomaticWeightedLoss
|
| 15 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 16 |
+
|
| 17 |
+
num_workers=2
|
| 18 |
+
EPSILON = 1e-8
|
| 19 |
+
batch_size = 64
|
| 20 |
+
|
| 21 |
+
class BLCL(BaseLearner):
|
| 22 |
+
"""
|
| 23 |
+
BLCL: Continual Learning class implementing incremental learning with contrastive and cross-entropy lossusing uncertaintiy-based weighting of the losses.
|
| 24 |
+
It handles sequential training on new tasks, while preserving knowledge from previously learned classes.
|
| 25 |
+
"""
|
| 26 |
+
def __init__(self, args):
|
| 27 |
+
super().__init__(args)
|
| 28 |
+
self.args = args
|
| 29 |
+
self._old_base = None
|
| 30 |
+
self.args.update({'curr': self._cur_task})
|
| 31 |
+
self._network = AdaptiveNet(args, True)
|
| 32 |
+
logging.info(f'>>> train generalized blocks:{self.args["train_base"]} train_adaptive:{self.args["train_adaptive"]}')
|
| 33 |
+
self.writer = SummaryWriter(log_dir='runs/{}'.format(args['summary_file']))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def after_task(self):
|
| 37 |
+
"""
|
| 38 |
+
Update known classes after finishing a task.
|
| 39 |
+
Handle freezing or training of generalized blocks based on the task configuration.
|
| 40 |
+
"""
|
| 41 |
+
self._known_classes = self._total_classes
|
| 42 |
+
if self._cur_task == 0:
|
| 43 |
+
if self.args['train_base']:
|
| 44 |
+
logging.info("Train Generalized Blocks...")
|
| 45 |
+
self._network.TaskAgnosticExtractor.train()
|
| 46 |
+
for param in self._network.TaskAgnosticExtractor.parameters():
|
| 47 |
+
param.requires_grad = True
|
| 48 |
+
else:
|
| 49 |
+
logging.info("Fix Generalized Blocks...")
|
| 50 |
+
self._network.TaskAgnosticExtractor.eval()
|
| 51 |
+
for param in self._network.TaskAgnosticExtractor.parameters():
|
| 52 |
+
param.requires_grad = False
|
| 53 |
+
|
| 54 |
+
logging.info('Exemplar size: {}'.format(self.exemplar_size))
|
| 55 |
+
|
| 56 |
+
def incremental_train(self, data_manager):
|
| 57 |
+
"""
|
| 58 |
+
Perform incremental training for the current task. This method updates the model to learn new classes
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
data_manager (DataManager): Manages datasets and provides task-specific data.
|
| 62 |
+
"""
|
| 63 |
+
self._cur_task += 1
|
| 64 |
+
self._total_classes = self._known_classes + data_manager.get_task_size(self._cur_task)
|
| 65 |
+
|
| 66 |
+
# Update arguments with the current task number.
|
| 67 |
+
self.args.update({'curr': self._cur_task})
|
| 68 |
+
|
| 69 |
+
# Update the model's fully connected layer to accommodate new classes.
|
| 70 |
+
self._network.update_fc(self._total_classes)
|
| 71 |
+
logging.info("****MODEL ARCHITECTURE after fc update*****")
|
| 72 |
+
logging.info(self._network)
|
| 73 |
+
logging.info('Learning on {}-{}'.format(self._known_classes, self._total_classes))
|
| 74 |
+
logging.info(
|
| 75 |
+
"Known_classes: {}\tTotal_classes: {}\tcurrent_task: {}".format(self._known_classes, self._total_classes, self._cur_task)
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
if self._cur_task>0: # Freeze the network of the previous trained adaptive network (requires grad = False)
|
| 79 |
+
logging.info("self._curr_task {} and no of adaptiveExtractors {}".format(self._cur_task, len(self._network.AdaptiveExtractors)))
|
| 80 |
+
for i in range(self._cur_task):
|
| 81 |
+
for p in self._network.AdaptiveExtractors[i].parameters():
|
| 82 |
+
if self.args['train_adaptive']:
|
| 83 |
+
p.requires_grad = True
|
| 84 |
+
else:
|
| 85 |
+
p.requires_grad = False
|
| 86 |
+
|
| 87 |
+
if self.args["type"] == "avg":
|
| 88 |
+
break
|
| 89 |
+
|
| 90 |
+
logging.debug('All params: {}'.format(count_parameters(self._network)))
|
| 91 |
+
logging.debug('Trainable params: {}'.format(count_parameters(self._network, True)))
|
| 92 |
+
|
| 93 |
+
# Get the training dataset, including any rehearsal memory (previously stored samples).
|
| 94 |
+
_, tr_targets, train_dataset = data_manager.get_dataset(
|
| 95 |
+
np.arange(self._known_classes, self._total_classes),
|
| 96 |
+
source='train',
|
| 97 |
+
mode='train',
|
| 98 |
+
appendent=self._get_memory(),
|
| 99 |
+
ret_data=True
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
self.train_loader = DataLoader(
|
| 103 |
+
train_dataset,
|
| 104 |
+
num_workers=num_workers,
|
| 105 |
+
batch_size=self.args["batch_size"],
|
| 106 |
+
shuffle=True
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
_, te_targets, test_dataset = data_manager.get_dataset(
|
| 111 |
+
np.arange(0, self._total_classes),
|
| 112 |
+
source='test',
|
| 113 |
+
mode='test',
|
| 114 |
+
ret_data=True
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
self.test_loader = DataLoader(
|
| 118 |
+
test_dataset,
|
| 119 |
+
batch_size=self.args["batch_size"],
|
| 120 |
+
shuffle=False,
|
| 121 |
+
num_workers=num_workers
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
# Setup losses: Automatic weighting of cross-entropy loss and contrastive loss
|
| 125 |
+
self.contrastive_loss = DMLLossCosine()
|
| 126 |
+
self.awl = AutomaticWeightedLoss(2)
|
| 127 |
+
|
| 128 |
+
if len(self._multiple_gpus) > 1:
|
| 129 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 130 |
+
self._train(self.train_loader, self.test_loader)
|
| 131 |
+
self.build_rehearsal_memory(data_manager, self.samples_per_class)
|
| 132 |
+
if len(self._multiple_gpus) > 1:
|
| 133 |
+
self._network = self._network.module
|
| 134 |
+
|
| 135 |
+
def set_network(self):
|
| 136 |
+
if len(self._multiple_gpus) > 1:
|
| 137 |
+
self._network = self._network.module
|
| 138 |
+
self._network.train() #All status from eval to train
|
| 139 |
+
if self.args['train_base']:
|
| 140 |
+
self._network.TaskAgnosticExtractor.train()
|
| 141 |
+
else:
|
| 142 |
+
self._network.TaskAgnosticExtractor.eval()
|
| 143 |
+
|
| 144 |
+
# set adaptive extractor's status
|
| 145 |
+
self._network.AdaptiveExtractors[-1].train()
|
| 146 |
+
if self._cur_task >= 1:
|
| 147 |
+
for i in range(self._cur_task):
|
| 148 |
+
if self.args['train_adaptive']:
|
| 149 |
+
self._network.AdaptiveExtractors[i].train()
|
| 150 |
+
else:
|
| 151 |
+
self._network.AdaptiveExtractors[i].eval()
|
| 152 |
+
if self.args["type"] == "avg":
|
| 153 |
+
break
|
| 154 |
+
|
| 155 |
+
if len(self._multiple_gpus) > 1:
|
| 156 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 157 |
+
|
| 158 |
+
def _train(self, train_loader, test_loader):
|
| 159 |
+
self._network.to(self._device)
|
| 160 |
+
if self._cur_task==0:
|
| 161 |
+
logging.debug('## Initial Training ##')
|
| 162 |
+
optimizer = optim.SGD([{"params": filter(lambda p: p.requires_grad, self._network.parameters()),
|
| 163 |
+
"momentum": 0.9,
|
| 164 |
+
"lr": self.args["init_lr"],
|
| 165 |
+
"weight_decay": self.args["init_weight_decay"]},
|
| 166 |
+
{"params": self.awl.parameters(),
|
| 167 |
+
"weight_decay": 0,
|
| 168 |
+
"lr": self.args["init_lr"]}])
|
| 169 |
+
if self.args['scheduler'] == 'steplr':
|
| 170 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 171 |
+
optimizer=optimizer,
|
| 172 |
+
milestones=self.args['init_milestones'],
|
| 173 |
+
gamma=self.args['init_lr_decay']
|
| 174 |
+
)
|
| 175 |
+
elif self.args['scheduler'] == 'cosine':
|
| 176 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(
|
| 177 |
+
optimizer=optimizer,
|
| 178 |
+
T_max=self.args['init_epoch']
|
| 179 |
+
)
|
| 180 |
+
else:
|
| 181 |
+
raise NotImplementedError
|
| 182 |
+
|
| 183 |
+
if not self.args['skip']:
|
| 184 |
+
self._init_train(train_loader, test_loader, optimizer, scheduler)
|
| 185 |
+
else:
|
| 186 |
+
if isinstance(self._network, nn.DataParallel):
|
| 187 |
+
self._network = self._network.module
|
| 188 |
+
load_acc = self._network.load_checkpoint(self.args)
|
| 189 |
+
self._network.to(self._device)
|
| 190 |
+
|
| 191 |
+
if len(self._multiple_gpus) > 1:
|
| 192 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 193 |
+
|
| 194 |
+
cur_test_acc = self._compute_accuracy(self._network, self.test_loader)
|
| 195 |
+
logging.info(f"Loaded_Test_Acc:{load_acc} Cur_Test_Acc:{cur_test_acc}")
|
| 196 |
+
else:
|
| 197 |
+
optimizer = optim.SGD([{"params": filter(lambda p: p.requires_grad, self._network.parameters()),
|
| 198 |
+
"momentum": 0.9,
|
| 199 |
+
"lr": self.args["lrate"],
|
| 200 |
+
"weight_decay": self.args["weight_decay"]},
|
| 201 |
+
{"params": self.awl.parameters(),
|
| 202 |
+
"weight_decay": 0,
|
| 203 |
+
"lr": self.args["lrate"]}])
|
| 204 |
+
if self.args['scheduler'] == 'steplr':
|
| 205 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 206 |
+
optimizer=optimizer,
|
| 207 |
+
milestones=self.args['milestones'],
|
| 208 |
+
gamma=self.args['lrate_decay']
|
| 209 |
+
)
|
| 210 |
+
elif self.args['scheduler'] == 'cosine':
|
| 211 |
+
assert self.args['t_max'] is not None
|
| 212 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(
|
| 213 |
+
optimizer=optimizer,
|
| 214 |
+
T_max=self.args['t_max']
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
raise NotImplementedError
|
| 218 |
+
self._update_representation(train_loader, test_loader, optimizer, scheduler)
|
| 219 |
+
if len(self._multiple_gpus) > 1:
|
| 220 |
+
self._network.module.weight_align(self._total_classes-self._known_classes)
|
| 221 |
+
else:
|
| 222 |
+
self._network.weight_align(self._total_classes-self._known_classes)
|
| 223 |
+
|
| 224 |
+
self.writer.add_figure("Confusion matrix",
|
| 225 |
+
self._createConfusionMatrix(self._network, self.test_loader),
|
| 226 |
+
self._cur_task)
|
| 227 |
+
self.writer.add_scalar('Accuracies', self.curr_acc, self._cur_task)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _test_model(self, test_loader, epoch):
|
| 231 |
+
self._network.eval()
|
| 232 |
+
self.awl.eval()
|
| 233 |
+
losses = 0.
|
| 234 |
+
losses_clf = 0.
|
| 235 |
+
|
| 236 |
+
for i, (_, inputs, targets) in enumerate(test_loader):
|
| 237 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 238 |
+
outputs = self._network(inputs)
|
| 239 |
+
logits =outputs["logits"]
|
| 240 |
+
|
| 241 |
+
loss_clf = F.cross_entropy(logits, targets)
|
| 242 |
+
loss = loss_clf
|
| 243 |
+
losses += loss.item()
|
| 244 |
+
losses_clf += loss_clf.item()
|
| 245 |
+
|
| 246 |
+
self.writer.add_scalar('Task: {} on {}-{} -- test/classification_loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 247 |
+
losses_clf / len(test_loader), epoch)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _init_train(self,train_loader, test_loader, optimizer, scheduler):
|
| 251 |
+
prog_bar = tqdm(range(self.args["init_epoch"]))
|
| 252 |
+
for _, epoch in enumerate(prog_bar):
|
| 253 |
+
self._network.train()
|
| 254 |
+
losses = 0.
|
| 255 |
+
losses_clf = 0.
|
| 256 |
+
losses_contrast = 0.
|
| 257 |
+
correct, total = 0, 0
|
| 258 |
+
|
| 259 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 260 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 261 |
+
|
| 262 |
+
outputs = self._network(inputs)
|
| 263 |
+
logits, embeddings =outputs["logits"], outputs["features"]
|
| 264 |
+
|
| 265 |
+
loss_clf = F.cross_entropy(logits,targets)
|
| 266 |
+
c_loss = self.contrastive_loss(embeddings, targets)
|
| 267 |
+
loss = self.awl(loss_clf, c_loss)
|
| 268 |
+
optimizer.zero_grad()
|
| 269 |
+
loss.backward()
|
| 270 |
+
optimizer.step()
|
| 271 |
+
losses += loss.item()
|
| 272 |
+
losses_clf+=loss_clf.item()
|
| 273 |
+
losses_contrast+=c_loss.item()
|
| 274 |
+
|
| 275 |
+
_, preds = torch.max(logits, dim=1)
|
| 276 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 277 |
+
total += len(targets)
|
| 278 |
+
|
| 279 |
+
params = list(next(self.awl.parameters()))
|
| 280 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/contrastive_loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 281 |
+
losses_contrast / len(train_loader), epoch)
|
| 282 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/classification_loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 283 |
+
losses_clf / len(train_loader), epoch)
|
| 284 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/Total_loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 285 |
+
losses / len(train_loader), epoch)
|
| 286 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/clf_weight'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 287 |
+
params[0], epoch)
|
| 288 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/contrastive_weight'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 289 |
+
params[1], epoch)
|
| 290 |
+
|
| 291 |
+
scheduler.step()
|
| 292 |
+
train_acc = np.around(tensor2numpy(correct)*100 / total, decimals=2)
|
| 293 |
+
if epoch%5==0:
|
| 294 |
+
self._test_model(test_loader=self.test_loader, epoch=epoch)
|
| 295 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 296 |
+
info = 'Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}'.format(
|
| 297 |
+
self._cur_task, epoch+1, self.args['init_epoch'], losses/len(train_loader), train_acc, test_acc)
|
| 298 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy train'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 299 |
+
train_acc, epoch)
|
| 300 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy test'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 301 |
+
test_acc, epoch)
|
| 302 |
+
else:
|
| 303 |
+
info = 'Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}'.format(
|
| 304 |
+
self._cur_task,
|
| 305 |
+
epoch + 1,
|
| 306 |
+
self.args['init_epoch'],
|
| 307 |
+
losses/len(train_loader),
|
| 308 |
+
train_acc)
|
| 309 |
+
prog_bar.set_description(info)
|
| 310 |
+
logging.info(info)
|
| 311 |
+
|
| 312 |
+
def _update_representation(self, train_loader, test_loader, optimizer, scheduler):
|
| 313 |
+
prog_bar = tqdm(range(self.args["epochs"]))
|
| 314 |
+
for _, epoch in enumerate(prog_bar):
|
| 315 |
+
self.set_network()
|
| 316 |
+
losses = 0.
|
| 317 |
+
losses_clf=0.
|
| 318 |
+
losses_contrast=0.
|
| 319 |
+
losses_aux=0.
|
| 320 |
+
correct, total = 0, 0
|
| 321 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 322 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 323 |
+
|
| 324 |
+
outputs = self._network(inputs)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
logits, aux_logits, embeddings=outputs["logits"],outputs["aux_logits"],outputs["features"]
|
| 328 |
+
|
| 329 |
+
loss_clf=F.cross_entropy(logits,targets)
|
| 330 |
+
c_loss = self.contrastive_loss(embeddings,targets)
|
| 331 |
+
aux_targets = targets.clone()
|
| 332 |
+
aux_targets=torch.where(aux_targets-self._known_classes+1>0, aux_targets-self._known_classes+1,0)
|
| 333 |
+
loss_aux=F.cross_entropy(aux_logits,aux_targets)
|
| 334 |
+
loss= self.awl(loss_clf, c_loss) + self.args['alpha_aux']*loss_aux
|
| 335 |
+
optimizer.zero_grad()
|
| 336 |
+
loss.backward()
|
| 337 |
+
optimizer.step()
|
| 338 |
+
losses += loss.item()
|
| 339 |
+
losses_aux+=loss_aux.item()
|
| 340 |
+
losses_clf+=loss_clf.item()
|
| 341 |
+
losses_contrast+=c_loss.item()
|
| 342 |
+
|
| 343 |
+
_, preds = torch.max(logits, dim=1)
|
| 344 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 345 |
+
total += len(targets)
|
| 346 |
+
|
| 347 |
+
params = list(next(self.awl.parameters()))
|
| 348 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/contrastive_loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 349 |
+
losses_contrast / len(train_loader), epoch)
|
| 350 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/classification_loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 351 |
+
losses_clf / len(train_loader), epoch)
|
| 352 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/Total_loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 353 |
+
losses / len(train_loader), epoch)
|
| 354 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/clf_weight'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 355 |
+
params[0], epoch)
|
| 356 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/contrastive_weight'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 357 |
+
params[1], epoch)
|
| 358 |
+
scheduler.step()
|
| 359 |
+
train_acc = np.around(tensor2numpy(correct)*100 / total, decimals=2)
|
| 360 |
+
if epoch % 5 == 0:
|
| 361 |
+
self._test_model(test_loader=self.test_loader, epoch=epoch)
|
| 362 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 363 |
+
info = 'Task {}, Epoch {}/{} => Loss {:.3f}, Loss_clf {:.3f}, Loss_aux {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}'.format(
|
| 364 |
+
self._cur_task, epoch+1, self.args["epochs"], losses/len(train_loader),losses_clf/len(train_loader),losses_aux/len(train_loader),train_acc, test_acc)
|
| 365 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy train'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 366 |
+
train_acc, epoch)
|
| 367 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy test'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 368 |
+
test_acc, epoch)
|
| 369 |
+
else:
|
| 370 |
+
info = 'Task {}, Epoch {}/{} => Loss {:.3f}, Loss_clf {:.3f}, Loss_aux {:.3f}, Train_accy {:.2f}'.format(
|
| 371 |
+
self._cur_task,
|
| 372 |
+
epoch + 1,
|
| 373 |
+
self.args["epochs"],
|
| 374 |
+
losses/len(train_loader),
|
| 375 |
+
losses_clf/len(train_loader),
|
| 376 |
+
losses_aux/len(train_loader),
|
| 377 |
+
train_acc)
|
| 378 |
+
|
| 379 |
+
prog_bar.set_description(info)
|
| 380 |
+
logging.info(info)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _construct_exemplar(self, data_manager, m):
|
| 384 |
+
logging.info("Constructing exemplars...({} per classes)".format(m))
|
| 385 |
+
for class_idx in range(self._known_classes, self._total_classes):
|
| 386 |
+
data, targets, idx_dataset = data_manager.get_dataset(
|
| 387 |
+
np.arange(class_idx, class_idx + 1),
|
| 388 |
+
source="train",
|
| 389 |
+
mode="test",
|
| 390 |
+
ret_data=True,
|
| 391 |
+
)
|
| 392 |
+
idx_loader = DataLoader(
|
| 393 |
+
idx_dataset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 394 |
+
)
|
| 395 |
+
vectors, _ = self._extract_vectors(idx_loader)
|
| 396 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 397 |
+
class_mean = np.mean(vectors, axis=0)
|
| 398 |
+
|
| 399 |
+
# Select
|
| 400 |
+
selected_exemplars = []
|
| 401 |
+
exemplar_vectors = [] # [n, feature_dim]
|
| 402 |
+
for k in range(1, m + 1):
|
| 403 |
+
S = np.sum(
|
| 404 |
+
exemplar_vectors, axis=0
|
| 405 |
+
) # [feature_dim] sum of selected exemplars vectors
|
| 406 |
+
mu_p = (vectors + S) / k # [n, feature_dim] sum to all vectors
|
| 407 |
+
i = np.argmin(np.sqrt(np.sum((class_mean - mu_p) ** 2, axis=1)))
|
| 408 |
+
selected_exemplars.append(
|
| 409 |
+
np.array(data[i])
|
| 410 |
+
) # New object to avoid passing by inference
|
| 411 |
+
exemplar_vectors.append(
|
| 412 |
+
np.array(vectors[i])
|
| 413 |
+
) # New object to avoid passing by inference
|
| 414 |
+
|
| 415 |
+
vectors = np.delete(
|
| 416 |
+
vectors, i, axis=0
|
| 417 |
+
) # Remove it to avoid duplicative selection
|
| 418 |
+
data = np.delete(
|
| 419 |
+
data, i, axis=0
|
| 420 |
+
) # Remove it to avoid duplicative selection
|
| 421 |
+
|
| 422 |
+
if len(vectors) == 0:
|
| 423 |
+
break
|
| 424 |
+
# uniques = np.unique(selected_exemplars, axis=0)
|
| 425 |
+
# print('Unique elements: {}'.format(len(uniques)))
|
| 426 |
+
selected_exemplars = np.array(selected_exemplars)
|
| 427 |
+
# exemplar_targets = np.full(m, class_idx)
|
| 428 |
+
exemplar_targets = np.full(selected_exemplars.shape[0], class_idx)
|
| 429 |
+
self._data_memory = (
|
| 430 |
+
np.concatenate((self._data_memory, selected_exemplars))
|
| 431 |
+
if len(self._data_memory) != 0
|
| 432 |
+
else selected_exemplars
|
| 433 |
+
)
|
| 434 |
+
self._targets_memory = (
|
| 435 |
+
np.concatenate((self._targets_memory, exemplar_targets))
|
| 436 |
+
if len(self._targets_memory) != 0
|
| 437 |
+
else exemplar_targets
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
# Exemplar mean
|
| 441 |
+
idx_dataset = data_manager.get_dataset(
|
| 442 |
+
[],
|
| 443 |
+
source="train",
|
| 444 |
+
mode="test",
|
| 445 |
+
appendent=(selected_exemplars, exemplar_targets),
|
| 446 |
+
)
|
| 447 |
+
idx_loader = DataLoader(
|
| 448 |
+
idx_dataset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 449 |
+
)
|
| 450 |
+
vectors, _ = self._extract_vectors(idx_loader)
|
| 451 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 452 |
+
mean = np.mean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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Please note that the current implementation of DER only contains the dynamic expansion process, since masking and pruning are not implemented by the source repo.
|
| 2 |
+
import logging
|
| 3 |
+
import numpy as np
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch import optim
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
from torch.utils.data import DataLoader
|
| 10 |
+
from models.base import BaseLearner
|
| 11 |
+
from utils.inc_net import DERNet, IncrementalNet
|
| 12 |
+
from utils.toolkit import count_parameters, target2onehot, tensor2numpy
|
| 13 |
+
|
| 14 |
+
EPSILON = 1e-8
|
| 15 |
+
|
| 16 |
+
init_epoch = 200
|
| 17 |
+
init_lr = 0.1
|
| 18 |
+
init_milestones = [60, 120, 170]
|
| 19 |
+
init_lr_decay = 0.1
|
| 20 |
+
init_weight_decay = 0.0005
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
epochs = 170
|
| 24 |
+
lrate = 0.1
|
| 25 |
+
milestones = [80, 120, 150]
|
| 26 |
+
lrate_decay = 0.1
|
| 27 |
+
batch_size = 128
|
| 28 |
+
weight_decay = 2e-4
|
| 29 |
+
num_workers = 8
|
| 30 |
+
T = 2
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class DER(BaseLearner):
|
| 34 |
+
def __init__(self, args):
|
| 35 |
+
super().__init__(args)
|
| 36 |
+
self._network = DERNet(args, False)
|
| 37 |
+
|
| 38 |
+
def after_task(self):
|
| 39 |
+
self._known_classes = self._total_classes
|
| 40 |
+
logging.info("Exemplar size: {}".format(self.exemplar_size))
|
| 41 |
+
|
| 42 |
+
def incremental_train(self, data_manager):
|
| 43 |
+
self._cur_task += 1
|
| 44 |
+
self._total_classes = self._known_classes + data_manager.get_task_size(
|
| 45 |
+
self._cur_task
|
| 46 |
+
)
|
| 47 |
+
self._network.update_fc(self._total_classes)
|
| 48 |
+
logging.info(
|
| 49 |
+
"Learning on {}-{}".format(self._known_classes, self._total_classes)
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
if self._cur_task > 0:
|
| 53 |
+
for i in range(self._cur_task):
|
| 54 |
+
for p in self._network.convnets[i].parameters():
|
| 55 |
+
p.requires_grad = False
|
| 56 |
+
|
| 57 |
+
logging.info("All params: {}".format(count_parameters(self._network)))
|
| 58 |
+
logging.info(
|
| 59 |
+
"Trainable params: {}".format(count_parameters(self._network, True))
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
train_dataset = data_manager.get_dataset(
|
| 63 |
+
np.arange(self._known_classes, self._total_classes),
|
| 64 |
+
source="train",
|
| 65 |
+
mode="train",
|
| 66 |
+
appendent=self._get_memory(),
|
| 67 |
+
)
|
| 68 |
+
self.train_loader = DataLoader(
|
| 69 |
+
train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers
|
| 70 |
+
)
|
| 71 |
+
test_dataset = data_manager.get_dataset(
|
| 72 |
+
np.arange(0, self._total_classes), source="test", mode="test"
|
| 73 |
+
)
|
| 74 |
+
self.test_loader = DataLoader(
|
| 75 |
+
test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
if len(self._multiple_gpus) > 1:
|
| 79 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 80 |
+
self._train(self.train_loader, self.test_loader)
|
| 81 |
+
self.build_rehearsal_memory(data_manager, self.samples_per_class)
|
| 82 |
+
if len(self._multiple_gpus) > 1:
|
| 83 |
+
self._network = self._network.module
|
| 84 |
+
|
| 85 |
+
def train(self):
|
| 86 |
+
self._network.train()
|
| 87 |
+
if len(self._multiple_gpus) > 1 :
|
| 88 |
+
self._network_module_ptr = self._network.module
|
| 89 |
+
else:
|
| 90 |
+
self._network_module_ptr = self._network
|
| 91 |
+
self._network_module_ptr.convnets[-1].train()
|
| 92 |
+
if self._cur_task >= 1:
|
| 93 |
+
for i in range(self._cur_task):
|
| 94 |
+
self._network_module_ptr.convnets[i].eval()
|
| 95 |
+
|
| 96 |
+
def _train(self, train_loader, test_loader):
|
| 97 |
+
self._network.to(self._device)
|
| 98 |
+
if self._cur_task == 0:
|
| 99 |
+
optimizer = optim.SGD(
|
| 100 |
+
filter(lambda p: p.requires_grad, self._network.parameters()),
|
| 101 |
+
momentum=0.9,
|
| 102 |
+
lr=init_lr,
|
| 103 |
+
weight_decay=init_weight_decay,
|
| 104 |
+
)
|
| 105 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 106 |
+
optimizer=optimizer, milestones=init_milestones, gamma=init_lr_decay
|
| 107 |
+
)
|
| 108 |
+
self._init_train(train_loader, test_loader, optimizer, scheduler)
|
| 109 |
+
else:
|
| 110 |
+
optimizer = optim.SGD(
|
| 111 |
+
filter(lambda p: p.requires_grad, self._network.parameters()),
|
| 112 |
+
lr=lrate,
|
| 113 |
+
momentum=0.9,
|
| 114 |
+
weight_decay=weight_decay,
|
| 115 |
+
)
|
| 116 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 117 |
+
optimizer=optimizer, milestones=milestones, gamma=lrate_decay
|
| 118 |
+
)
|
| 119 |
+
self._update_representation(train_loader, test_loader, optimizer, scheduler)
|
| 120 |
+
if len(self._multiple_gpus) > 1:
|
| 121 |
+
self._network.module.weight_align(
|
| 122 |
+
self._total_classes - self._known_classes
|
| 123 |
+
)
|
| 124 |
+
else:
|
| 125 |
+
self._network.weight_align(self._total_classes - self._known_classes)
|
| 126 |
+
|
| 127 |
+
def _init_train(self, train_loader, test_loader, optimizer, scheduler):
|
| 128 |
+
prog_bar = tqdm(range(init_epoch))
|
| 129 |
+
for _, epoch in enumerate(prog_bar):
|
| 130 |
+
self.train()
|
| 131 |
+
losses = 0.0
|
| 132 |
+
correct, total = 0, 0
|
| 133 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 134 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 135 |
+
logits = self._network(inputs)["logits"]
|
| 136 |
+
|
| 137 |
+
loss = F.cross_entropy(logits, targets)
|
| 138 |
+
optimizer.zero_grad()
|
| 139 |
+
loss.backward()
|
| 140 |
+
optimizer.step()
|
| 141 |
+
losses += loss.item()
|
| 142 |
+
|
| 143 |
+
_, preds = torch.max(logits, dim=1)
|
| 144 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 145 |
+
total += len(targets)
|
| 146 |
+
|
| 147 |
+
scheduler.step()
|
| 148 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 149 |
+
|
| 150 |
+
if epoch % 5 == 0:
|
| 151 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 152 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 153 |
+
self._cur_task,
|
| 154 |
+
epoch + 1,
|
| 155 |
+
init_epoch,
|
| 156 |
+
losses / len(train_loader),
|
| 157 |
+
train_acc,
|
| 158 |
+
test_acc,
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 162 |
+
self._cur_task,
|
| 163 |
+
epoch + 1,
|
| 164 |
+
init_epoch,
|
| 165 |
+
losses / len(train_loader),
|
| 166 |
+
train_acc,
|
| 167 |
+
)
|
| 168 |
+
prog_bar.set_description(info)
|
| 169 |
+
|
| 170 |
+
logging.info(info)
|
| 171 |
+
|
| 172 |
+
def _update_representation(self, train_loader, test_loader, optimizer, scheduler):
|
| 173 |
+
prog_bar = tqdm(range(epochs))
|
| 174 |
+
for _, epoch in enumerate(prog_bar):
|
| 175 |
+
self.train()
|
| 176 |
+
losses = 0.0
|
| 177 |
+
losses_clf = 0.0
|
| 178 |
+
losses_aux = 0.0
|
| 179 |
+
correct, total = 0, 0
|
| 180 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 181 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 182 |
+
outputs = self._network(inputs)
|
| 183 |
+
logits, aux_logits = outputs["logits"], outputs["aux_logits"]
|
| 184 |
+
loss_clf = F.cross_entropy(logits, targets)
|
| 185 |
+
aux_targets = targets.clone()
|
| 186 |
+
aux_targets = torch.where(
|
| 187 |
+
aux_targets - self._known_classes + 1 > 0,
|
| 188 |
+
aux_targets - self._known_classes + 1,
|
| 189 |
+
0,
|
| 190 |
+
)
|
| 191 |
+
loss_aux = F.cross_entropy(aux_logits, aux_targets)
|
| 192 |
+
loss = loss_clf + loss_aux
|
| 193 |
+
|
| 194 |
+
optimizer.zero_grad()
|
| 195 |
+
loss.backward()
|
| 196 |
+
optimizer.step()
|
| 197 |
+
losses += loss.item()
|
| 198 |
+
losses_aux += loss_aux.item()
|
| 199 |
+
losses_clf += loss_clf.item()
|
| 200 |
+
|
| 201 |
+
_, preds = torch.max(logits, dim=1)
|
| 202 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 203 |
+
total += len(targets)
|
| 204 |
+
|
| 205 |
+
scheduler.step()
|
| 206 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 207 |
+
if epoch % 5 == 0:
|
| 208 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 209 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Loss_clf {:.3f}, Loss_aux {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 210 |
+
self._cur_task,
|
| 211 |
+
epoch + 1,
|
| 212 |
+
epochs,
|
| 213 |
+
losses / len(train_loader),
|
| 214 |
+
losses_clf / len(train_loader),
|
| 215 |
+
losses_aux / len(train_loader),
|
| 216 |
+
train_acc,
|
| 217 |
+
test_acc,
|
| 218 |
+
)
|
| 219 |
+
else:
|
| 220 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Loss_clf {:.3f}, Loss_aux {:.3f}, Train_accy {:.2f}".format(
|
| 221 |
+
self._cur_task,
|
| 222 |
+
epoch + 1,
|
| 223 |
+
epochs,
|
| 224 |
+
losses / len(train_loader),
|
| 225 |
+
losses_clf / len(train_loader),
|
| 226 |
+
losses_aux / len(train_loader),
|
| 227 |
+
train_acc,
|
| 228 |
+
)
|
| 229 |
+
prog_bar.set_description(info)
|
| 230 |
+
logging.info(info)
|
models/ewc.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch import optim
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
from torch.utils.data import DataLoader
|
| 9 |
+
from models.base import BaseLearner
|
| 10 |
+
from models.podnet import pod_spatial_loss
|
| 11 |
+
from utils.inc_net import IncrementalNet
|
| 12 |
+
from utils.toolkit import target2onehot, tensor2numpy
|
| 13 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
EPSILON = 1e-8
|
| 18 |
+
|
| 19 |
+
init_epoch = 200
|
| 20 |
+
init_lr = 0.1
|
| 21 |
+
init_milestones = [60, 120, 170]
|
| 22 |
+
init_lr_decay = 0.1
|
| 23 |
+
init_weight_decay = 0.0005
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
epochs = 200
|
| 27 |
+
lrate = 0.1
|
| 28 |
+
milestones = [70, 120, 150]
|
| 29 |
+
lrate_decay = 0.1
|
| 30 |
+
batch_size = 32
|
| 31 |
+
weight_decay = 2e-4
|
| 32 |
+
num_workers = 2
|
| 33 |
+
T = 2
|
| 34 |
+
lamda = 1000
|
| 35 |
+
fishermax = 0.0001
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class EWC(BaseLearner):
|
| 41 |
+
def __init__(self, args):
|
| 42 |
+
super().__init__(args)
|
| 43 |
+
self.fisher = None
|
| 44 |
+
self._network = IncrementalNet(args, True)
|
| 45 |
+
self.writer = SummaryWriter(log_dir='runs/{}'.format(args['summary_file']))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def after_task(self):
|
| 49 |
+
self._known_classes = self._total_classes
|
| 50 |
+
|
| 51 |
+
def incremental_train(self, data_manager):
|
| 52 |
+
self.curr_acc = 0
|
| 53 |
+
self._cur_task += 1
|
| 54 |
+
self._total_classes = self._known_classes + data_manager.get_task_size(
|
| 55 |
+
self._cur_task
|
| 56 |
+
)
|
| 57 |
+
self._network.update_fc(self._total_classes)
|
| 58 |
+
logging.info(
|
| 59 |
+
"Learning on {}-{}".format(self._known_classes, self._total_classes)
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
train_dataset = data_manager.get_dataset(
|
| 63 |
+
np.arange(self._known_classes, self._total_classes),
|
| 64 |
+
source="train",
|
| 65 |
+
mode="train",
|
| 66 |
+
)
|
| 67 |
+
self.train_loader = DataLoader(
|
| 68 |
+
train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers
|
| 69 |
+
)
|
| 70 |
+
test_dataset = data_manager.get_dataset(
|
| 71 |
+
np.arange(0, self._total_classes), source="test", mode="test"
|
| 72 |
+
)
|
| 73 |
+
self.test_loader = DataLoader(
|
| 74 |
+
test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
if len(self._multiple_gpus) > 1:
|
| 78 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 79 |
+
self._train(self.train_loader, self.test_loader)
|
| 80 |
+
if len(self._multiple_gpus) > 1:
|
| 81 |
+
self._network = self._network.module
|
| 82 |
+
|
| 83 |
+
if self.fisher is None:
|
| 84 |
+
self.fisher = self.getFisherDiagonal(self.train_loader)
|
| 85 |
+
else:
|
| 86 |
+
alpha = self._known_classes / self._total_classes
|
| 87 |
+
new_finsher = self.getFisherDiagonal(self.train_loader)
|
| 88 |
+
for n, p in new_finsher.items():
|
| 89 |
+
new_finsher[n][: len(self.fisher[n])] = (
|
| 90 |
+
alpha * self.fisher[n]
|
| 91 |
+
+ (1 - alpha) * new_finsher[n][: len(self.fisher[n])]
|
| 92 |
+
)
|
| 93 |
+
self.fisher = new_finsher
|
| 94 |
+
self.mean = {
|
| 95 |
+
n: p.clone().detach()
|
| 96 |
+
for n, p in self._network.named_parameters()
|
| 97 |
+
if p.requires_grad
|
| 98 |
+
}
|
| 99 |
+
if self._total_classes == data_manager.get_total_classnum():
|
| 100 |
+
self.writer.close()
|
| 101 |
+
|
| 102 |
+
def _train(self, train_loader, test_loader):
|
| 103 |
+
self._network.to(self._device)
|
| 104 |
+
if self._cur_task == 0:
|
| 105 |
+
optimizer = optim.SGD(
|
| 106 |
+
self._network.parameters(),
|
| 107 |
+
momentum=0.9,
|
| 108 |
+
lr=init_lr,
|
| 109 |
+
weight_decay=init_weight_decay,
|
| 110 |
+
)
|
| 111 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 112 |
+
optimizer=optimizer, milestones=init_milestones, gamma=init_lr_decay
|
| 113 |
+
)
|
| 114 |
+
self._init_train(train_loader, test_loader, optimizer, scheduler)
|
| 115 |
+
else:
|
| 116 |
+
optimizer = optim.SGD(
|
| 117 |
+
self._network.parameters(),
|
| 118 |
+
lr=lrate,
|
| 119 |
+
momentum=0.9,
|
| 120 |
+
weight_decay=weight_decay,
|
| 121 |
+
)
|
| 122 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 123 |
+
optimizer=optimizer, milestones=milestones, gamma=lrate_decay
|
| 124 |
+
)
|
| 125 |
+
self._update_representation(train_loader, test_loader, optimizer, scheduler)
|
| 126 |
+
|
| 127 |
+
self.writer.add_figure("Confusion matrix",
|
| 128 |
+
self._createConfusionMatrix(self._network, self.test_loader),
|
| 129 |
+
self._cur_task)
|
| 130 |
+
self.writer.add_scalar('Accuracies', self.curr_acc, self._cur_task)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _init_train(self, train_loader, test_loader, optimizer, scheduler):
|
| 134 |
+
prog_bar = tqdm(range(init_epoch))
|
| 135 |
+
for _, epoch in enumerate(prog_bar):
|
| 136 |
+
self._network.train()
|
| 137 |
+
losses = 0.0
|
| 138 |
+
correct, total = 0, 0
|
| 139 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 140 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 141 |
+
logits = self._network(inputs)["logits"]
|
| 142 |
+
loss = F.cross_entropy(logits, targets)
|
| 143 |
+
optimizer.zero_grad()
|
| 144 |
+
loss.backward()
|
| 145 |
+
optimizer.step()
|
| 146 |
+
losses += loss.item()
|
| 147 |
+
|
| 148 |
+
_, preds = torch.max(logits, dim=1)
|
| 149 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 150 |
+
total += len(targets)
|
| 151 |
+
|
| 152 |
+
scheduler.step()
|
| 153 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 154 |
+
|
| 155 |
+
if epoch % 5 == 0:
|
| 156 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 157 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 158 |
+
self._cur_task,
|
| 159 |
+
epoch + 1,
|
| 160 |
+
init_epoch,
|
| 161 |
+
losses / len(train_loader),
|
| 162 |
+
train_acc,
|
| 163 |
+
test_acc,
|
| 164 |
+
)
|
| 165 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 166 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 167 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 168 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 169 |
+
self._cur_task,
|
| 170 |
+
epoch + 1,
|
| 171 |
+
init_epoch,
|
| 172 |
+
losses / len(train_loader),
|
| 173 |
+
train_acc,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
prog_bar.set_description(info)
|
| 177 |
+
|
| 178 |
+
logging.info(info)
|
| 179 |
+
|
| 180 |
+
def _update_representation(self, train_loader, test_loader, optimizer, scheduler):
|
| 181 |
+
prog_bar = tqdm(range(epochs))
|
| 182 |
+
for _, epoch in enumerate(prog_bar):
|
| 183 |
+
self._network.train()
|
| 184 |
+
losses = 0.0
|
| 185 |
+
correct, total = 0, 0
|
| 186 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 187 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 188 |
+
logits = self._network(inputs)["logits"]
|
| 189 |
+
|
| 190 |
+
loss_clf = F.cross_entropy(
|
| 191 |
+
logits[:, self._known_classes :], targets - self._known_classes
|
| 192 |
+
)
|
| 193 |
+
loss_ewc = self.compute_ewc()
|
| 194 |
+
loss = loss_clf + lamda * loss_ewc
|
| 195 |
+
|
| 196 |
+
optimizer.zero_grad()
|
| 197 |
+
loss.backward()
|
| 198 |
+
optimizer.step()
|
| 199 |
+
losses += loss.item()
|
| 200 |
+
|
| 201 |
+
_, preds = torch.max(logits, dim=1)
|
| 202 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 203 |
+
total += len(targets)
|
| 204 |
+
|
| 205 |
+
scheduler.step()
|
| 206 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 207 |
+
if epoch % 5 == 0:
|
| 208 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 209 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 210 |
+
self._cur_task,
|
| 211 |
+
epoch + 1,
|
| 212 |
+
epochs,
|
| 213 |
+
losses / len(train_loader),
|
| 214 |
+
train_acc,
|
| 215 |
+
test_acc,
|
| 216 |
+
)
|
| 217 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 218 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 219 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 220 |
+
else:
|
| 221 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 222 |
+
self._cur_task,
|
| 223 |
+
epoch + 1,
|
| 224 |
+
epochs,
|
| 225 |
+
losses / len(train_loader),
|
| 226 |
+
train_acc,
|
| 227 |
+
)
|
| 228 |
+
prog_bar.set_description(info)
|
| 229 |
+
logging.info(info)
|
| 230 |
+
|
| 231 |
+
def compute_ewc(self):
|
| 232 |
+
loss = 0
|
| 233 |
+
if len(self._multiple_gpus) > 1:
|
| 234 |
+
for n, p in self._network.module.named_parameters():
|
| 235 |
+
if n in self.fisher.keys():
|
| 236 |
+
loss += (
|
| 237 |
+
torch.sum(
|
| 238 |
+
(self.fisher[n])
|
| 239 |
+
* (p[: len(self.mean[n])] - self.mean[n]).pow(2)
|
| 240 |
+
)
|
| 241 |
+
/ 2
|
| 242 |
+
)
|
| 243 |
+
else:
|
| 244 |
+
for n, p in self._network.named_parameters():
|
| 245 |
+
if n in self.fisher.keys():
|
| 246 |
+
loss += (
|
| 247 |
+
torch.sum(
|
| 248 |
+
(self.fisher[n])
|
| 249 |
+
* (p[: len(self.mean[n])] - self.mean[n]).pow(2)
|
| 250 |
+
)
|
| 251 |
+
/ 2
|
| 252 |
+
)
|
| 253 |
+
return loss
|
| 254 |
+
|
| 255 |
+
def getFisherDiagonal(self, train_loader):
|
| 256 |
+
fisher = {
|
| 257 |
+
n: torch.zeros(p.shape).to(self._device)
|
| 258 |
+
for n, p in self._network.named_parameters()
|
| 259 |
+
if p.requires_grad
|
| 260 |
+
}
|
| 261 |
+
self._network.train()
|
| 262 |
+
optimizer = optim.SGD(self._network.parameters(), lr=lrate)
|
| 263 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 264 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 265 |
+
logits = self._network(inputs)["logits"]
|
| 266 |
+
loss = torch.nn.functional.cross_entropy(logits, targets)
|
| 267 |
+
optimizer.zero_grad()
|
| 268 |
+
loss.backward()
|
| 269 |
+
for n, p in self._network.named_parameters():
|
| 270 |
+
if p.grad is not None:
|
| 271 |
+
fisher[n] += p.grad.pow(2).clone()
|
| 272 |
+
for n, p in fisher.items():
|
| 273 |
+
fisher[n] = p / len(train_loader)
|
| 274 |
+
fisher[n] = torch.min(fisher[n], torch.tensor(fishermax))
|
| 275 |
+
return fisher
|
models/finetune.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
from torch import optim
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
from torch.utils.data import DataLoader
|
| 10 |
+
from utils.inc_net import IncrementalNet
|
| 11 |
+
from models.base import BaseLearner
|
| 12 |
+
from utils.toolkit import target2onehot, tensor2numpy, count_parameters, count_parameters
|
| 13 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
init_epoch = 200
|
| 18 |
+
init_lr = 0.1
|
| 19 |
+
init_milestones = [60, 120, 170]
|
| 20 |
+
init_lr_decay = 0.1
|
| 21 |
+
init_weight_decay = 0.0005
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
epochs = 200
|
| 25 |
+
lrate = 0.1
|
| 26 |
+
milestones = [40, 70]
|
| 27 |
+
lrate_decay = 0.1
|
| 28 |
+
batch_size = 32
|
| 29 |
+
|
| 30 |
+
weight_decay = 2e-4
|
| 31 |
+
num_workers = 2
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Finetune(BaseLearner):
|
| 35 |
+
def __init__(self, args):
|
| 36 |
+
super().__init__(args)
|
| 37 |
+
self._network = IncrementalNet(args, True)
|
| 38 |
+
self.writer = SummaryWriter(log_dir='runs/{}'.format(args['summary_file']))
|
| 39 |
+
#self.train_mode = args['train']
|
| 40 |
+
|
| 41 |
+
def after_task(self):
|
| 42 |
+
self._known_classes = self._total_classes
|
| 43 |
+
|
| 44 |
+
def incremental_train(self, data_manager):
|
| 45 |
+
self.curr_acc = 0
|
| 46 |
+
self._cur_task += 1
|
| 47 |
+
self._total_classes = self._known_classes + data_manager.get_task_size(
|
| 48 |
+
self._cur_task
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
self._network.update_fc(self._total_classes)
|
| 53 |
+
logging.info(
|
| 54 |
+
"Learning on {}-{}".format(self._known_classes, self._total_classes)
|
| 55 |
+
)
|
| 56 |
+
logging.info("All params: {}".format(count_parameters(self._network)))
|
| 57 |
+
logging.info(
|
| 58 |
+
"Trainable params: {}".format(count_parameters(self._network, True))
|
| 59 |
+
)
|
| 60 |
+
logging.debug("****MODEL ARCHITECTURE****")
|
| 61 |
+
logging.debug(self._network)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
train_dataset = data_manager.get_dataset(
|
| 65 |
+
np.arange(self._known_classes, self._total_classes),
|
| 66 |
+
source="train",
|
| 67 |
+
mode="train",
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
self.train_loader = DataLoader(
|
| 73 |
+
train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers
|
| 74 |
+
)
|
| 75 |
+
test_dataset = data_manager.get_dataset(
|
| 76 |
+
np.arange(0, self._total_classes), source="test", mode="test"
|
| 77 |
+
)
|
| 78 |
+
self.test_loader = DataLoader(
|
| 79 |
+
test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
if len(self._multiple_gpus) > 1:
|
| 83 |
+
print('***********RUNNING on multiple devices****************')
|
| 84 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 85 |
+
|
| 86 |
+
self._train(self.train_loader, self.test_loader)
|
| 87 |
+
if len(self._multiple_gpus) > 1:
|
| 88 |
+
self._network = self._network.module
|
| 89 |
+
if self._total_classes == data_manager.get_total_classnum():
|
| 90 |
+
self.writer.close()
|
| 91 |
+
|
| 92 |
+
def _train(self, train_loader, test_loader):
|
| 93 |
+
|
| 94 |
+
self._network.to(self._device)
|
| 95 |
+
|
| 96 |
+
if self._cur_task == 0:
|
| 97 |
+
optimizer = optim.SGD(
|
| 98 |
+
self._network.parameters(),
|
| 99 |
+
momentum=0.9,
|
| 100 |
+
lr=init_lr,
|
| 101 |
+
weight_decay=init_weight_decay,
|
| 102 |
+
)
|
| 103 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 104 |
+
optimizer=optimizer, milestones=init_milestones, gamma=init_lr_decay
|
| 105 |
+
)
|
| 106 |
+
self._init_train(train_loader, test_loader, optimizer, scheduler)
|
| 107 |
+
else:
|
| 108 |
+
optimizer = optim.SGD(
|
| 109 |
+
self._network.parameters(),
|
| 110 |
+
lr=lrate,
|
| 111 |
+
momentum=0.9,
|
| 112 |
+
weight_decay=weight_decay,
|
| 113 |
+
) # 1e-5
|
| 114 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 115 |
+
optimizer=optimizer, milestones=milestones, gamma=lrate_decay
|
| 116 |
+
)
|
| 117 |
+
self._update_representation(train_loader, test_loader, optimizer, scheduler)
|
| 118 |
+
|
| 119 |
+
self.writer.add_figure("Confusion matrix",
|
| 120 |
+
self._createConfusionMatrix(self._network, self.test_loader),
|
| 121 |
+
self._cur_task)
|
| 122 |
+
self.writer.add_scalar('Accuracies', self.curr_acc, self._cur_task)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _init_train(self, train_loader, test_loader, optimizer, scheduler):
|
| 126 |
+
prog_bar = tqdm(range(init_epoch))
|
| 127 |
+
for _, epoch in enumerate(prog_bar):
|
| 128 |
+
self._network.train()
|
| 129 |
+
losses = 0.0
|
| 130 |
+
correct, total = 0, 0
|
| 131 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 132 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 133 |
+
logits = self._network(inputs)["logits"]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
loss = F.cross_entropy(logits, targets)
|
| 137 |
+
optimizer.zero_grad()
|
| 138 |
+
loss.backward()
|
| 139 |
+
optimizer.step()
|
| 140 |
+
losses += loss.item()
|
| 141 |
+
|
| 142 |
+
_, preds = torch.max(logits, dim=1)
|
| 143 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 144 |
+
total += len(targets)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
scheduler.step()
|
| 148 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 149 |
+
|
| 150 |
+
if epoch % 5 == 0:
|
| 151 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 152 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 153 |
+
self._cur_task,
|
| 154 |
+
epoch + 1,
|
| 155 |
+
init_epoch,
|
| 156 |
+
losses / len(train_loader),
|
| 157 |
+
train_acc,
|
| 158 |
+
test_acc,
|
| 159 |
+
)
|
| 160 |
+
# "Learning on {}-{}".format(self._known_classes, self._total_classes)
|
| 161 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 162 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 163 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 164 |
+
|
| 165 |
+
else:
|
| 166 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 167 |
+
self._cur_task,
|
| 168 |
+
epoch + 1,
|
| 169 |
+
init_epoch,
|
| 170 |
+
losses / len(train_loader),
|
| 171 |
+
train_acc,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
prog_bar.set_description(info)
|
| 175 |
+
|
| 176 |
+
logging.info(info)
|
| 177 |
+
|
| 178 |
+
def _update_representation(self, train_loader, test_loader, optimizer, scheduler):
|
| 179 |
+
|
| 180 |
+
prog_bar = tqdm(range(epochs))
|
| 181 |
+
for _, epoch in enumerate(prog_bar):
|
| 182 |
+
self._network.train()
|
| 183 |
+
losses = 0.0
|
| 184 |
+
correct, total = 0, 0
|
| 185 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 186 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 187 |
+
logits = self._network(inputs)["logits"]
|
| 188 |
+
|
| 189 |
+
fake_targets = targets - self._known_classes
|
| 190 |
+
loss_clf = F.cross_entropy(
|
| 191 |
+
logits[:, self._known_classes :], fake_targets
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
loss = loss_clf
|
| 195 |
+
|
| 196 |
+
optimizer.zero_grad()
|
| 197 |
+
loss.backward()
|
| 198 |
+
optimizer.step()
|
| 199 |
+
losses += loss.item()
|
| 200 |
+
|
| 201 |
+
_, preds = torch.max(logits, dim=1)
|
| 202 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 203 |
+
total += len(targets)
|
| 204 |
+
|
| 205 |
+
scheduler.step()
|
| 206 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 207 |
+
if epoch % 5 == 0:
|
| 208 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 209 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 210 |
+
self._cur_task,
|
| 211 |
+
epoch + 1,
|
| 212 |
+
epochs,
|
| 213 |
+
losses / len(train_loader),
|
| 214 |
+
train_acc,
|
| 215 |
+
test_acc,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 219 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 220 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 221 |
+
|
| 222 |
+
else:
|
| 223 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 224 |
+
self._cur_task,
|
| 225 |
+
epoch + 1,
|
| 226 |
+
epochs,
|
| 227 |
+
losses / len(train_loader),
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch import optim
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
from torch.utils.data import DataLoader
|
| 9 |
+
from models.base import BaseLearner
|
| 10 |
+
from utils.inc_net import FOSTERNet
|
| 11 |
+
from utils.toolkit import count_parameters, target2onehot, tensor2numpy, count_parameters
|
| 12 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 13 |
+
# Please refer to https://github.com/G-U-N/ECCV22-FOSTER for the full source code to reproduce foster.
|
| 14 |
+
|
| 15 |
+
EPSILON = 1e-8
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class FOSTER(BaseLearner):
|
| 19 |
+
def __init__(self, args):
|
| 20 |
+
super().__init__(args)
|
| 21 |
+
self.args = args
|
| 22 |
+
self._network = FOSTERNet(args, False)
|
| 23 |
+
self._snet = None
|
| 24 |
+
self.beta1 = args["beta1"]
|
| 25 |
+
self.beta2 = args["beta2"]
|
| 26 |
+
self.per_cls_weights = None
|
| 27 |
+
self.is_teacher_wa = args["is_teacher_wa"]
|
| 28 |
+
self.is_student_wa = args["is_student_wa"]
|
| 29 |
+
self.lambda_okd = args["lambda_okd"]
|
| 30 |
+
self.wa_value = args["wa_value"]
|
| 31 |
+
self.oofc = args["oofc"].lower()
|
| 32 |
+
self.writer = SummaryWriter(log_dir='runs/{}'.format(args['summary_file']))
|
| 33 |
+
|
| 34 |
+
def after_task(self):
|
| 35 |
+
self._known_classes = self._total_classes
|
| 36 |
+
logging.info("Exemplar size: {}".format(self.exemplar_size))
|
| 37 |
+
|
| 38 |
+
def incremental_train(self, data_manager):
|
| 39 |
+
self.curr_acc = 0
|
| 40 |
+
self.data_manager = data_manager
|
| 41 |
+
self._cur_task += 1
|
| 42 |
+
if self._cur_task > 1:
|
| 43 |
+
self._network = self._snet
|
| 44 |
+
self._total_classes = self._known_classes + data_manager.get_task_size(
|
| 45 |
+
self._cur_task
|
| 46 |
+
)
|
| 47 |
+
self._network.update_fc(self._total_classes)
|
| 48 |
+
self._network_module_ptr = self._network
|
| 49 |
+
self._network.update_fc(self._total_classes)
|
| 50 |
+
logging.info(
|
| 51 |
+
"Learning on {}-{}".format(self._known_classes, self._total_classes)
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
logging.debug("****MODEL ARCHITECTURE****")
|
| 55 |
+
logging.debug(self._network)
|
| 56 |
+
|
| 57 |
+
if self._cur_task > 0:
|
| 58 |
+
for p in self._network.convnets[0].parameters():
|
| 59 |
+
p.requires_grad = False
|
| 60 |
+
for p in self._network.oldfc.parameters():
|
| 61 |
+
p.requires_grad = False
|
| 62 |
+
|
| 63 |
+
logging.info("All params: {}".format(count_parameters(self._network)))
|
| 64 |
+
logging.info(
|
| 65 |
+
"Trainable params: {}".format(count_parameters(self._network, True))
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
train_dataset = data_manager.get_dataset(
|
| 69 |
+
np.arange(self._known_classes, self._total_classes),
|
| 70 |
+
source="train",
|
| 71 |
+
mode="train",
|
| 72 |
+
appendent=self._get_memory(),
|
| 73 |
+
)
|
| 74 |
+
self.train_loader = DataLoader(
|
| 75 |
+
train_dataset,
|
| 76 |
+
batch_size=self.args["batch_size"],
|
| 77 |
+
shuffle=True,
|
| 78 |
+
num_workers=self.args["num_workers"],
|
| 79 |
+
pin_memory=True,
|
| 80 |
+
)
|
| 81 |
+
test_dataset = data_manager.get_dataset(
|
| 82 |
+
np.arange(0, self._total_classes), source="test", mode="test"
|
| 83 |
+
)
|
| 84 |
+
self.test_loader = DataLoader(
|
| 85 |
+
test_dataset,
|
| 86 |
+
batch_size=self.args["batch_size"],
|
| 87 |
+
shuffle=False,
|
| 88 |
+
num_workers=self.args["num_workers"],
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
inference_dataset = data_manager.get_dataset(
|
| 92 |
+
np.arange(0, self._total_classes), source="inference", mode="test"
|
| 93 |
+
)
|
| 94 |
+
self.inference_loader = DataLoader(
|
| 95 |
+
inference_dataset, batch_size=self.args["batch_size"], shuffle=False,
|
| 96 |
+
num_workers=self.args["num_workers"]
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if len(self._multiple_gpus) > 1:
|
| 101 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 102 |
+
self._train(self.train_loader, self.test_loader)
|
| 103 |
+
self.build_rehearsal_memory(data_manager, self.samples_per_class)
|
| 104 |
+
if len(self._multiple_gpus) > 1:
|
| 105 |
+
self._network = self._network.module
|
| 106 |
+
if self._total_classes == data_manager.get_total_classnum():
|
| 107 |
+
self.writer.close()
|
| 108 |
+
|
| 109 |
+
def train(self):
|
| 110 |
+
self._network_module_ptr.train()
|
| 111 |
+
self._network_module_ptr.convnets[-1].train()
|
| 112 |
+
if self._cur_task >= 1:
|
| 113 |
+
self._network_module_ptr.convnets[0].eval()
|
| 114 |
+
|
| 115 |
+
def _train(self, train_loader, test_loader):
|
| 116 |
+
self._network.to(self._device)
|
| 117 |
+
if hasattr(self._network, "module"):
|
| 118 |
+
self._network_module_ptr = self._network.module
|
| 119 |
+
if self._cur_task == 0:
|
| 120 |
+
optimizer = optim.SGD(
|
| 121 |
+
filter(lambda p: p.requires_grad, self._network.parameters()),
|
| 122 |
+
momentum=0.9,
|
| 123 |
+
lr=self.args["init_lr"],
|
| 124 |
+
weight_decay=self.args["init_weight_decay"],
|
| 125 |
+
)
|
| 126 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(
|
| 127 |
+
optimizer=optimizer, T_max=self.args["init_epochs"]
|
| 128 |
+
)
|
| 129 |
+
self._init_train(train_loader, test_loader, optimizer, scheduler)
|
| 130 |
+
else:
|
| 131 |
+
|
| 132 |
+
cls_num_list = [self.samples_old_class] * self._known_classes + [
|
| 133 |
+
self.samples_new_class(i)
|
| 134 |
+
for i in range(self._known_classes, self._total_classes)
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
effective_num = 1.0 - np.power(self.beta1, cls_num_list)
|
| 138 |
+
per_cls_weights = (1.0 - self.beta1) / np.array(effective_num)
|
| 139 |
+
per_cls_weights = (
|
| 140 |
+
per_cls_weights / np.sum(per_cls_weights) * len(cls_num_list)
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
logging.info("per cls weights : {}".format(per_cls_weights))
|
| 144 |
+
self.per_cls_weights = torch.FloatTensor(per_cls_weights).to(self._device)
|
| 145 |
+
|
| 146 |
+
optimizer = optim.SGD(
|
| 147 |
+
filter(lambda p: p.requires_grad, self._network.parameters()),
|
| 148 |
+
lr=self.args["lr"],
|
| 149 |
+
momentum=0.9,
|
| 150 |
+
weight_decay=self.args["weight_decay"],
|
| 151 |
+
)
|
| 152 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(
|
| 153 |
+
optimizer=optimizer, T_max=self.args["boosting_epochs"]
|
| 154 |
+
)
|
| 155 |
+
if self.oofc == "az":
|
| 156 |
+
for i, p in enumerate(self._network_module_ptr.fc.parameters()):
|
| 157 |
+
if i == 0:
|
| 158 |
+
p.data[
|
| 159 |
+
self._known_classes :, : self._network_module_ptr.out_dim
|
| 160 |
+
] = torch.tensor(0.0)
|
| 161 |
+
elif self.oofc != "ft":
|
| 162 |
+
assert 0, "not implemented"
|
| 163 |
+
self._feature_boosting(train_loader, test_loader, optimizer, scheduler)
|
| 164 |
+
if self.is_teacher_wa:
|
| 165 |
+
self._network_module_ptr.weight_align(
|
| 166 |
+
self._known_classes,
|
| 167 |
+
self._total_classes - self._known_classes,
|
| 168 |
+
self.wa_value,
|
| 169 |
+
)
|
| 170 |
+
else:
|
| 171 |
+
logging.info("do not weight align teacher!")
|
| 172 |
+
|
| 173 |
+
cls_num_list = [self.samples_old_class] * self._known_classes + [
|
| 174 |
+
self.samples_new_class(i)
|
| 175 |
+
for i in range(self._known_classes, self._total_classes)
|
| 176 |
+
]
|
| 177 |
+
effective_num = 1.0 - np.power(self.beta2, cls_num_list)
|
| 178 |
+
per_cls_weights = (1.0 - self.beta2) / np.array(effective_num)
|
| 179 |
+
per_cls_weights = (
|
| 180 |
+
per_cls_weights / np.sum(per_cls_weights) * len(cls_num_list)
|
| 181 |
+
)
|
| 182 |
+
logging.info("per cls weights : {}".format(per_cls_weights))
|
| 183 |
+
self.per_cls_weights = torch.FloatTensor(per_cls_weights).to(self._device)
|
| 184 |
+
self._feature_compression(train_loader, test_loader)
|
| 185 |
+
|
| 186 |
+
self.writer.add_figure("Confusion matrix",
|
| 187 |
+
self._createConfusionMatrix(self._network, self.inference_loader),
|
| 188 |
+
self._cur_task)
|
| 189 |
+
self.writer.add_scalar('Accuracies', self.curr_acc, self._cur_task)
|
| 190 |
+
|
| 191 |
+
def _init_train(self, train_loader, test_loader, optimizer, scheduler):
|
| 192 |
+
prog_bar = tqdm(range(self.args["init_epochs"]))
|
| 193 |
+
for _, epoch in enumerate(prog_bar):
|
| 194 |
+
self.train()
|
| 195 |
+
losses = 0.0
|
| 196 |
+
correct, total = 0, 0
|
| 197 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 198 |
+
inputs, targets = inputs.to(
|
| 199 |
+
self._device, non_blocking=True
|
| 200 |
+
), targets.to(self._device, non_blocking=True)
|
| 201 |
+
logits = self._network(inputs)["logits"]
|
| 202 |
+
loss = F.cross_entropy(logits, targets)
|
| 203 |
+
optimizer.zero_grad()
|
| 204 |
+
loss.backward()
|
| 205 |
+
optimizer.step()
|
| 206 |
+
losses += loss.item()
|
| 207 |
+
_, preds = torch.max(logits, dim=1)
|
| 208 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 209 |
+
total += len(targets)
|
| 210 |
+
scheduler.step()
|
| 211 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 212 |
+
|
| 213 |
+
if epoch % 5 == 0:
|
| 214 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 215 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 216 |
+
self._cur_task,
|
| 217 |
+
epoch + 1,
|
| 218 |
+
self.args["init_epochs"],
|
| 219 |
+
losses / len(train_loader),
|
| 220 |
+
train_acc,
|
| 221 |
+
test_acc,
|
| 222 |
+
)
|
| 223 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Loss/train'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 224 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy train'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 225 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy test'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 226 |
+
|
| 227 |
+
else:
|
| 228 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 229 |
+
self._cur_task,
|
| 230 |
+
epoch + 1,
|
| 231 |
+
self.args["init_epochs"],
|
| 232 |
+
losses / len(train_loader),
|
| 233 |
+
train_acc,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
prog_bar.set_description(info)
|
| 237 |
+
logging.info(info)
|
| 238 |
+
|
| 239 |
+
def _feature_boosting(self, train_loader, test_loader, optimizer, scheduler):
|
| 240 |
+
prog_bar = tqdm(range(self.args["boosting_epochs"]))
|
| 241 |
+
for _, epoch in enumerate(prog_bar):
|
| 242 |
+
self.train()
|
| 243 |
+
losses = 0.0
|
| 244 |
+
losses_clf = 0.0
|
| 245 |
+
losses_fe = 0.0
|
| 246 |
+
losses_kd = 0.0
|
| 247 |
+
correct, total = 0, 0
|
| 248 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 249 |
+
inputs, targets = inputs.to(
|
| 250 |
+
self._device, non_blocking=True
|
| 251 |
+
), targets.to(self._device, non_blocking=True)
|
| 252 |
+
outputs = self._network(inputs)
|
| 253 |
+
logits, fe_logits, old_logits = (
|
| 254 |
+
outputs["logits"],
|
| 255 |
+
outputs["fe_logits"],
|
| 256 |
+
outputs["old_logits"].detach(),
|
| 257 |
+
)
|
| 258 |
+
loss_clf = F.cross_entropy(logits / self.per_cls_weights, targets)
|
| 259 |
+
loss_fe = F.cross_entropy(fe_logits, targets)
|
| 260 |
+
loss_kd = self.lambda_okd * _KD_loss(
|
| 261 |
+
logits[:, : self._known_classes], old_logits, self.args["T"]
|
| 262 |
+
)
|
| 263 |
+
loss = loss_clf + loss_fe + loss_kd
|
| 264 |
+
optimizer.zero_grad()
|
| 265 |
+
loss.backward()
|
| 266 |
+
if self.oofc == "az":
|
| 267 |
+
for i, p in enumerate(self._network_module_ptr.fc.parameters()):
|
| 268 |
+
if i == 0:
|
| 269 |
+
p.grad.data[
|
| 270 |
+
self._known_classes :,
|
| 271 |
+
: self._network_module_ptr.out_dim,
|
| 272 |
+
] = torch.tensor(0.0)
|
| 273 |
+
elif self.oofc != "ft":
|
| 274 |
+
assert 0, "not implemented"
|
| 275 |
+
optimizer.step()
|
| 276 |
+
losses += loss.item()
|
| 277 |
+
losses_fe += loss_fe.item()
|
| 278 |
+
losses_clf += loss_clf.item()
|
| 279 |
+
losses_kd += (
|
| 280 |
+
self._known_classes / self._total_classes
|
| 281 |
+
) * loss_kd.item()
|
| 282 |
+
_, preds = torch.max(logits, dim=1)
|
| 283 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 284 |
+
total += len(targets)
|
| 285 |
+
scheduler.step()
|
| 286 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 287 |
+
if epoch % 5 == 0:
|
| 288 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 289 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Loss_clf {:.3f}, Loss_fe {:.3f}, Loss_kd {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 290 |
+
self._cur_task,
|
| 291 |
+
epoch + 1,
|
| 292 |
+
self.args["boosting_epochs"],
|
| 293 |
+
losses / len(train_loader),
|
| 294 |
+
losses_clf / len(train_loader),
|
| 295 |
+
losses_fe / len(train_loader),
|
| 296 |
+
losses_kd / len(train_loader),
|
| 297 |
+
train_acc,
|
| 298 |
+
test_acc,
|
| 299 |
+
)
|
| 300 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Loss/train'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 301 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy train'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 302 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy test'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 303 |
+
else:
|
| 304 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Loss_clf {:.3f}, Loss_fe {:.3f}, Loss_kd {:.3f}, Train_accy {:.2f}".format(
|
| 305 |
+
self._cur_task,
|
| 306 |
+
epoch + 1,
|
| 307 |
+
self.args["boosting_epochs"],
|
| 308 |
+
losses / len(train_loader),
|
| 309 |
+
losses_clf / len(train_loader),
|
| 310 |
+
losses_fe / len(train_loader),
|
| 311 |
+
losses_kd / len(train_loader),
|
| 312 |
+
train_acc,
|
| 313 |
+
)
|
| 314 |
+
prog_bar.set_description(info)
|
| 315 |
+
logging.info(info)
|
| 316 |
+
|
| 317 |
+
def _feature_compression(self, train_loader, test_loader):
|
| 318 |
+
self._snet = FOSTERNet(self.args, False)
|
| 319 |
+
self._snet.update_fc(self._total_classes)
|
| 320 |
+
if len(self._multiple_gpus) > 1:
|
| 321 |
+
self._snet = nn.DataParallel(self._snet, self._multiple_gpus)
|
| 322 |
+
if hasattr(self._snet, "module"):
|
| 323 |
+
self._snet_module_ptr = self._snet.module
|
| 324 |
+
else:
|
| 325 |
+
self._snet_module_ptr = self._snet
|
| 326 |
+
self._snet.to(self._device)
|
| 327 |
+
self._snet_module_ptr.convnets[0].load_state_dict(
|
| 328 |
+
self._network_module_ptr.convnets[0].state_dict()
|
| 329 |
+
)
|
| 330 |
+
self._snet_module_ptr.copy_fc(self._network_module_ptr.oldfc)
|
| 331 |
+
optimizer = optim.SGD(
|
| 332 |
+
filter(lambda p: p.requires_grad, self._snet.parameters()),
|
| 333 |
+
lr=self.args["lr"],
|
| 334 |
+
momentum=0.9,
|
| 335 |
+
)
|
| 336 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(
|
| 337 |
+
optimizer=optimizer, T_max=self.args["compression_epochs"]
|
| 338 |
+
)
|
| 339 |
+
self._network.eval()
|
| 340 |
+
prog_bar = tqdm(range(self.args["compression_epochs"]))
|
| 341 |
+
for _, epoch in enumerate(prog_bar):
|
| 342 |
+
self._snet.train()
|
| 343 |
+
losses = 0.0
|
| 344 |
+
correct, total = 0, 0
|
| 345 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 346 |
+
inputs, targets = inputs.to(
|
| 347 |
+
self._device, non_blocking=True
|
| 348 |
+
), targets.to(self._device, non_blocking=True)
|
| 349 |
+
dark_logits = self._snet(inputs)["logits"]
|
| 350 |
+
with torch.no_grad():
|
| 351 |
+
outputs = self._network(inputs)
|
| 352 |
+
logits, old_logits, fe_logits = (
|
| 353 |
+
outputs["logits"],
|
| 354 |
+
outputs["old_logits"],
|
| 355 |
+
outputs["fe_logits"],
|
| 356 |
+
)
|
| 357 |
+
loss_dark = self.BKD(dark_logits, logits, self.args["T"])
|
| 358 |
+
loss = loss_dark
|
| 359 |
+
optimizer.zero_grad()
|
| 360 |
+
loss.backward()
|
| 361 |
+
optimizer.step()
|
| 362 |
+
losses += loss.item()
|
| 363 |
+
_, preds = torch.max(dark_logits[: targets.shape[0]], dim=1)
|
| 364 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 365 |
+
total += len(targets)
|
| 366 |
+
scheduler.step()
|
| 367 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 368 |
+
if epoch % 5 == 0:
|
| 369 |
+
test_acc = self._compute_accuracy(self._snet, test_loader)
|
| 370 |
+
info = "SNet: Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 371 |
+
self._cur_task,
|
| 372 |
+
epoch + 1,
|
| 373 |
+
self.args["compression_epochs"],
|
| 374 |
+
losses / len(train_loader),
|
| 375 |
+
train_acc,
|
| 376 |
+
test_acc,
|
| 377 |
+
)
|
| 378 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Loss/train'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 379 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy train'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 380 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy test'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 381 |
+
else:
|
| 382 |
+
info = "SNet: Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 383 |
+
self._cur_task,
|
| 384 |
+
epoch + 1,
|
| 385 |
+
self.args["compression_epochs"],
|
| 386 |
+
losses / len(train_loader),
|
| 387 |
+
train_acc,
|
| 388 |
+
)
|
| 389 |
+
prog_bar.set_description(info)
|
| 390 |
+
logging.info(info)
|
| 391 |
+
if len(self._multiple_gpus) > 1:
|
| 392 |
+
self._snet = self._snet.module
|
| 393 |
+
if self.is_student_wa:
|
| 394 |
+
self._snet.weight_align(
|
| 395 |
+
self._known_classes,
|
| 396 |
+
self._total_classes - self._known_classes,
|
| 397 |
+
self.wa_value,
|
| 398 |
+
)
|
| 399 |
+
else:
|
| 400 |
+
logging.info("do not weight align student!")
|
| 401 |
+
|
| 402 |
+
self._snet.eval()
|
| 403 |
+
y_pred, y_true = [], []
|
| 404 |
+
for _, (_, inputs, targets) in enumerate(test_loader):
|
| 405 |
+
inputs = inputs.to(self._device, non_blocking=True)
|
| 406 |
+
with torch.no_grad():
|
| 407 |
+
outputs = self._snet(inputs)["logits"]
|
| 408 |
+
predicts = torch.topk(
|
| 409 |
+
outputs, k=self.topk, dim=1, largest=True, sorted=True
|
| 410 |
+
)[1]
|
| 411 |
+
y_pred.append(predicts.cpu().numpy())
|
| 412 |
+
y_true.append(targets.cpu().numpy())
|
| 413 |
+
y_pred = np.concatenate(y_pred)
|
| 414 |
+
y_true = np.concatenate(y_true)
|
| 415 |
+
cnn_accy = self._evaluate(y_pred, y_true)
|
| 416 |
+
logging.info("darknet eval: ")
|
| 417 |
+
logging.info("CNN top1 curve: {}".format(cnn_accy["top1"]))
|
| 418 |
+
logging.info("CNN top5 curve: {}".format(cnn_accy["top5"]))
|
| 419 |
+
|
| 420 |
+
@property
|
| 421 |
+
def samples_old_class(self):
|
| 422 |
+
if self._fixed_memory:
|
| 423 |
+
return self._memory_per_class
|
| 424 |
+
else:
|
| 425 |
+
assert self._total_classes != 0, "Total classes is 0"
|
| 426 |
+
return self._memory_size // self._known_classes
|
| 427 |
+
|
| 428 |
+
def samples_new_class(self, index):
|
| 429 |
+
if self.args["dataset"] == "cifar100":
|
| 430 |
+
return 500
|
| 431 |
+
else:
|
| 432 |
+
return self.data_manager.getlen(index)
|
| 433 |
+
|
| 434 |
+
def BKD(self, pred, soft, T):
|
| 435 |
+
pred = torch.log_softmax(pred / T, dim=1)
|
| 436 |
+
soft = torch.softmax(soft / T, dim=1)
|
| 437 |
+
soft = soft * self.per_cls_weights
|
| 438 |
+
soft = soft / soft.sum(1)[:, None]
|
| 439 |
+
return -1 * torch.mul(soft, pred).sum() / pred.shape[0]
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def _KD_loss(pred, soft, T):
|
| 443 |
+
pred = torch.log_softmax(pred / T, dim=1)
|
| 444 |
+
soft = torch.softmax(soft / T, dim=1)
|
| 445 |
+
return -1 * torch.mul(soft, pred).sum() / pred.shape[0]
|
models/icarl.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch import optim
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
from torch.utils.data import DataLoader
|
| 9 |
+
from models.base import BaseLearner
|
| 10 |
+
from utils.inc_net import IncrementalNet
|
| 11 |
+
from utils.inc_net import CosineIncrementalNet
|
| 12 |
+
from utils.toolkit import target2onehot, tensor2numpy
|
| 13 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 14 |
+
|
| 15 |
+
EPSILON = 1e-8
|
| 16 |
+
|
| 17 |
+
init_epoch = 200
|
| 18 |
+
init_lr = 0.1
|
| 19 |
+
init_milestones = [60, 120, 170]
|
| 20 |
+
init_lr_decay = 0.1
|
| 21 |
+
init_weight_decay = 0.0005
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
epochs = 200
|
| 25 |
+
lrate = 0.1
|
| 26 |
+
milestones = [80, 120]
|
| 27 |
+
lrate_decay = 0.1
|
| 28 |
+
batch_size = 128
|
| 29 |
+
weight_decay = 2e-4
|
| 30 |
+
num_workers = 2
|
| 31 |
+
T = 2
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class iCaRL(BaseLearner):
|
| 35 |
+
def __init__(self, args):
|
| 36 |
+
super().__init__(args)
|
| 37 |
+
self._network = IncrementalNet(args, True)
|
| 38 |
+
self.writer = SummaryWriter(log_dir='runs/{}'.format(args['summary_file']))
|
| 39 |
+
|
| 40 |
+
def after_task(self):
|
| 41 |
+
self._old_network = self._network.copy().freeze()
|
| 42 |
+
self._known_classes = self._total_classes
|
| 43 |
+
logging.info("Exemplar size: {}".format(self.exemplar_size))
|
| 44 |
+
|
| 45 |
+
def incremental_train(self, data_manager):
|
| 46 |
+
self.curr_acc = 0
|
| 47 |
+
self._cur_task += 1
|
| 48 |
+
self._total_classes = self._known_classes + data_manager.get_task_size(
|
| 49 |
+
self._cur_task
|
| 50 |
+
)
|
| 51 |
+
self._network.update_fc(self._total_classes)
|
| 52 |
+
logging.info(
|
| 53 |
+
"Learning on {}-{}".format(self._known_classes, self._total_classes)
|
| 54 |
+
)
|
| 55 |
+
logging.info(
|
| 56 |
+
"Known_classes: {}\tTotal_classes: {}\tcurrent_task: {}".format(self._known_classes, self._total_classes, self._cur_task)
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
_, tr_targets, train_dataset = data_manager.get_dataset(
|
| 60 |
+
np.arange(self._known_classes, self._total_classes),
|
| 61 |
+
source="train",
|
| 62 |
+
mode="train",
|
| 63 |
+
appendent=self._get_memory(),
|
| 64 |
+
ret_data=True
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
self.train_loader = DataLoader(
|
| 69 |
+
train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
_, te_targets, test_dataset = data_manager.get_dataset(
|
| 73 |
+
np.arange(0, self._total_classes),
|
| 74 |
+
source="test",
|
| 75 |
+
mode="test",
|
| 76 |
+
ret_data=True
|
| 77 |
+
)
|
| 78 |
+
self.test_loader = DataLoader(
|
| 79 |
+
test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
uq_te, count_te = np.unique(te_targets, return_counts=True)
|
| 83 |
+
uq_tr, count_tr = np.unique(tr_targets, return_counts=True)
|
| 84 |
+
|
| 85 |
+
if len(self._multiple_gpus) > 1:
|
| 86 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 87 |
+
self._train(self.train_loader, self.test_loader)
|
| 88 |
+
self.build_rehearsal_memory(data_manager, self.samples_per_class)
|
| 89 |
+
if len(self._multiple_gpus) > 1:
|
| 90 |
+
self._network = self._network.module
|
| 91 |
+
|
| 92 |
+
def _train(self, train_loader, test_loader):
|
| 93 |
+
self._network.to(self._device)
|
| 94 |
+
if self._old_network is not None:
|
| 95 |
+
self._old_network.to(self._device)
|
| 96 |
+
|
| 97 |
+
if self._cur_task == 0:
|
| 98 |
+
optimizer = optim.SGD(
|
| 99 |
+
self._network.parameters(),
|
| 100 |
+
momentum=0.9,
|
| 101 |
+
lr=init_lr,
|
| 102 |
+
weight_decay=init_weight_decay,
|
| 103 |
+
)
|
| 104 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 105 |
+
optimizer=optimizer, milestones=init_milestones, gamma=init_lr_decay
|
| 106 |
+
)
|
| 107 |
+
logging.info('## Initial Training ##')
|
| 108 |
+
self._init_train(train_loader, test_loader, optimizer, scheduler)
|
| 109 |
+
|
| 110 |
+
else:
|
| 111 |
+
optimizer = optim.SGD(
|
| 112 |
+
self._network.parameters(),
|
| 113 |
+
lr=lrate,
|
| 114 |
+
momentum=0.9,
|
| 115 |
+
weight_decay=weight_decay,
|
| 116 |
+
) # 1e-5
|
| 117 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 118 |
+
optimizer=optimizer, milestones=milestones, gamma=lrate_decay
|
| 119 |
+
)
|
| 120 |
+
self._update_representation(train_loader, test_loader, optimizer, scheduler)
|
| 121 |
+
|
| 122 |
+
self.writer.add_figure("Confusion matrix",
|
| 123 |
+
self._createConfusionMatrix(self._network, self.test_loader),
|
| 124 |
+
self._cur_task)
|
| 125 |
+
self.writer.add_scalar('Accuracies', self.curr_acc, self._cur_task)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _init_train(self, train_loader, test_loader, optimizer, scheduler):
|
| 129 |
+
prog_bar = tqdm(range(init_epoch))
|
| 130 |
+
for _, epoch in enumerate(prog_bar):
|
| 131 |
+
|
| 132 |
+
self._network.train()
|
| 133 |
+
losses = 0.0
|
| 134 |
+
correct, total = 0, 0
|
| 135 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 136 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 137 |
+
logits = self._network(inputs)["logits"]
|
| 138 |
+
|
| 139 |
+
loss = F.cross_entropy(logits, targets)
|
| 140 |
+
optimizer.zero_grad()
|
| 141 |
+
loss.backward()
|
| 142 |
+
optimizer.step()
|
| 143 |
+
losses += loss.item()
|
| 144 |
+
|
| 145 |
+
_, preds = torch.max(logits, dim=1)
|
| 146 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 147 |
+
total += len(targets)
|
| 148 |
+
|
| 149 |
+
scheduler.step()
|
| 150 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 151 |
+
|
| 152 |
+
if epoch % 5 == 0:
|
| 153 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 154 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 155 |
+
self._cur_task,
|
| 156 |
+
epoch + 1,
|
| 157 |
+
init_epoch,
|
| 158 |
+
losses / len(train_loader),
|
| 159 |
+
train_acc,
|
| 160 |
+
test_acc,
|
| 161 |
+
)
|
| 162 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 163 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 164 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 165 |
+
else:
|
| 166 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 167 |
+
self._cur_task,
|
| 168 |
+
epoch + 1,
|
| 169 |
+
init_epoch,
|
| 170 |
+
losses / len(train_loader),
|
| 171 |
+
train_acc,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
prog_bar.set_description(info)
|
| 175 |
+
|
| 176 |
+
logging.info(info)
|
| 177 |
+
|
| 178 |
+
def _update_representation(self, train_loader, test_loader, optimizer, scheduler):
|
| 179 |
+
prog_bar = tqdm(range(epochs))
|
| 180 |
+
for _, epoch in enumerate(prog_bar):
|
| 181 |
+
|
| 182 |
+
self._network.train()
|
| 183 |
+
losses = 0.0
|
| 184 |
+
correct, total = 0, 0
|
| 185 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 186 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 187 |
+
logits = self._network(inputs)["logits"]
|
| 188 |
+
|
| 189 |
+
loss_clf = F.cross_entropy(logits, targets)
|
| 190 |
+
loss_kd = _KD_loss(
|
| 191 |
+
logits[:, : self._known_classes],
|
| 192 |
+
self._old_network(inputs)["logits"],
|
| 193 |
+
T,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
loss = loss_clf + loss_kd
|
| 197 |
+
|
| 198 |
+
optimizer.zero_grad()
|
| 199 |
+
loss.backward()
|
| 200 |
+
optimizer.step()
|
| 201 |
+
losses += loss.item()
|
| 202 |
+
|
| 203 |
+
_, preds = torch.max(logits, dim=1)
|
| 204 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 205 |
+
total += len(targets)
|
| 206 |
+
|
| 207 |
+
scheduler.step()
|
| 208 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 209 |
+
if epoch % 5 == 0:
|
| 210 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 211 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 212 |
+
self._cur_task,
|
| 213 |
+
epoch + 1,
|
| 214 |
+
epochs,
|
| 215 |
+
losses / len(train_loader),
|
| 216 |
+
train_acc,
|
| 217 |
+
test_acc,
|
| 218 |
+
)
|
| 219 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 220 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 221 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 222 |
+
else:
|
| 223 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 224 |
+
self._cur_task,
|
| 225 |
+
epoch + 1,
|
| 226 |
+
epochs,
|
| 227 |
+
losses / len(train_loader),
|
| 228 |
+
train_acc,
|
| 229 |
+
)
|
| 230 |
+
prog_bar.set_description(info)
|
| 231 |
+
logging.info(info)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _KD_loss(pred, soft, T):
|
| 235 |
+
pred = torch.log_softmax(pred / T, dim=1)
|
| 236 |
+
soft = torch.softmax(soft / T, dim=1)
|
| 237 |
+
return -1 * torch.mul(soft, pred).sum() / pred.shape[0]
|
models/lwf.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torch.serialization import load
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
from torch import optim
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
from torch.utils.data import DataLoader
|
| 10 |
+
from utils.inc_net import IncrementalNet
|
| 11 |
+
from models.base import BaseLearner
|
| 12 |
+
from utils.toolkit import target2onehot, tensor2numpy
|
| 13 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 14 |
+
|
| 15 |
+
init_epoch = 200
|
| 16 |
+
init_lr = 0.1
|
| 17 |
+
init_milestones = [60, 120, 160]
|
| 18 |
+
init_lr_decay = 0.1
|
| 19 |
+
init_weight_decay = 0.0005
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
epochs = 200
|
| 23 |
+
lrate = 0.1
|
| 24 |
+
milestones = [60, 120, 180, 220]
|
| 25 |
+
lrate_decay = 0.1
|
| 26 |
+
batch_size = 32
|
| 27 |
+
weight_decay = 2e-4
|
| 28 |
+
num_workers = 2
|
| 29 |
+
T = 2
|
| 30 |
+
lamda = 3
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class LwF(BaseLearner):
|
| 34 |
+
def __init__(self, args):
|
| 35 |
+
super().__init__(args)
|
| 36 |
+
self._network = IncrementalNet(args, True)
|
| 37 |
+
self.writer = SummaryWriter(log_dir='runs/{}'.format(args['summary_file']))
|
| 38 |
+
|
| 39 |
+
def after_task(self):
|
| 40 |
+
self._old_network = self._network.copy().freeze()
|
| 41 |
+
self._known_classes = self._total_classes
|
| 42 |
+
|
| 43 |
+
def incremental_train(self, data_manager):
|
| 44 |
+
self.curr_acc = 0
|
| 45 |
+
self._cur_task += 1
|
| 46 |
+
self._total_classes = self._known_classes + data_manager.get_task_size(
|
| 47 |
+
self._cur_task
|
| 48 |
+
)
|
| 49 |
+
self._network.update_fc(self._total_classes)
|
| 50 |
+
logging.info(
|
| 51 |
+
"Learning on {}-{}".format(self._known_classes, self._total_classes)
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
train_dataset = data_manager.get_dataset(
|
| 55 |
+
np.arange(self._known_classes, self._total_classes),
|
| 56 |
+
source="train",
|
| 57 |
+
mode="train",
|
| 58 |
+
)
|
| 59 |
+
self.train_loader = DataLoader(
|
| 60 |
+
train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers
|
| 61 |
+
)
|
| 62 |
+
test_dataset = data_manager.get_dataset(
|
| 63 |
+
np.arange(0, self._total_classes), source="test", mode="test"
|
| 64 |
+
)
|
| 65 |
+
self.test_loader = DataLoader(
|
| 66 |
+
test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
if len(self._multiple_gpus) > 1:
|
| 70 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 71 |
+
self._train(self.train_loader, self.test_loader)
|
| 72 |
+
if len(self._multiple_gpus) > 1:
|
| 73 |
+
self._network = self._network.module
|
| 74 |
+
if self._total_classes == data_manager.get_total_classnum():
|
| 75 |
+
self.writer.close()
|
| 76 |
+
|
| 77 |
+
def _train(self, train_loader, test_loader):
|
| 78 |
+
self._network.to(self._device)
|
| 79 |
+
if self._old_network is not None:
|
| 80 |
+
self._old_network.to(self._device)
|
| 81 |
+
|
| 82 |
+
if self._cur_task == 0:
|
| 83 |
+
optimizer = optim.SGD(
|
| 84 |
+
self._network.parameters(),
|
| 85 |
+
momentum=0.9,
|
| 86 |
+
lr=init_lr,
|
| 87 |
+
weight_decay=init_weight_decay,
|
| 88 |
+
)
|
| 89 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 90 |
+
optimizer=optimizer, milestones=init_milestones, gamma=init_lr_decay
|
| 91 |
+
)
|
| 92 |
+
self._init_train(train_loader, test_loader, optimizer, scheduler)
|
| 93 |
+
else:
|
| 94 |
+
optimizer = optim.SGD(
|
| 95 |
+
self._network.parameters(),
|
| 96 |
+
lr=lrate,
|
| 97 |
+
momentum=0.9,
|
| 98 |
+
weight_decay=weight_decay,
|
| 99 |
+
)
|
| 100 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 101 |
+
optimizer=optimizer, milestones=milestones, gamma=lrate_decay
|
| 102 |
+
)
|
| 103 |
+
self._update_representation(train_loader, test_loader, optimizer, scheduler)
|
| 104 |
+
|
| 105 |
+
self.writer.add_figure("Confusion matrix",
|
| 106 |
+
self._createConfusionMatrix(self._network, self.test_loader),
|
| 107 |
+
self._cur_task)
|
| 108 |
+
self.writer.add_scalar('Accuracies', self.curr_acc, self._cur_task)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _init_train(self, train_loader, test_loader, optimizer, scheduler):
|
| 112 |
+
prog_bar = tqdm(range(init_epoch))
|
| 113 |
+
for _, epoch in enumerate(prog_bar):
|
| 114 |
+
self._network.train()
|
| 115 |
+
losses = 0.0
|
| 116 |
+
correct, total = 0, 0
|
| 117 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 118 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 119 |
+
logits = self._network(inputs)["logits"]
|
| 120 |
+
|
| 121 |
+
loss = F.cross_entropy(logits, targets)
|
| 122 |
+
optimizer.zero_grad()
|
| 123 |
+
loss.backward()
|
| 124 |
+
optimizer.step()
|
| 125 |
+
losses += loss.item()
|
| 126 |
+
|
| 127 |
+
_, preds = torch.max(logits, dim=1)
|
| 128 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 129 |
+
total += len(targets)
|
| 130 |
+
|
| 131 |
+
scheduler.step()
|
| 132 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 133 |
+
|
| 134 |
+
if epoch % 5 == 0:
|
| 135 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 136 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 137 |
+
self._cur_task,
|
| 138 |
+
epoch + 1,
|
| 139 |
+
init_epoch,
|
| 140 |
+
losses / len(train_loader),
|
| 141 |
+
train_acc,
|
| 142 |
+
test_acc,
|
| 143 |
+
)
|
| 144 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 145 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 146 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 147 |
+
else:
|
| 148 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 149 |
+
self._cur_task,
|
| 150 |
+
epoch + 1,
|
| 151 |
+
init_epoch,
|
| 152 |
+
losses / len(train_loader),
|
| 153 |
+
train_acc,
|
| 154 |
+
)
|
| 155 |
+
prog_bar.set_description(info)
|
| 156 |
+
|
| 157 |
+
logging.info(info)
|
| 158 |
+
|
| 159 |
+
def _update_representation(self, train_loader, test_loader, optimizer, scheduler):
|
| 160 |
+
|
| 161 |
+
prog_bar = tqdm(range(epochs))
|
| 162 |
+
for _, epoch in enumerate(prog_bar):
|
| 163 |
+
self._network.train()
|
| 164 |
+
losses = 0.0
|
| 165 |
+
correct, total = 0, 0
|
| 166 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 167 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 168 |
+
logits = self._network(inputs)["logits"]
|
| 169 |
+
|
| 170 |
+
fake_targets = targets - self._known_classes
|
| 171 |
+
loss_clf = F.cross_entropy(
|
| 172 |
+
logits[:, self._known_classes :], fake_targets
|
| 173 |
+
)
|
| 174 |
+
loss_kd = _KD_loss(
|
| 175 |
+
logits[:, : self._known_classes],
|
| 176 |
+
self._old_network(inputs)["logits"],
|
| 177 |
+
T,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
loss = lamda * loss_kd + loss_clf
|
| 181 |
+
|
| 182 |
+
optimizer.zero_grad()
|
| 183 |
+
loss.backward()
|
| 184 |
+
optimizer.step()
|
| 185 |
+
losses += loss.item()
|
| 186 |
+
|
| 187 |
+
with torch.no_grad():
|
| 188 |
+
_, preds = torch.max(logits, dim=1)
|
| 189 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 190 |
+
total += len(targets)
|
| 191 |
+
|
| 192 |
+
scheduler.step()
|
| 193 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 194 |
+
if epoch % 5 == 0:
|
| 195 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 196 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 197 |
+
self._cur_task,
|
| 198 |
+
epoch + 1,
|
| 199 |
+
epochs,
|
| 200 |
+
losses / len(train_loader),
|
| 201 |
+
train_acc,
|
| 202 |
+
test_acc,
|
| 203 |
+
)
|
| 204 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 205 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 206 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 207 |
+
else:
|
| 208 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 209 |
+
self._cur_task,
|
| 210 |
+
epoch + 1,
|
| 211 |
+
epochs,
|
| 212 |
+
losses / len(train_loader),
|
| 213 |
+
train_acc,
|
| 214 |
+
)
|
| 215 |
+
prog_bar.set_description(info)
|
| 216 |
+
logging.info(info)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _KD_loss(pred, soft, T):
|
| 220 |
+
pred = torch.log_softmax(pred / T, dim=1)
|
| 221 |
+
soft = torch.softmax(soft / T, dim=1)
|
| 222 |
+
return -1 * torch.mul(soft, pred).sum() / pred.shape[0]
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
import copy
|
| 7 |
+
from torch import optim
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
from torch.utils.data import DataLoader
|
| 10 |
+
from models.base import BaseLearner
|
| 11 |
+
from utils.inc_net import AdaptiveNet
|
| 12 |
+
from utils.toolkit import count_parameters, target2onehot, tensor2numpy
|
| 13 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 14 |
+
|
| 15 |
+
num_workers=2
|
| 16 |
+
EPSILON = 1e-8
|
| 17 |
+
batch_size = 64
|
| 18 |
+
|
| 19 |
+
class MEMO(BaseLearner):
|
| 20 |
+
|
| 21 |
+
def __init__(self, args):
|
| 22 |
+
super().__init__(args)
|
| 23 |
+
self.args = args
|
| 24 |
+
self._old_base = None
|
| 25 |
+
self.args.update({'curr': self._cur_task})
|
| 26 |
+
self._network = AdaptiveNet(args, True)
|
| 27 |
+
logging.info(f'>>> train generalized blocks:{self.args["train_base"]} train_adaptive:{self.args["train_adaptive"]}')
|
| 28 |
+
self.writer = SummaryWriter(log_dir='DARCY-runs/{}'.format(args['summary_file']))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def after_task(self):
|
| 32 |
+
self._known_classes = self._total_classes
|
| 33 |
+
if self._cur_task == 0:
|
| 34 |
+
if self.args['train_base']:
|
| 35 |
+
logging.info("Train Generalized Blocks...")
|
| 36 |
+
self._network.TaskAgnosticExtractor.train()
|
| 37 |
+
for param in self._network.TaskAgnosticExtractor.parameters():
|
| 38 |
+
param.requires_grad = True
|
| 39 |
+
else:
|
| 40 |
+
logging.info("Fix Generalized Blocks...")
|
| 41 |
+
self._network.TaskAgnosticExtractor.eval()
|
| 42 |
+
for param in self._network.TaskAgnosticExtractor.parameters():
|
| 43 |
+
param.requires_grad = False
|
| 44 |
+
|
| 45 |
+
logging.info('Exemplar size: {}'.format(self.exemplar_size))
|
| 46 |
+
|
| 47 |
+
def incremental_train(self, data_manager):
|
| 48 |
+
self._cur_task += 1
|
| 49 |
+
self._total_classes = self._known_classes + data_manager.get_task_size(self._cur_task)
|
| 50 |
+
self.args.update({'curr': self._cur_task})
|
| 51 |
+
self._network.update_fc(self._total_classes)
|
| 52 |
+
logging.info("****MODEL ARCHITECTURE after fc update*****")
|
| 53 |
+
logging.info(self._network)
|
| 54 |
+
logging.info('Learning on {}-{}'.format(self._known_classes, self._total_classes))
|
| 55 |
+
logging.info(
|
| 56 |
+
"Known_classes: {}\tTotal_classes: {}\tcurrent_task: {}".format(self._known_classes, self._total_classes, self._cur_task)
|
| 57 |
+
)
|
| 58 |
+
if self._cur_task>0: # Freeze the network of the previous trained adaptive network (requires grad = False)
|
| 59 |
+
logging.info("self._curr_task {} and no of adaptiveExtractors {}".format(self._cur_task, len(self._network.AdaptiveExtractors)))
|
| 60 |
+
for i in range(self._cur_task):
|
| 61 |
+
for p in self._network.AdaptiveExtractors[i].parameters():
|
| 62 |
+
if self.args['train_adaptive']:
|
| 63 |
+
p.requires_grad = True
|
| 64 |
+
else:
|
| 65 |
+
p.requires_grad = False
|
| 66 |
+
|
| 67 |
+
if self.args["type"] == "avg":
|
| 68 |
+
break
|
| 69 |
+
|
| 70 |
+
logging.debug('All params: {}'.format(count_parameters(self._network)))
|
| 71 |
+
logging.debug('Trainable params: {}'.format(count_parameters(self._network, True)))
|
| 72 |
+
_, tr_targets, train_dataset = data_manager.get_dataset(
|
| 73 |
+
np.arange(self._known_classes, self._total_classes),
|
| 74 |
+
source='train',
|
| 75 |
+
mode='train',
|
| 76 |
+
appendent=self._get_memory(),
|
| 77 |
+
ret_data=True
|
| 78 |
+
)
|
| 79 |
+
self.train_loader = DataLoader(
|
| 80 |
+
train_dataset,
|
| 81 |
+
batch_size=self.args["batch_size"],
|
| 82 |
+
shuffle=True,
|
| 83 |
+
num_workers=num_workers
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
_, te_targets, test_dataset = data_manager.get_dataset(
|
| 87 |
+
np.arange(0, self._total_classes),
|
| 88 |
+
source='test',
|
| 89 |
+
mode='test',
|
| 90 |
+
ret_data=True
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
self.test_loader = DataLoader(
|
| 94 |
+
test_dataset,
|
| 95 |
+
batch_size=self.args["batch_size"],
|
| 96 |
+
shuffle=False,
|
| 97 |
+
num_workers=num_workers
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if len(self._multiple_gpus) > 1:
|
| 101 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 102 |
+
self._train(self.train_loader, self.test_loader)
|
| 103 |
+
self.build_rehearsal_memory(data_manager, self.samples_per_class)
|
| 104 |
+
if len(self._multiple_gpus) > 1:
|
| 105 |
+
self._network = self._network.module
|
| 106 |
+
|
| 107 |
+
def set_network(self):
|
| 108 |
+
if len(self._multiple_gpus) > 1:
|
| 109 |
+
self._network = self._network.module
|
| 110 |
+
self._network.train() #All status from eval to train
|
| 111 |
+
if self.args['train_base']:
|
| 112 |
+
self._network.TaskAgnosticExtractor.train()
|
| 113 |
+
else:
|
| 114 |
+
self._network.TaskAgnosticExtractor.eval()
|
| 115 |
+
|
| 116 |
+
# set adaptive extractor's status
|
| 117 |
+
self._network.AdaptiveExtractors[-1].train()
|
| 118 |
+
if self._cur_task >= 1:
|
| 119 |
+
for i in range(self._cur_task):
|
| 120 |
+
if self.args['train_adaptive']:
|
| 121 |
+
self._network.AdaptiveExtractors[i].train()
|
| 122 |
+
else:
|
| 123 |
+
self._network.AdaptiveExtractors[i].eval()
|
| 124 |
+
if self.args["type"] == "avg":
|
| 125 |
+
break
|
| 126 |
+
|
| 127 |
+
if len(self._multiple_gpus) > 1:
|
| 128 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 129 |
+
|
| 130 |
+
def _train(self, train_loader, test_loader):
|
| 131 |
+
self._network.to(self._device)
|
| 132 |
+
if self._cur_task==0:
|
| 133 |
+
logging.debug('## Initial Training ##')
|
| 134 |
+
optimizer = optim.SGD(
|
| 135 |
+
filter(lambda p: p.requires_grad, self._network.parameters()),
|
| 136 |
+
momentum=0.9,
|
| 137 |
+
lr=self.args["init_lr"],
|
| 138 |
+
weight_decay=self.args["init_weight_decay"]
|
| 139 |
+
)
|
| 140 |
+
if self.args['scheduler'] == 'steplr':
|
| 141 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 142 |
+
optimizer=optimizer,
|
| 143 |
+
milestones=self.args['init_milestones'],
|
| 144 |
+
gamma=self.args['init_lr_decay']
|
| 145 |
+
)
|
| 146 |
+
elif self.args['scheduler'] == 'cosine':
|
| 147 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(
|
| 148 |
+
optimizer=optimizer,
|
| 149 |
+
T_max=self.args['init_epoch']
|
| 150 |
+
)
|
| 151 |
+
else:
|
| 152 |
+
raise NotImplementedError
|
| 153 |
+
|
| 154 |
+
if not self.args['skip']:
|
| 155 |
+
self._init_train(train_loader, test_loader, optimizer, scheduler)
|
| 156 |
+
else:
|
| 157 |
+
if isinstance(self._network, nn.DataParallel):
|
| 158 |
+
self._network = self._network.module
|
| 159 |
+
load_acc = self._network.load_checkpoint(self.args)
|
| 160 |
+
self._network.to(self._device)
|
| 161 |
+
|
| 162 |
+
if len(self._multiple_gpus) > 1:
|
| 163 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 164 |
+
|
| 165 |
+
cur_test_acc = self._compute_accuracy(self._network, self.test_loader)
|
| 166 |
+
logging.info(f"Loaded_Test_Acc:{load_acc} Cur_Test_Acc:{cur_test_acc}")
|
| 167 |
+
else:
|
| 168 |
+
optimizer = optim.SGD(
|
| 169 |
+
filter(lambda p: p.requires_grad, self._network.parameters()),
|
| 170 |
+
lr=self.args['lrate'],
|
| 171 |
+
momentum=0.9,
|
| 172 |
+
weight_decay=self.args['weight_decay']
|
| 173 |
+
)
|
| 174 |
+
if self.args['scheduler'] == 'steplr':
|
| 175 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 176 |
+
optimizer=optimizer,
|
| 177 |
+
milestones=self.args['milestones'],
|
| 178 |
+
gamma=self.args['lrate_decay']
|
| 179 |
+
)
|
| 180 |
+
elif self.args['scheduler'] == 'cosine':
|
| 181 |
+
assert self.args['t_max'] is not None
|
| 182 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(
|
| 183 |
+
optimizer=optimizer,
|
| 184 |
+
T_max=self.args['t_max']
|
| 185 |
+
)
|
| 186 |
+
else:
|
| 187 |
+
raise NotImplementedError
|
| 188 |
+
self._update_representation(train_loader, test_loader, optimizer, scheduler)
|
| 189 |
+
if len(self._multiple_gpus) > 1:
|
| 190 |
+
self._network.module.weight_align(self._total_classes-self._known_classes)
|
| 191 |
+
else:
|
| 192 |
+
self._network.weight_align(self._total_classes-self._known_classes)
|
| 193 |
+
|
| 194 |
+
self.writer.add_figure("Confusion matrix",
|
| 195 |
+
self._createConfusionMatrix(self._network, self.test_loader),
|
| 196 |
+
self._cur_task)
|
| 197 |
+
self.writer.add_scalar('Accuracies', self.curr_acc, self._cur_task)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _test_model(self, test_loader, epoch):
|
| 201 |
+
self._network.eval()
|
| 202 |
+
losses = 0.
|
| 203 |
+
|
| 204 |
+
for i, (_, inputs, targets) in enumerate(test_loader):
|
| 205 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 206 |
+
outputs = self._network(inputs)
|
| 207 |
+
logits = outputs["logits"]
|
| 208 |
+
loss_clf = F.cross_entropy(logits, targets)
|
| 209 |
+
loss= loss_clf
|
| 210 |
+
losses += loss.item()
|
| 211 |
+
self.writer.add_scalar('Task: {} on {}-{} -- test/Loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 212 |
+
losses / len(test_loader), epoch)
|
| 213 |
+
|
| 214 |
+
def _init_train(self,train_loader, test_loader, optimizer, scheduler):
|
| 215 |
+
prog_bar = tqdm(range(self.args["init_epoch"]))
|
| 216 |
+
for _, epoch in enumerate(prog_bar):
|
| 217 |
+
self._network.train()
|
| 218 |
+
losses = 0.
|
| 219 |
+
correct, total = 0, 0
|
| 220 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 221 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 222 |
+
logits = self._network(inputs)['logits']
|
| 223 |
+
|
| 224 |
+
loss=F.cross_entropy(logits,targets)
|
| 225 |
+
optimizer.zero_grad()
|
| 226 |
+
loss.backward()
|
| 227 |
+
optimizer.step()
|
| 228 |
+
losses += loss.item()
|
| 229 |
+
|
| 230 |
+
_, preds = torch.max(logits, dim=1)
|
| 231 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 232 |
+
total += len(targets)
|
| 233 |
+
|
| 234 |
+
scheduler.step()
|
| 235 |
+
train_acc = np.around(tensor2numpy(correct)*100 / total, decimals=2)
|
| 236 |
+
if epoch%5==0:
|
| 237 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 238 |
+
self._test_model(test_loader=test_loader, epoch=epoch)
|
| 239 |
+
info = 'Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}'.format(
|
| 240 |
+
self._cur_task, epoch+1, self.args['init_epoch'], losses/len(train_loader), train_acc, test_acc)
|
| 241 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/Loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 242 |
+
losses / len(train_loader), epoch)
|
| 243 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy train'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 244 |
+
train_acc, epoch)
|
| 245 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy test'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 246 |
+
test_acc, epoch)
|
| 247 |
+
else:
|
| 248 |
+
info = 'Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}'.format(
|
| 249 |
+
self._cur_task,
|
| 250 |
+
epoch + 1,
|
| 251 |
+
self.args['init_epoch'],
|
| 252 |
+
losses/len(train_loader),
|
| 253 |
+
train_acc)
|
| 254 |
+
prog_bar.set_description(info)
|
| 255 |
+
logging.info(info)
|
| 256 |
+
|
| 257 |
+
def _update_representation(self, train_loader, test_loader, optimizer, scheduler):
|
| 258 |
+
prog_bar = tqdm(range(self.args["epochs"]))
|
| 259 |
+
for _, epoch in enumerate(prog_bar):
|
| 260 |
+
self.set_network()
|
| 261 |
+
losses = 0.
|
| 262 |
+
losses_clf=0.
|
| 263 |
+
losses_aux=0.
|
| 264 |
+
correct, total = 0, 0
|
| 265 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 266 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 267 |
+
|
| 268 |
+
outputs= self._network(inputs)
|
| 269 |
+
logits,aux_logits=outputs["logits"],outputs["aux_logits"]
|
| 270 |
+
loss_clf=F.cross_entropy(logits,targets)
|
| 271 |
+
aux_targets = targets.clone()
|
| 272 |
+
aux_targets=torch.where(aux_targets-self._known_classes+1>0, aux_targets-self._known_classes+1,0)
|
| 273 |
+
loss_aux=F.cross_entropy(aux_logits,aux_targets)
|
| 274 |
+
loss=loss_clf+self.args['alpha_aux']*loss_aux
|
| 275 |
+
|
| 276 |
+
optimizer.zero_grad()
|
| 277 |
+
loss.backward()
|
| 278 |
+
optimizer.step()
|
| 279 |
+
losses += loss.item()
|
| 280 |
+
losses_aux+=loss_aux.item()
|
| 281 |
+
losses_clf+=loss_clf.item()
|
| 282 |
+
|
| 283 |
+
_, preds = torch.max(logits, dim=1)
|
| 284 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 285 |
+
total += len(targets)
|
| 286 |
+
|
| 287 |
+
scheduler.step()
|
| 288 |
+
train_acc = np.around(tensor2numpy(correct)*100 / total, decimals=2)
|
| 289 |
+
if epoch % 5 == 0:
|
| 290 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 291 |
+
self._test_model(test_loader=test_loader, epoch=epoch)
|
| 292 |
+
info = 'Task {}, Epoch {}/{} => Loss {:.3f}, Loss_clf {:.3f}, Loss_aux {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}'.format(
|
| 293 |
+
self._cur_task, epoch+1, self.args["epochs"], losses/len(train_loader),losses_clf/len(train_loader),losses_aux/len(train_loader),train_acc, test_acc)
|
| 294 |
+
|
| 295 |
+
self.writer.add_scalar('Task: {} on {}-{} -- train/Loss'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 296 |
+
losses / len(train_loader), epoch)
|
| 297 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy train'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 298 |
+
train_acc, epoch)
|
| 299 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Accuracy test'.format(self._cur_task, self._known_classes, self._total_classes),
|
| 300 |
+
test_acc, epoch)
|
| 301 |
+
else:
|
| 302 |
+
info = 'Task {}, Epoch {}/{} => Loss {:.3f}, Loss_clf {:.3f}, Loss_aux {:.3f}, Train_accy {:.2f}'.format(
|
| 303 |
+
self._cur_task,
|
| 304 |
+
epoch + 1,
|
| 305 |
+
self.args["epochs"],
|
| 306 |
+
losses/len(train_loader),
|
| 307 |
+
losses_clf/len(train_loader),
|
| 308 |
+
losses_aux/len(train_loader),
|
| 309 |
+
train_acc)
|
| 310 |
+
|
| 311 |
+
prog_bar.set_description(info)
|
| 312 |
+
logging.info(info)
|
| 313 |
+
|
| 314 |
+
def _construct_exemplar(self, data_manager, m):
|
| 315 |
+
logging.info("Constructing exemplars...({} per classes)".format(m))
|
| 316 |
+
for class_idx in range(self._known_classes, self._total_classes):
|
| 317 |
+
data, targets, idx_dataset = data_manager.get_dataset(
|
| 318 |
+
np.arange(class_idx, class_idx + 1),
|
| 319 |
+
source="train",
|
| 320 |
+
mode="test",
|
| 321 |
+
ret_data=True,
|
| 322 |
+
)
|
| 323 |
+
idx_loader = DataLoader(
|
| 324 |
+
idx_dataset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 325 |
+
)
|
| 326 |
+
vectors, _ = self._extract_vectors(idx_loader)
|
| 327 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 328 |
+
class_mean = np.mean(vectors, axis=0)
|
| 329 |
+
|
| 330 |
+
# Select
|
| 331 |
+
selected_exemplars = []
|
| 332 |
+
exemplar_vectors = [] # [n, feature_dim]
|
| 333 |
+
for k in range(1, m + 1):
|
| 334 |
+
S = np.sum(
|
| 335 |
+
exemplar_vectors, axis=0
|
| 336 |
+
) # [feature_dim] sum of selected exemplars vectors
|
| 337 |
+
mu_p = (vectors + S) / k # [n, feature_dim] sum to all vectors
|
| 338 |
+
i = np.argmin(np.sqrt(np.sum((class_mean - mu_p) ** 2, axis=1)))
|
| 339 |
+
selected_exemplars.append(
|
| 340 |
+
np.array(data[i])
|
| 341 |
+
) # New object to avoid passing by inference
|
| 342 |
+
exemplar_vectors.append(
|
| 343 |
+
np.array(vectors[i])
|
| 344 |
+
) # New object to avoid passing by inference
|
| 345 |
+
|
| 346 |
+
vectors = np.delete(
|
| 347 |
+
vectors, i, axis=0
|
| 348 |
+
) # Remove it to avoid duplicative selection
|
| 349 |
+
data = np.delete(
|
| 350 |
+
data, i, axis=0
|
| 351 |
+
) # Remove it to avoid duplicative selection
|
| 352 |
+
|
| 353 |
+
if len(vectors) == 0:
|
| 354 |
+
break
|
| 355 |
+
# uniques = np.unique(selected_exemplars, axis=0)
|
| 356 |
+
# print('Unique elements: {}'.format(len(uniques)))
|
| 357 |
+
selected_exemplars = np.array(selected_exemplars)
|
| 358 |
+
# exemplar_targets = np.full(m, class_idx)
|
| 359 |
+
exemplar_targets = np.full(selected_exemplars.shape[0], class_idx)
|
| 360 |
+
self._data_memory = (
|
| 361 |
+
np.concatenate((self._data_memory, selected_exemplars))
|
| 362 |
+
if len(self._data_memory) != 0
|
| 363 |
+
else selected_exemplars
|
| 364 |
+
)
|
| 365 |
+
self._targets_memory = (
|
| 366 |
+
np.concatenate((self._targets_memory, exemplar_targets))
|
| 367 |
+
if len(self._targets_memory) != 0
|
| 368 |
+
else exemplar_targets
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
# Exemplar mean
|
| 372 |
+
idx_dataset = data_manager.get_dataset(
|
| 373 |
+
[],
|
| 374 |
+
source="train",
|
| 375 |
+
mode="test",
|
| 376 |
+
appendent=(selected_exemplars, exemplar_targets),
|
| 377 |
+
)
|
| 378 |
+
idx_loader = DataLoader(
|
| 379 |
+
idx_dataset, batch_size=batch_size, shuffle=False, num_workers=4
|
| 380 |
+
)
|
| 381 |
+
vectors, _ = self._extract_vectors(idx_loader)
|
| 382 |
+
vectors = (vectors.T / (np.linalg.norm(vectors.T, axis=0) + EPSILON)).T
|
| 383 |
+
mean = np.mean(vectors, axis=0)
|
| 384 |
+
mean = mean / np.linalg.norm(mean)
|
| 385 |
+
|
| 386 |
+
self._class_means[class_idx, :] = mean
|
models/replay.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch import optim
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
from torch.utils.data import DataLoader
|
| 9 |
+
from models.base import BaseLearner
|
| 10 |
+
from utils.inc_net import IncrementalNet
|
| 11 |
+
from utils.toolkit import target2onehot, tensor2numpy
|
| 12 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 13 |
+
|
| 14 |
+
EPSILON = 1e-8
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
init_epoch = 200
|
| 18 |
+
init_lr = 0.1
|
| 19 |
+
init_milestones = [60, 120, 170]
|
| 20 |
+
init_lr_decay = 0.1
|
| 21 |
+
init_weight_decay = 0.0005
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
epochs = 200
|
| 25 |
+
lrate = 0.1
|
| 26 |
+
milestones = [30, 50]
|
| 27 |
+
lrate_decay = 0.1
|
| 28 |
+
batch_size = 128
|
| 29 |
+
weight_decay = 2e-4
|
| 30 |
+
num_workers = 2
|
| 31 |
+
T = 2
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Replay(BaseLearner):
|
| 35 |
+
def __init__(self, args):
|
| 36 |
+
super().__init__(args)
|
| 37 |
+
self._network = IncrementalNet(args, True)
|
| 38 |
+
self.writer = SummaryWriter(log_dir='runs/{}'.format(args['summary_file']))
|
| 39 |
+
|
| 40 |
+
def after_task(self):
|
| 41 |
+
self._known_classes = self._total_classes
|
| 42 |
+
logging.info("Exemplar size: {}".format(self.exemplar_size))
|
| 43 |
+
|
| 44 |
+
def incremental_train(self, data_manager):
|
| 45 |
+
self.curr_acc = 0
|
| 46 |
+
self._cur_task += 1
|
| 47 |
+
self._total_classes = self._known_classes + data_manager.get_task_size(
|
| 48 |
+
self._cur_task
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
self._network.update_fc(self._total_classes)
|
| 52 |
+
logging.info(
|
| 53 |
+
"Learning on {}-{}".format(self._known_classes, self._total_classes)
|
| 54 |
+
)
|
| 55 |
+
logging.info(
|
| 56 |
+
"Known_classes: {}\tTotal_classes: {}\tcurrent_task: {}".format(self._known_classes, self._total_classes, self._cur_task)
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# Loader
|
| 60 |
+
_, tr_targets, train_dataset = data_manager.get_dataset(
|
| 61 |
+
np.arange(self._known_classes, self._total_classes),
|
| 62 |
+
source="train",
|
| 63 |
+
mode="train",
|
| 64 |
+
appendent=self._get_memory(),
|
| 65 |
+
ret_data=True
|
| 66 |
+
)
|
| 67 |
+
self.train_loader = DataLoader(
|
| 68 |
+
train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers
|
| 69 |
+
)
|
| 70 |
+
_, te_targets, test_dataset = data_manager.get_dataset(
|
| 71 |
+
np.arange(0, self._total_classes), source="test", mode="test", ret_data=True
|
| 72 |
+
)
|
| 73 |
+
self.test_loader = DataLoader(
|
| 74 |
+
test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# Procedure
|
| 78 |
+
if len(self._multiple_gpus) > 1:
|
| 79 |
+
self._network = nn.DataParallel(self._network, self._multiple_gpus)
|
| 80 |
+
self._train(self.train_loader, self.test_loader)
|
| 81 |
+
|
| 82 |
+
self.build_rehearsal_memory(data_manager, self.samples_per_class)
|
| 83 |
+
if len(self._multiple_gpus) > 1:
|
| 84 |
+
self._network = self._network.module
|
| 85 |
+
|
| 86 |
+
def _train(self, train_loader, test_loader):
|
| 87 |
+
self._network.to(self._device)
|
| 88 |
+
if self._cur_task == 0:
|
| 89 |
+
optimizer = optim.SGD(
|
| 90 |
+
self._network.parameters(),
|
| 91 |
+
momentum=0.9,
|
| 92 |
+
lr=init_lr,
|
| 93 |
+
weight_decay=init_weight_decay,
|
| 94 |
+
)
|
| 95 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 96 |
+
optimizer=optimizer, milestones=init_milestones, gamma=init_lr_decay
|
| 97 |
+
)
|
| 98 |
+
logging.info('## Initial Training ##')
|
| 99 |
+
self._init_train(train_loader, test_loader, optimizer, scheduler)
|
| 100 |
+
else:
|
| 101 |
+
optimizer = optim.SGD(
|
| 102 |
+
self._network.parameters(),
|
| 103 |
+
lr=lrate,
|
| 104 |
+
momentum=0.9,
|
| 105 |
+
weight_decay=weight_decay,
|
| 106 |
+
) # 1e-5
|
| 107 |
+
scheduler = optim.lr_scheduler.MultiStepLR(
|
| 108 |
+
optimizer=optimizer, milestones=milestones, gamma=lrate_decay
|
| 109 |
+
)
|
| 110 |
+
self._update_representation(train_loader, test_loader, optimizer, scheduler)
|
| 111 |
+
|
| 112 |
+
self.writer.add_figure("Confusion matrix",
|
| 113 |
+
self._createConfusionMatrix(self._network, self.test_loader),
|
| 114 |
+
self._cur_task)
|
| 115 |
+
self.writer.add_scalar('Accuracies', self.curr_acc, self._cur_task)
|
| 116 |
+
|
| 117 |
+
def _init_train(self, train_loader, test_loader, optimizer, scheduler):
|
| 118 |
+
prog_bar = tqdm(range(init_epoch))
|
| 119 |
+
for _, epoch in enumerate(prog_bar):
|
| 120 |
+
self._network.train()
|
| 121 |
+
losses = 0.0
|
| 122 |
+
correct, total = 0, 0
|
| 123 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 124 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 125 |
+
logits = self._network(inputs)["logits"]
|
| 126 |
+
|
| 127 |
+
loss = F.cross_entropy(logits, targets)
|
| 128 |
+
optimizer.zero_grad()
|
| 129 |
+
loss.backward()
|
| 130 |
+
optimizer.step()
|
| 131 |
+
losses += loss.item()
|
| 132 |
+
|
| 133 |
+
_, preds = torch.max(logits, dim=1)
|
| 134 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 135 |
+
total += len(targets)
|
| 136 |
+
|
| 137 |
+
scheduler.step()
|
| 138 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 139 |
+
|
| 140 |
+
if epoch % 5 == 0:
|
| 141 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 142 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 143 |
+
self._cur_task,
|
| 144 |
+
epoch + 1,
|
| 145 |
+
init_epoch,
|
| 146 |
+
losses / len(train_loader),
|
| 147 |
+
train_acc,
|
| 148 |
+
test_acc,
|
| 149 |
+
)
|
| 150 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 151 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 152 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 153 |
+
else:
|
| 154 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 155 |
+
self._cur_task,
|
| 156 |
+
epoch + 1,
|
| 157 |
+
init_epoch,
|
| 158 |
+
losses / len(train_loader),
|
| 159 |
+
train_acc,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
prog_bar.set_description(info)
|
| 163 |
+
|
| 164 |
+
logging.info(info)
|
| 165 |
+
|
| 166 |
+
def _update_representation(self, train_loader, test_loader, optimizer, scheduler):
|
| 167 |
+
prog_bar = tqdm(range(epochs))
|
| 168 |
+
for _, epoch in enumerate(prog_bar):
|
| 169 |
+
self._network.train()
|
| 170 |
+
losses = 0.0
|
| 171 |
+
correct, total = 0, 0
|
| 172 |
+
for i, (_, inputs, targets) in enumerate(train_loader):
|
| 173 |
+
inputs, targets = inputs.to(self._device), targets.to(self._device)
|
| 174 |
+
logits = self._network(inputs)["logits"]
|
| 175 |
+
|
| 176 |
+
loss_clf = F.cross_entropy(logits, targets)
|
| 177 |
+
loss = loss_clf
|
| 178 |
+
|
| 179 |
+
optimizer.zero_grad()
|
| 180 |
+
loss.backward()
|
| 181 |
+
optimizer.step()
|
| 182 |
+
losses += loss.item()
|
| 183 |
+
|
| 184 |
+
# acc
|
| 185 |
+
_, preds = torch.max(logits, dim=1)
|
| 186 |
+
correct += preds.eq(targets.expand_as(preds)).cpu().sum()
|
| 187 |
+
total += len(targets)
|
| 188 |
+
|
| 189 |
+
scheduler.step()
|
| 190 |
+
train_acc = np.around(tensor2numpy(correct) * 100 / total, decimals=2)
|
| 191 |
+
if epoch % 5 == 0:
|
| 192 |
+
test_acc = self._compute_accuracy(self._network, test_loader)
|
| 193 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}, Test_accy {:.2f}".format(
|
| 194 |
+
self._cur_task,
|
| 195 |
+
epoch + 1,
|
| 196 |
+
epochs,
|
| 197 |
+
losses / len(train_loader),
|
| 198 |
+
train_acc,
|
| 199 |
+
test_acc,
|
| 200 |
+
)
|
| 201 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Loss'.format(self._cur_task, self._known_classes, self._total_classes), losses / len(train_loader), epoch)
|
| 202 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Train/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), train_acc, epoch)
|
| 203 |
+
self.writer.add_scalar('Task: {} on {}-{} -- Test/Accuracy'.format(self._cur_task, self._known_classes, self._total_classes), test_acc, epoch)
|
| 204 |
+
else:
|
| 205 |
+
info = "Task {}, Epoch {}/{} => Loss {:.3f}, Train_accy {:.2f}".format(
|
| 206 |
+
self._cur_task,
|
| 207 |
+
epoch + 1,
|
| 208 |
+
epochs,
|
| 209 |
+
losses / len(train_loader),
|
| 210 |
+
train_ac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
import copy
|
| 4 |
+
import torch
|
| 5 |
+
from utils import factory
|
| 6 |
+
from utils.data_manager import DataManager
|
| 7 |
+
from utils.toolkit import count_parameters
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def train(args):
|
| 12 |
+
"""
|
| 13 |
+
Entry point for training the model.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
args (dict): Configuration arguments including model settings, dataset info, device, seed list, etc.
|
| 17 |
+
"""
|
| 18 |
+
seed_list = copy.deepcopy(args["seed"])
|
| 19 |
+
device = copy.deepcopy(args["device"])
|
| 20 |
+
|
| 21 |
+
for seed in seed_list:
|
| 22 |
+
args["seed"] = seed
|
| 23 |
+
args["device"] = device
|
| 24 |
+
_train(args)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _train(args):
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
Main training function to handle incremental learning across tasks.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
args (dict): Configuration arguments including model settings, dataset info, etc.
|
| 34 |
+
"""
|
| 35 |
+
# Initialize class counter
|
| 36 |
+
init_cls = 0 if args ["init_cls"] == args["increment"] else args["init_cls"]
|
| 37 |
+
logs_name = "logs/{}/{}".format(args["model_name"],args["dataset"])
|
| 38 |
+
|
| 39 |
+
if not os.path.exists(logs_name):
|
| 40 |
+
os.makedirs(logs_name)
|
| 41 |
+
|
| 42 |
+
if not os.path.exists("predictions"):
|
| 43 |
+
os.makedirs("predictions")
|
| 44 |
+
|
| 45 |
+
logfilename = "logs/{}/{}/{}_{}_{}".format(
|
| 46 |
+
args["model_name"],
|
| 47 |
+
args["dataset"],
|
| 48 |
+
args["convnet_type"],
|
| 49 |
+
args["seed"],
|
| 50 |
+
args["summary_file"]
|
| 51 |
+
)
|
| 52 |
+
logging.basicConfig(
|
| 53 |
+
level=logging.INFO,
|
| 54 |
+
format="[%(asctime)s: %(filename)s: %(lineno)d: %(funcName)s]=> %(message)s",
|
| 55 |
+
handlers=[
|
| 56 |
+
logging.FileHandler(filename=logfilename + ".log", mode="w"),
|
| 57 |
+
logging.StreamHandler(sys.stdout),
|
| 58 |
+
],
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
_set_random()
|
| 62 |
+
_set_device(args)
|
| 63 |
+
|
| 64 |
+
# Initialize data manager for handling datasets
|
| 65 |
+
data_manager = DataManager(
|
| 66 |
+
args["dataset"],
|
| 67 |
+
args["shuffle"],
|
| 68 |
+
args["seed"],
|
| 69 |
+
args["init_cls"],
|
| 70 |
+
args["increment"],
|
| 71 |
+
)
|
| 72 |
+
model = factory.get_model(args["model_name"], args)
|
| 73 |
+
|
| 74 |
+
# Initialize accuracy tracking variables
|
| 75 |
+
cnn_curve, nme_curve = {"top1": [], "top3": []}, {"top1": [], "top3": []}
|
| 76 |
+
|
| 77 |
+
logging.info("nb_tasks: {}".format(data_manager.nb_tasks))
|
| 78 |
+
for task in range(data_manager.nb_tasks):
|
| 79 |
+
|
| 80 |
+
model.incremental_train(data_manager)
|
| 81 |
+
cnn_accy, nme_accy = model.eval_task()
|
| 82 |
+
model.after_task()
|
| 83 |
+
|
| 84 |
+
if nme_accy is not None:
|
| 85 |
+
logging.info("CNN: {}".format(cnn_accy["grouped"]))
|
| 86 |
+
logging.info("NME: {}".format(nme_accy["grouped"]))
|
| 87 |
+
|
| 88 |
+
cnn_curve["top1"].append(cnn_accy["top1"])
|
| 89 |
+
cnn_curve["top3"].append(cnn_accy["top3"])
|
| 90 |
+
|
| 91 |
+
nme_curve["top1"].append(nme_accy["top1"])
|
| 92 |
+
nme_curve["top3"].append(nme_accy["top3"])
|
| 93 |
+
|
| 94 |
+
logging.info("CNN top1 curve: {}".format(cnn_curve["top1"]))
|
| 95 |
+
logging.info("CNN top3 curve: {}".format(cnn_curve["top3"]))
|
| 96 |
+
logging.info("NME top1 curve: {}".format(nme_curve["top1"]))
|
| 97 |
+
logging.info("NME top3 curve: {}\n".format(nme_curve["top3"]))
|
| 98 |
+
|
| 99 |
+
print('Average Accuracy (CNN):', sum(cnn_curve["top1"])/len(cnn_curve["top1"]))
|
| 100 |
+
print('Average Accuracy (NME):', sum(nme_curve["top1"])/len(nme_curve["top1"]))
|
| 101 |
+
|
| 102 |
+
logging.info("Average Accuracy (CNN): {}".format(sum(cnn_curve["top1"])/len(cnn_curve["top1"])))
|
| 103 |
+
logging.info("Average Accuracy (NME): {}".format(sum(nme_curve["top1"])/len(nme_curve["top1"])))
|
| 104 |
+
else:
|
| 105 |
+
logging.info("No NME accuracy.")
|
| 106 |
+
logging.info("CNN: {}".format(cnn_accy["grouped"]))
|
| 107 |
+
|
| 108 |
+
cnn_curve["top1"].append(cnn_accy["top1"])
|
| 109 |
+
cnn_curve["top3"].append(cnn_accy["top3"])
|
| 110 |
+
|
| 111 |
+
logging.info("CNN top1 curve: {}".format(cnn_curve["top1"]))
|
| 112 |
+
logging.info("CNN top3 curve: {}\n".format(cnn_curve["top3"]))
|
| 113 |
+
|
| 114 |
+
print('Average Accuracy (CNN):', sum(cnn_curve["top1"])/len(cnn_curve["top1"]))
|
| 115 |
+
logging.info("Average Accuracy (CNN): {}".format(sum(cnn_curve["top1"])/len(cnn_curve["top1"])))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _set_device(args):
|
| 119 |
+
"""
|
| 120 |
+
Configure device settings for the model (CPU or GPU).
|
| 121 |
+
|
| 122 |
+
Args:
|
| 123 |
+
args (dict): Configuration arguments including device settings.
|
| 124 |
+
"""
|
| 125 |
+
device_type = args["device"]
|
| 126 |
+
gpus = []
|
| 127 |
+
|
| 128 |
+
for device in device_type:
|
| 129 |
+
if device_type == -1:
|
| 130 |
+
device = torch.device("cpu")
|
| 131 |
+
else:
|
| 132 |
+
device = torch.device("cuda:{}".format(device))
|
| 133 |
+
|
| 134 |
+
gpus.append(device)
|
| 135 |
+
|
| 136 |
+
args["device"] = gpus
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _set_random():
|
| 140 |
+
torch.manual_seed(1)
|
| 141 |
+
torch.cuda.manual_seed(1)
|
| 142 |
+
torch.cuda.manual_seed_all(1)
|
| 143 |
+
torch.backends.cudnn.deterministic = True
|
| 144 |
+
torch.backends.cudnn.benchmark = False
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def print_args(args):
|
| 148 |
+
for key, value in args.items():
|
| 149 |
+
logging.info("{}: {}".format(key, value))
|
utils/__init__.py
ADDED
|
File without changes
|
utils/augmentation.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
image_augmentation.py
|
| 3 |
+
|
| 4 |
+
This script performs data augmentation on images using various transformations such as color jitter,
|
| 5 |
+
Gaussian blur, sharpness adjustment, horizontal flip, and vertical flip.
|
| 6 |
+
It generates augmented images from an existing dataset and saves them to new folders.
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from PIL import Image
|
| 11 |
+
import os
|
| 12 |
+
from torchvision.utils import save_image
|
| 13 |
+
import torchvision.transforms as tvts
|
| 14 |
+
import random
|
| 15 |
+
|
| 16 |
+
# List of transformations for data augmentation
|
| 17 |
+
transforms=[tvts.ColorJitter(brightness=.5, hue=.3),
|
| 18 |
+
tvts.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5.)),
|
| 19 |
+
tvts.RandomAdjustSharpness(sharpness_factor=2),
|
| 20 |
+
tvts.RandomHorizontalFlip(p=0.5),
|
| 21 |
+
tvts.RandomVerticalFlip(p=0.5)]
|
| 22 |
+
|
| 23 |
+
def select_random_imgs(img_list, count):
|
| 24 |
+
"""
|
| 25 |
+
Selects a random subset of images from a list.
|
| 26 |
+
|
| 27 |
+
Parameters:
|
| 28 |
+
img_list (list): List of image filenames.
|
| 29 |
+
count (int): Number of images to select.
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
list: Randomly selected image filenames.
|
| 33 |
+
"""
|
| 34 |
+
return random.sample(img_list, count)
|
| 35 |
+
|
| 36 |
+
def create_foldername(fname):
|
| 37 |
+
"""
|
| 38 |
+
Creates a new folder name for augmented images.
|
| 39 |
+
|
| 40 |
+
Parameters:
|
| 41 |
+
fname (str): Original folder name.
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
str: Augmented folder name.
|
| 45 |
+
"""
|
| 46 |
+
names = fname.split("_")
|
| 47 |
+
names.insert(2, "augment")
|
| 48 |
+
return "_".join(names)
|
| 49 |
+
|
| 50 |
+
def save_original_imgs(source_fname, dest_fname, img_files):
|
| 51 |
+
"""
|
| 52 |
+
Saves original images to the destination folder.
|
| 53 |
+
|
| 54 |
+
Parameters:
|
| 55 |
+
source_fname (str): Source folder name.
|
| 56 |
+
dest_fname (str): Destination folder name.
|
| 57 |
+
img_files (list): List of image filenames.
|
| 58 |
+
"""
|
| 59 |
+
for img in img_files:
|
| 60 |
+
img_name = img.split(".")[0]
|
| 61 |
+
img = open_PILimg(path=os.path.join(source_fname, img))
|
| 62 |
+
save_image(tvts.ToTensor()(img), os.path.join(dest_fname, "{}.jpg".format(img_name)))
|
| 63 |
+
|
| 64 |
+
def open_PILimg(path):
|
| 65 |
+
"""
|
| 66 |
+
Opens an image file using PIL.
|
| 67 |
+
|
| 68 |
+
Parameters:
|
| 69 |
+
path (str): File path to the image.
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
PIL.Image.Image: PIL image object.
|
| 73 |
+
"""
|
| 74 |
+
return Image.open(path).convert("RGB")
|
| 75 |
+
|
| 76 |
+
def augment_folder(root_fname, fname, augment_count=25):
|
| 77 |
+
"""
|
| 78 |
+
Augments images in a folder and saves the augmented images to a new folder.
|
| 79 |
+
|
| 80 |
+
Parameters:
|
| 81 |
+
root_fname (str): Root folder containing the source images.
|
| 82 |
+
fname (str): Name of the folder containing the source images.
|
| 83 |
+
augment_count (int): Number of augmented images to generate for each original image.
|
| 84 |
+
"""
|
| 85 |
+
onlyfiles = os.listdir(os.path.join(root_fname, fname))
|
| 86 |
+
print(f'Befor augmentation, number of images: {len(onlyfiles)}')
|
| 87 |
+
random_imgs = select_random_imgs(onlyfiles, len(onlyfiles))
|
| 88 |
+
augment_fname = create_foldername(root_fname)
|
| 89 |
+
if not os.path.exists(augment_fname):
|
| 90 |
+
os.mkdir(augment_fname)
|
| 91 |
+
|
| 92 |
+
save_fname = os.path.join(augment_fname, fname)
|
| 93 |
+
|
| 94 |
+
if not os.path.exists(save_fname):
|
| 95 |
+
os.mkdir(save_fname)
|
| 96 |
+
|
| 97 |
+
save_original_imgs(source_fname=os.path.join(root_fname, fname),
|
| 98 |
+
dest_fname=os.path.join(augment_fname, fname),
|
| 99 |
+
img_files=onlyfiles)
|
| 100 |
+
|
| 101 |
+
for img in random_imgs:
|
| 102 |
+
img_name = img.split(".")[0]
|
| 103 |
+
img = open_PILimg(path=os.path.join(root_fname, fname, img))
|
| 104 |
+
|
| 105 |
+
for transform in transforms:
|
| 106 |
+
transname = transform.__class__.__name__
|
| 107 |
+
transformed_imgs = [transform(img) for _ in range(augment_count)]
|
| 108 |
+
for i, trans_img in enumerate(transformed_imgs):
|
| 109 |
+
save_image(tvts.ToTensor()(trans_img), os.path.join(save_fname, "trans_img_{}_{}_{}.jpg".format(img_name, transname, i)))
|
| 110 |
+
|
| 111 |
+
print(f"After augmentation, number of images: {len(os.listdir(save_fname))}")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
# Example usage
|
| 116 |
+
root_folder = [["GNSS/Train"]]
|
| 117 |
+
for root in root_folder:
|
| 118 |
+
folders = [f for f in os.listdir(root) if os.path.isdir(os.path.join(root, f))]
|
| 119 |
+
for folder in folders:
|
| 120 |
+
augment_folder(root, folder)
|
| 121 |
+
|
| 122 |
+
|
utils/bayesian_weighting.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
class AutomaticWeightedLoss(nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
Automatically weighted multi-task loss module.
|
| 7 |
+
|
| 8 |
+
This module automatically weights multiple loss functions based on their individual magnitudes.
|
| 9 |
+
|
| 10 |
+
Params:
|
| 11 |
+
num (int): The number of loss functions.
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
def __init__(self, num=2):
|
| 15 |
+
super(AutomaticWeightedLoss, self).__init__()
|
| 16 |
+
params = torch.ones(num, requires_grad=True)
|
| 17 |
+
self.params = torch.nn.Parameter(params)
|
| 18 |
+
|
| 19 |
+
def forward(self, *x):
|
| 20 |
+
"""
|
| 21 |
+
Forward pass through the AutomaticWeightedLoss module.
|
| 22 |
+
|
| 23 |
+
Parameters:
|
| 24 |
+
*x (Tensor): Variable number of loss functions.
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
Tensor: Weighted sum of the loss functions.
|
| 28 |
+
"""
|
| 29 |
+
loss_sum = 0
|
| 30 |
+
for i, loss in enumerate(x):
|
| 31 |
+
loss_sum += 0.5 / (self.params[i] ** 2) * loss + torch.log(1 + self.params[i] ** 2)
|
| 32 |
+
return loss_sum
|
| 33 |
+
|
| 34 |
+
|
utils/cluster_analysis.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sklearn.metrics import davies_bouldin_score as dbs
|
| 2 |
+
from sklearn.metrics import calinski_harabasz_score as chs
|
| 3 |
+
|
| 4 |
+
def cluster_analysis(embeddings, predicted_labels, task_no):
|
| 5 |
+
"""
|
| 6 |
+
Calculate clustering quality metrics for the provided embeddings and labels.
|
| 7 |
+
|
| 8 |
+
Args:
|
| 9 |
+
embeddings (np.ndarray): The embeddings (n_samples, n_features) to be clustered.
|
| 10 |
+
predicted_labels (np.ndarray): The predicted cluster labels (n_samples,) for the embeddings.
|
| 11 |
+
|
| 12 |
+
Returns:
|
| 13 |
+
tuple: A tuple containing:
|
| 14 |
+
- Davies-Bouldin Score
|
| 15 |
+
- Calinski-Harabasz Score
|
| 16 |
+
- Silhouette Score (if more than 1 cluster exists)
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
if len(embeddings) != len(predicted_labels):
|
| 20 |
+
raise ValueError("Embeddings and predicted labels must have the same length.")
|
| 21 |
+
|
| 22 |
+
# Calculating cluster analysis scores
|
| 23 |
+
dbs_score = dbs(X=embeddings, labels=predicted_labels)
|
| 24 |
+
chs_score = chs(X=embeddings, labels=predicted_labels)
|
| 25 |
+
return dbs_score, chs_score
|
| 26 |
+
|
| 27 |
+
|
utils/contrastive_loss.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
DMLLossCosine.py
|
| 3 |
+
|
| 4 |
+
This module implements a custom PyTorch loss function called DMLLossCosine.
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
- Create an instance of DMLLossCosine.
|
| 8 |
+
- Call the instance with embeddings and target tensors to compute the loss.
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
from torch import nn, optim
|
| 16 |
+
from torch.utils.data import Dataset, DataLoader
|
| 17 |
+
from torchvision import transforms
|
| 18 |
+
import matplotlib.pyplot as plt
|
| 19 |
+
import torchvision
|
| 20 |
+
from tqdm.notebook import tqdm
|
| 21 |
+
import logging
|
| 22 |
+
import random
|
| 23 |
+
|
| 24 |
+
class DMLLossCosine(nn.Module):
|
| 25 |
+
"""
|
| 26 |
+
DMLLossCosine - Deep Metric Learning Loss using Cosine Similarity.
|
| 27 |
+
|
| 28 |
+
This loss function measures the cosine similarity between embeddings and
|
| 29 |
+
computes the Mean Squared Error (MSE) loss with the target distances.
|
| 30 |
+
|
| 31 |
+
Attributes:
|
| 32 |
+
similarity (nn.CosineSimilarity): Cosine similarity module.
|
| 33 |
+
|
| 34 |
+
Methods:
|
| 35 |
+
forward: Computes the forward pass of the loss function.
|
| 36 |
+
embeddings_distance_pairs: Computes pairs of embeddings and their distances.
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
def __init__(self):
|
| 40 |
+
super(DMLLossCosine, self).__init__()
|
| 41 |
+
self.similarity = nn.CosineSimilarity(dim=-1, eps=1e-7)
|
| 42 |
+
|
| 43 |
+
def forward(self, embeddings, target):
|
| 44 |
+
"""
|
| 45 |
+
Computes the forward pass of the loss function.
|
| 46 |
+
|
| 47 |
+
Parameters:
|
| 48 |
+
embeddings (torch.Tensor): Input embeddings tensor.
|
| 49 |
+
target (torch.Tensor): Target tensor.
|
| 50 |
+
|
| 51 |
+
Returns:
|
| 52 |
+
loss (torch.Tensor): Computed loss.
|
| 53 |
+
|
| 54 |
+
"""
|
| 55 |
+
first, second, distance = self.embeddings_distance_pairs(embeddings=embeddings, target=target)
|
| 56 |
+
distance = distance.to("cuda")
|
| 57 |
+
score = self.similarity(first, second)
|
| 58 |
+
return nn.MSELoss()(score, distance)
|
| 59 |
+
|
| 60 |
+
def embeddings_distance_pairs(self, embeddings, target):
|
| 61 |
+
"""
|
| 62 |
+
Computes pairs of embeddings and their distances.
|
| 63 |
+
|
| 64 |
+
Parameters:
|
| 65 |
+
embeddings (torch.Tensor): Input embeddings tensor.
|
| 66 |
+
target (torch.Tensor): Target tensor.
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
first (torch.Tensor): First tensor containing embeddings.
|
| 70 |
+
second (torch.Tensor): Second tensor containing embeddings.
|
| 71 |
+
distance (torch.Tensor): Tensor containing distances.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
distance = []
|
| 75 |
+
first = []
|
| 76 |
+
second = []
|
| 77 |
+
for i, val1 in enumerate(target):
|
| 78 |
+
for j, val2 in enumerate(target[i:]):
|
| 79 |
+
if val1 == val2:
|
| 80 |
+
distance.append(torch.tensor(1.))
|
| 81 |
+
else:
|
| 82 |
+
distance.append(torch.tensor(0.))
|
| 83 |
+
first.append(embeddings[i])
|
| 84 |
+
second.append(embeddings[i+j])
|
| 85 |
+
|
| 86 |
+
return torch.stack(first), torch.stack(second), torch.stack(distance)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
|
utils/data.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 1 |
+
import numpy as np
|
| 2 |
+
from torchvision import datasets, transforms
|
| 3 |
+
from utils.toolkit import split_images_labels
|
| 4 |
+
from torchvision.datasets import VisionDataset
|
| 5 |
+
from torch.utils.data import Dataset, DataLoader, random_split
|
| 6 |
+
from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union
|
| 7 |
+
from typing import Any
|
| 8 |
+
import os
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import logging
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
class iData(object):
|
| 14 |
+
train_trsf = []
|
| 15 |
+
test_trsf = []
|
| 16 |
+
common_trsf = []
|
| 17 |
+
class_order = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class iCIFAR10(iData):
|
| 21 |
+
use_path = False
|
| 22 |
+
train_trsf = [
|
| 23 |
+
transforms.RandomCrop(32, padding=4),
|
| 24 |
+
transforms.RandomHorizontalFlip(p=0.5),
|
| 25 |
+
transforms.ColorJitter(brightness=63 / 255),
|
| 26 |
+
transforms.ToTensor(),
|
| 27 |
+
]
|
| 28 |
+
test_trsf = [transforms.ToTensor()]
|
| 29 |
+
common_trsf = [
|
| 30 |
+
transforms.Normalize(
|
| 31 |
+
mean=(0.4914, 0.4822, 0.4465), std=(0.2023, 0.1994, 0.2010)
|
| 32 |
+
),
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
class_order = np.arange(10).tolist()
|
| 36 |
+
|
| 37 |
+
def download_data(self):
|
| 38 |
+
train_dataset = datasets.cifar.CIFAR10("./data", train=True, download=True)
|
| 39 |
+
test_dataset = datasets.cifar.CIFAR10("./data", train=False, download=True)
|
| 40 |
+
self.train_data, self.train_targets = train_dataset.data, np.array(
|
| 41 |
+
train_dataset.targets
|
| 42 |
+
)
|
| 43 |
+
self.test_data, self.test_targets = test_dataset.data, np.array(
|
| 44 |
+
test_dataset.targets
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class iCIFAR100(iData):
|
| 49 |
+
use_path = False
|
| 50 |
+
train_trsf = [
|
| 51 |
+
|
| 52 |
+
transforms.RandomCrop(32, padding=4),
|
| 53 |
+
transforms.RandomHorizontalFlip(),
|
| 54 |
+
transforms.ColorJitter(brightness=63 / 255),
|
| 55 |
+
transforms.ToTensor()
|
| 56 |
+
]
|
| 57 |
+
test_trsf = [transforms.ToTensor()]
|
| 58 |
+
common_trsf = [
|
| 59 |
+
transforms.Normalize(
|
| 60 |
+
mean=(0.5071, 0.4867, 0.4408), std=(0.2675, 0.2565, 0.2761)
|
| 61 |
+
),
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
class_order = np.arange(100).tolist()
|
| 65 |
+
|
| 66 |
+
def download_data(self):
|
| 67 |
+
train_dataset = datasets.cifar.CIFAR100("./data", train=True, download=True)
|
| 68 |
+
test_dataset = datasets.cifar.CIFAR100("./data", train=False, download=True)
|
| 69 |
+
|
| 70 |
+
'''print(type(train_dataset))
|
| 71 |
+
print(type(test_dataset))
|
| 72 |
+
print('type of each pair of data', type(train_dataset[0]))
|
| 73 |
+
print(train_dataset.data[0].shape)
|
| 74 |
+
print(train_dataset.targets[0])'''
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
self.train_data, self.train_targets = train_dataset.data, np.array(
|
| 79 |
+
train_dataset.targets
|
| 80 |
+
)
|
| 81 |
+
self.test_data, self.test_targets = test_dataset.data, np.array(
|
| 82 |
+
test_dataset.targets
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class iImageNet1000(iData):
|
| 87 |
+
use_path = True
|
| 88 |
+
train_trsf = [
|
| 89 |
+
transforms.RandomResizedCrop(224),
|
| 90 |
+
transforms.RandomHorizontalFlip(),
|
| 91 |
+
transforms.ColorJitter(brightness=63 / 255),
|
| 92 |
+
]
|
| 93 |
+
test_trsf = [
|
| 94 |
+
transforms.Resize(256),
|
| 95 |
+
transforms.CenterCrop(224),
|
| 96 |
+
]
|
| 97 |
+
common_trsf = [
|
| 98 |
+
transforms.ToTensor(),
|
| 99 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
class_order = np.arange(1000).tolist()
|
| 103 |
+
|
| 104 |
+
def download_data(self):
|
| 105 |
+
assert 0, "You should specify the folder of your dataset"
|
| 106 |
+
train_dir = "[DATA-PATH]/train/"
|
| 107 |
+
test_dir = "[DATA-PATH]/val/"
|
| 108 |
+
|
| 109 |
+
train_dset = datasets.ImageFolder(train_dir)
|
| 110 |
+
test_dset = datasets.ImageFolder(test_dir)
|
| 111 |
+
|
| 112 |
+
self.train_data, self.train_targets = split_images_labels(train_dset.imgs)
|
| 113 |
+
self.test_data, self.test_targets = split_images_labels(test_dset.imgs)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class iImageNet100(iData):
|
| 117 |
+
use_path = True
|
| 118 |
+
train_trsf = [
|
| 119 |
+
transforms.RandomResizedCrop(224),
|
| 120 |
+
transforms.RandomHorizontalFlip(),
|
| 121 |
+
]
|
| 122 |
+
test_trsf = [
|
| 123 |
+
transforms.Resize(256),
|
| 124 |
+
transforms.CenterCrop(224),
|
| 125 |
+
]
|
| 126 |
+
common_trsf = [
|
| 127 |
+
transforms.ToTensor(),
|
| 128 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 129 |
+
]
|
| 130 |
+
|
| 131 |
+
class_order = np.arange(1000).tolist()
|
| 132 |
+
|
| 133 |
+
def download_data(self):
|
| 134 |
+
assert 0, "You should specify the folder of your dataset"
|
| 135 |
+
train_dir = "[DATA-PATH]/train/"
|
| 136 |
+
test_dir = "[DATA-PATH]/val/"
|
| 137 |
+
|
| 138 |
+
train_dset = datasets.ImageFolder(train_dir)
|
| 139 |
+
test_dset = datasets.ImageFolder(test_dir)
|
| 140 |
+
|
| 141 |
+
self.train_data, self.train_targets = split_images_labels(train_dset.imgs)
|
| 142 |
+
self.test_data, self.test_targets = split_images_labels(test_dset.imgs)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class iData(object):
|
| 146 |
+
train_trsf = []
|
| 147 |
+
test_trsf = []
|
| 148 |
+
common_trsf = []
|
| 149 |
+
class_order = None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def split_images_labels(imgs):
|
| 154 |
+
images = []
|
| 155 |
+
labels = []
|
| 156 |
+
for item in imgs:
|
| 157 |
+
images.append(item[0])
|
| 158 |
+
labels.append(item[1])
|
| 159 |
+
|
| 160 |
+
return np.array(images), np.array(labels)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class CustomImageFolder(datasets.ImageFolder):
|
| 164 |
+
def find_classes(self, directory: str) -> Tuple[List[str], Dict[str, int]]:
|
| 165 |
+
classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir())
|
| 166 |
+
if not classes:
|
| 167 |
+
raise FileNotFoundError(f"Couldn't find any class folder in {directory}.")
|
| 168 |
+
class_to_idx = dict()
|
| 169 |
+
for i, cls_name in enumerate(classes):
|
| 170 |
+
if int(cls_name) > 5:
|
| 171 |
+
class_to_idx[cls_name] = int(cls_name) - 1
|
| 172 |
+
else:
|
| 173 |
+
class_to_idx[cls_name] = int(cls_name)
|
| 174 |
+
return classes, class_to_idx
|
| 175 |
+
|
| 176 |
+
class GNSS(iData):
|
| 177 |
+
use_path = True
|
| 178 |
+
|
| 179 |
+
common_trsf = [
|
| 180 |
+
transforms.ToTensor()
|
| 181 |
+
]
|
| 182 |
+
|
| 183 |
+
class_order = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
| 184 |
+
|
| 185 |
+
def download_data(self):
|
| 186 |
+
|
| 187 |
+
train_dir = "./Dataset/GNSS/Train/"
|
| 188 |
+
test_dir = "./Dataset/GNSS/Test/"
|
| 189 |
+
|
| 190 |
+
train_dset = CustomImageFolder(train_dir)
|
| 191 |
+
test_dset = CustomImageFolder(test_dir)
|
| 192 |
+
|
| 193 |
+
self.train_data, self.train_targets = split_images_labels(train_dset.imgs)
|
| 194 |
+
self.test_data, self.test_targets = split_images_labels(test_dset.imgs)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
obj = GNSS()
|
| 199 |
+
obj.download_data()
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
|
utils/data_manager.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from torch.utils.data import Dataset
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from utils.data import iCIFAR10, iCIFAR100, iImageNet100, iImageNet1000, GNSS
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
import os
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
class DataManager(object):
|
| 12 |
+
def __init__(self, dataset_name, shuffle, seed, init_cls, increment):
|
| 13 |
+
self.dataset_name = dataset_name
|
| 14 |
+
self._setup_data(dataset_name, shuffle, seed)
|
| 15 |
+
assert init_cls <= len(self._class_order), "No enough classes."
|
| 16 |
+
self._increments = [init_cls]
|
| 17 |
+
while sum(self._increments) + increment < len(self._class_order):
|
| 18 |
+
self._increments.append(increment)
|
| 19 |
+
offset = len(self._class_order) - sum(self._increments)
|
| 20 |
+
if offset > 0:
|
| 21 |
+
self._increments.append(offset)
|
| 22 |
+
|
| 23 |
+
@property
|
| 24 |
+
def nb_tasks(self):
|
| 25 |
+
return len(self._increments)
|
| 26 |
+
|
| 27 |
+
def get_task_size(self, task):
|
| 28 |
+
return self._increments[task]
|
| 29 |
+
|
| 30 |
+
def get_accumulate_tasksize(self,task):
|
| 31 |
+
return sum(self._increments[:task+1])
|
| 32 |
+
|
| 33 |
+
def get_total_classnum(self):
|
| 34 |
+
return len(self._class_order)
|
| 35 |
+
|
| 36 |
+
def get_dataset(
|
| 37 |
+
self, indices, source, mode, appendent=None, ret_data=False, m_rate=None, dataset_type="normal"):
|
| 38 |
+
if source == "train":
|
| 39 |
+
x, y = self._train_data, self._train_targets
|
| 40 |
+
elif source == "test":
|
| 41 |
+
x, y = self._test_data, self._test_targets
|
| 42 |
+
else:
|
| 43 |
+
raise ValueError("Unknown data source {}.".format(source))
|
| 44 |
+
|
| 45 |
+
if mode == "train":
|
| 46 |
+
trsf = transforms.Compose([*self._train_trsf, *self._common_trsf])
|
| 47 |
+
elif mode == "flip":
|
| 48 |
+
trsf = transforms.Compose(
|
| 49 |
+
[
|
| 50 |
+
*self._test_trsf,
|
| 51 |
+
transforms.RandomHorizontalFlip(p=1.0),
|
| 52 |
+
*self._common_trsf,
|
| 53 |
+
]
|
| 54 |
+
)
|
| 55 |
+
elif mode == "test":
|
| 56 |
+
trsf = transforms.Compose([*self._test_trsf, *self._common_trsf])
|
| 57 |
+
else:
|
| 58 |
+
raise ValueError("Unknown mode {}.".format(mode))
|
| 59 |
+
|
| 60 |
+
data, targets = [], []
|
| 61 |
+
for idx in indices:
|
| 62 |
+
if m_rate is None:
|
| 63 |
+
class_data, class_targets = self._select(
|
| 64 |
+
x, y, low_range=idx, high_range=idx + 1
|
| 65 |
+
)
|
| 66 |
+
else:
|
| 67 |
+
class_data, class_targets = self._select_rmm(
|
| 68 |
+
x, y, low_range=idx, high_range=idx + 1, m_rate=m_rate
|
| 69 |
+
)
|
| 70 |
+
data.append(class_data)
|
| 71 |
+
targets.append(class_targets)
|
| 72 |
+
|
| 73 |
+
if appendent is not None and len(appendent) != 0:
|
| 74 |
+
appendent_data, appendent_targets = appendent
|
| 75 |
+
data.append(appendent_data)
|
| 76 |
+
targets.append(appendent_targets)
|
| 77 |
+
|
| 78 |
+
data, targets = np.concatenate(data), np.concatenate(targets)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if ret_data:
|
| 82 |
+
return data, targets, DummyDataset(data, targets, trsf, self.use_path, self.dataset_name)
|
| 83 |
+
else:
|
| 84 |
+
return DummyDataset(data, targets, trsf, self.use_path, self.dataset_name)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def get_finetune_dataset(self,known_classes,total_classes,source,mode,appendent,type="ratio"):
|
| 88 |
+
if source == 'train':
|
| 89 |
+
x, y = self._train_data, self._train_targets
|
| 90 |
+
elif source == 'test':
|
| 91 |
+
x, y = self._test_data, self._test_targets
|
| 92 |
+
else:
|
| 93 |
+
raise ValueError('Unknown data source {}.'.format(source))
|
| 94 |
+
|
| 95 |
+
if mode == 'train':
|
| 96 |
+
trsf = transforms.Compose([*self._train_trsf, *self._common_trsf])
|
| 97 |
+
elif mode == 'test':
|
| 98 |
+
trsf = transforms.Compose([*self._test_trsf, *self._common_trsf])
|
| 99 |
+
else:
|
| 100 |
+
raise ValueError('Unknown mode {}.'.format(mode))
|
| 101 |
+
val_data = []
|
| 102 |
+
val_targets = []
|
| 103 |
+
|
| 104 |
+
old_num_tot = 0
|
| 105 |
+
appendent_data, appendent_targets = appendent
|
| 106 |
+
|
| 107 |
+
for idx in range(0, known_classes):
|
| 108 |
+
append_data, append_targets = self._select(appendent_data, appendent_targets,
|
| 109 |
+
low_range=idx, high_range=idx+1)
|
| 110 |
+
num=len(append_data)
|
| 111 |
+
if num == 0:
|
| 112 |
+
continue
|
| 113 |
+
old_num_tot += num
|
| 114 |
+
val_data.append(append_data)
|
| 115 |
+
val_targets.append(append_targets)
|
| 116 |
+
if type == "ratio":
|
| 117 |
+
new_num_tot = int(old_num_tot*(total_classes-known_classes)/known_classes)
|
| 118 |
+
elif type == "same":
|
| 119 |
+
new_num_tot = old_num_tot
|
| 120 |
+
else:
|
| 121 |
+
assert 0, "not implemented yet"
|
| 122 |
+
new_num_average = int(new_num_tot/(total_classes-known_classes))
|
| 123 |
+
for idx in range(known_classes,total_classes):
|
| 124 |
+
class_data, class_targets = self._select(x, y, low_range=idx, high_range=idx+1)
|
| 125 |
+
val_indx = np.random.choice(len(class_data),new_num_average, replace=False)
|
| 126 |
+
val_data.append(class_data[val_indx])
|
| 127 |
+
val_targets.append(class_targets[val_indx])
|
| 128 |
+
val_data=np.concatenate(val_data)
|
| 129 |
+
val_targets = np.concatenate(val_targets)
|
| 130 |
+
return DummyDataset(val_data, val_targets, trsf, self.use_path)
|
| 131 |
+
|
| 132 |
+
def get_dataset_with_split(
|
| 133 |
+
self, indices, source, mode, appendent=None, val_samples_per_class=0
|
| 134 |
+
):
|
| 135 |
+
if source == "train":
|
| 136 |
+
x, y = self._train_data, self._train_targets
|
| 137 |
+
elif source == "test":
|
| 138 |
+
x, y = self._test_data, self._test_targets
|
| 139 |
+
else:
|
| 140 |
+
raise ValueError("Unknown data source {}.".format(source))
|
| 141 |
+
|
| 142 |
+
if mode == "train":
|
| 143 |
+
trsf = transforms.Compose([*self._train_trsf, *self._common_trsf])
|
| 144 |
+
elif mode == "test":
|
| 145 |
+
trsf = transforms.Compose([*self._test_trsf, *self._common_trsf])
|
| 146 |
+
else:
|
| 147 |
+
raise ValueError("Unknown mode {}.".format(mode))
|
| 148 |
+
|
| 149 |
+
train_data, train_targets = [], []
|
| 150 |
+
val_data, val_targets = [], []
|
| 151 |
+
for idx in indices:
|
| 152 |
+
class_data, class_targets = self._select(
|
| 153 |
+
x, y, low_range=idx, high_range=idx + 1
|
| 154 |
+
)
|
| 155 |
+
val_indx = np.random.choice(
|
| 156 |
+
len(class_data), val_samples_per_class, replace=False
|
| 157 |
+
)
|
| 158 |
+
train_indx = list(set(np.arange(len(class_data))) - set(val_indx))
|
| 159 |
+
val_data.append(class_data[val_indx])
|
| 160 |
+
val_targets.append(class_targets[val_indx])
|
| 161 |
+
train_data.append(class_data[train_indx])
|
| 162 |
+
train_targets.append(class_targets[train_indx])
|
| 163 |
+
|
| 164 |
+
if appendent is not None:
|
| 165 |
+
appendent_data, appendent_targets = appendent
|
| 166 |
+
for idx in range(0, int(np.max(appendent_targets)) + 1):
|
| 167 |
+
append_data, append_targets = self._select(
|
| 168 |
+
appendent_data, appendent_targets, low_range=idx, high_range=idx + 1
|
| 169 |
+
)
|
| 170 |
+
val_indx = np.random.choice(
|
| 171 |
+
len(append_data), val_samples_per_class, replace=False
|
| 172 |
+
)
|
| 173 |
+
train_indx = list(set(np.arange(len(append_data))) - set(val_indx))
|
| 174 |
+
val_data.append(append_data[val_indx])
|
| 175 |
+
val_targets.append(append_targets[val_indx])
|
| 176 |
+
train_data.append(append_data[train_indx])
|
| 177 |
+
train_targets.append(append_targets[train_indx])
|
| 178 |
+
|
| 179 |
+
train_data, train_targets = np.concatenate(train_data), np.concatenate(
|
| 180 |
+
train_targets
|
| 181 |
+
)
|
| 182 |
+
val_data, val_targets = np.concatenate(val_data), np.concatenate(val_targets)
|
| 183 |
+
|
| 184 |
+
return DummyDataset(
|
| 185 |
+
train_data, train_targets, trsf, self.use_path
|
| 186 |
+
), DummyDataset(val_data, val_targets, trsf, self.use_path)
|
| 187 |
+
|
| 188 |
+
def _setup_data(self, dataset_name, shuffle, seed):
|
| 189 |
+
idata = _get_idata(dataset_name)
|
| 190 |
+
idata.download_data()
|
| 191 |
+
shuffle = False
|
| 192 |
+
# Data
|
| 193 |
+
self._train_data, self._train_targets = idata.train_data, idata.train_targets
|
| 194 |
+
self._test_data, self._test_targets = idata.test_data, idata.test_targets
|
| 195 |
+
self.use_path = idata.use_path
|
| 196 |
+
|
| 197 |
+
# Transforms
|
| 198 |
+
self._train_trsf = idata.train_trsf
|
| 199 |
+
self._test_trsf = idata.test_trsf
|
| 200 |
+
self._common_trsf = idata.common_trsf
|
| 201 |
+
|
| 202 |
+
# Order
|
| 203 |
+
order = [i for i in range(len(np.unique(self._train_targets)))]
|
| 204 |
+
|
| 205 |
+
if shuffle:
|
| 206 |
+
np.random.seed(seed)
|
| 207 |
+
order = np.random.permutation(len(order)).tolist()
|
| 208 |
+
else:
|
| 209 |
+
order = idata.class_order
|
| 210 |
+
self._class_order = order
|
| 211 |
+
# Map indices
|
| 212 |
+
|
| 213 |
+
self._train_targets = _map_new_class_index(self._train_targets, self._class_order)
|
| 214 |
+
self._test_targets = _map_new_class_index(self._test_targets, self._class_order)
|
| 215 |
+
|
| 216 |
+
def _select(self, x, y, low_range, high_range):
|
| 217 |
+
idxes = np.where(np.logical_and(y >= low_range, y < high_range))[0]
|
| 218 |
+
|
| 219 |
+
if isinstance(x,np.ndarray):
|
| 220 |
+
x_return = x[idxes]
|
| 221 |
+
else:
|
| 222 |
+
x_return = []
|
| 223 |
+
for id in idxes:
|
| 224 |
+
x_return.append(x[id])
|
| 225 |
+
return x_return, y[idxes]
|
| 226 |
+
|
| 227 |
+
def _select_rmm(self, x, y, low_range, high_range, m_rate):
|
| 228 |
+
assert m_rate is not None
|
| 229 |
+
if m_rate != 0:
|
| 230 |
+
idxes = np.where(np.logical_and(y >= low_range, y < high_range))[0]
|
| 231 |
+
selected_idxes = np.random.randint(
|
| 232 |
+
0, len(idxes), size=int((1 - m_rate) * len(idxes))
|
| 233 |
+
)
|
| 234 |
+
new_idxes = idxes[selected_idxes]
|
| 235 |
+
new_idxes = np.sort(new_idxes)
|
| 236 |
+
else:
|
| 237 |
+
new_idxes = np.where(np.logical_and(y >= low_range, y < high_range))[0]
|
| 238 |
+
return x[new_idxes], y[new_idxes]
|
| 239 |
+
|
| 240 |
+
def getlen(self, index):
|
| 241 |
+
y = self._train_targets
|
| 242 |
+
return np.sum(np.where(y == index))
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class DummyDataset(Dataset):
|
| 246 |
+
def __init__(self, images, labels, trsf, use_path=False, dataset_name='cifar'):
|
| 247 |
+
assert len(images) == len(labels), "Data size error!"
|
| 248 |
+
self.images = images
|
| 249 |
+
self.labels = labels
|
| 250 |
+
self.trsf = trsf
|
| 251 |
+
self.use_path = use_path
|
| 252 |
+
self.dataset_name = dataset_name
|
| 253 |
+
|
| 254 |
+
def __len__(self):
|
| 255 |
+
return len(self.images)
|
| 256 |
+
|
| 257 |
+
def __getitem__(self, idx):
|
| 258 |
+
if self.use_path:
|
| 259 |
+
image = self.trsf(pil_loader(self.images[idx]))
|
| 260 |
+
else:
|
| 261 |
+
image = self.trsf(Image.fromarray(self.images[idx]))
|
| 262 |
+
label = self.labels[idx]
|
| 263 |
+
|
| 264 |
+
return idx, image, label
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _map_new_class_index(y, order):
|
| 268 |
+
return np.array(list(map(lambda x: order.index(x), y)))
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _get_idata(dataset_name):
|
| 272 |
+
name = dataset_name.lower()
|
| 273 |
+
if name == "cifar10":
|
| 274 |
+
return iCIFAR10()
|
| 275 |
+
elif name == "cifar100":
|
| 276 |
+
return iCIFAR100()
|
| 277 |
+
elif name == "imagenet1000":
|
| 278 |
+
return iImageNet1000()
|
| 279 |
+
elif name == "imagenet100":
|
| 280 |
+
return iImageNet100()
|
| 281 |
+
elif name == "gnss":
|
| 282 |
+
return GNSS()
|
| 283 |
+
else:
|
| 284 |
+
raise NotImplementedError("Unknown dataset {}.".format(dataset_name))
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def pil_loader(path):
|
| 288 |
+
"""
|
| 289 |
+
Ref:
|
| 290 |
+
https://pytorch.org/docs/stable/_modules/torchvision/datasets/folder.html#ImageFolder
|
| 291 |
+
"""
|
| 292 |
+
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
|
| 293 |
+
with open(path, "rb") as f:
|
| 294 |
+
img = Image.open(f)
|
| 295 |
+
return img.convert("RGB")
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def accimage_loader(path):
|
| 299 |
+
"""
|
| 300 |
+
Ref:
|
| 301 |
+
https://pytorch.org/docs/stable/_modules/torchvision/datasets/folder.html#ImageFolder
|
| 302 |
+
accimage is an accelerated Image loader and preprocessor leveraging Intel IPP.
|
| 303 |
+
accimage is available on conda-forge.
|
| 304 |
+
"""
|
| 305 |
+
import accimage
|
| 306 |
+
|
| 307 |
+
try:
|
| 308 |
+
return accimage.Image(path)
|
| 309 |
+
except IOError:
|
| 310 |
+
# Potentially a decoding problem, fall back to PIL.Image
|
| 311 |
+
return pil_loader(path)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def default_loader(path):
|
| 315 |
+
"""
|
| 316 |
+
Ref:
|
| 317 |
+
https://pytorch.org/docs/stable/_modules/torchvision/datasets/folder.html#ImageFolder
|
| 318 |
+
"""
|
| 319 |
+
from torchvision import get_image_backend
|
| 320 |
+
|
| 321 |
+
if get_image_backend() == "accimage":
|
| 322 |
+
return accimage_loader(path)
|
| 323 |
+
else:
|
| 324 |
+
return pil_loader(path)
|
utils/factory.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def get_model(model_name, args):
|
| 2 |
+
name = model_name.lower()
|
| 3 |
+
if name == "icarl":
|
| 4 |
+
from models.icarl import iCaRL
|
| 5 |
+
return iCaRL(args)
|
| 6 |
+
|
| 7 |
+
elif name == "lwf":
|
| 8 |
+
from models.lwf import LwF
|
| 9 |
+
return LwF(args)
|
| 10 |
+
elif name == "ewc":
|
| 11 |
+
from models.ewc import EWC
|
| 12 |
+
return EWC(args)
|
| 13 |
+
elif name == "finetune":
|
| 14 |
+
from models.finetune import Finetune
|
| 15 |
+
return Finetune(args)
|
| 16 |
+
elif name == "replay":
|
| 17 |
+
from models.replay import Replay
|
| 18 |
+
return Replay(args)
|
| 19 |
+
elif name == "memo":
|
| 20 |
+
from models.memo import MEMO
|
| 21 |
+
return MEMO(args)
|
| 22 |
+
elif name == "blcl":
|
| 23 |
+
from models.blcl import BLCL
|
| 24 |
+
return BLCL(args)
|
| 25 |
+
|
| 26 |
+
else:
|
| 27 |
+
assert 0
|
utils/inc_net.py
ADDED
|
@@ -0,0 +1,897 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import logging
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from convs.cifar_resnet import resnet32
|
| 6 |
+
from convs.resnet import resnet18, resnet34, resnet50, resnet101, resnet152
|
| 7 |
+
from convs.ucir_cifar_resnet import resnet32 as cosine_resnet32
|
| 8 |
+
from convs.ucir_resnet import resnet18 as cosine_resnet18
|
| 9 |
+
from convs.ucir_resnet import resnet34 as cosine_resnet34
|
| 10 |
+
from convs.ucir_resnet import resnet50 as cosine_resnet50
|
| 11 |
+
from convs.linears import SimpleLinear, SplitCosineLinear, CosineLinear
|
| 12 |
+
from convs.modified_represnet import resnet18_rep,resnet34_rep
|
| 13 |
+
from convs.resnet_cbam import resnet18_cbam,resnet34_cbam,resnet50_cbam
|
| 14 |
+
from convs.memo_resnet import get_resnet18_imagenet as get_memo_resnet18 #for MEMO imagenet
|
| 15 |
+
from convs.memo_cifar_resnet import get_resnet32_a2fc as get_memo_resnet32 #for MEMO cifar
|
| 16 |
+
from convs.memo_cifar_resnet import get_resnet56_a2fc as get_memo_resnet56 #for MEMO cifar
|
| 17 |
+
import convs.memo_resnet as memor
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
def get_convnet(args, pretrained=False):
|
| 21 |
+
name = args["convnet_type"].lower()
|
| 22 |
+
if name == "resnet32":
|
| 23 |
+
return resnet32()
|
| 24 |
+
elif name == "resnet18":
|
| 25 |
+
return resnet18(pretrained=pretrained,args=args)
|
| 26 |
+
elif name == "resnet34":
|
| 27 |
+
return resnet34(pretrained=pretrained,args=args)
|
| 28 |
+
elif name == "resnet50":
|
| 29 |
+
return resnet50(pretrained=pretrained,args=args)
|
| 30 |
+
# MEMO benchmark backbone
|
| 31 |
+
elif name == 'memo_resnet18':
|
| 32 |
+
_basenet, _adaptive_net = get_memo_resnet18(args=args)
|
| 33 |
+
return _basenet, _adaptive_net
|
| 34 |
+
|
| 35 |
+
elif name == 'memo_resnet32':
|
| 36 |
+
_basenet, _adaptive_net = get_memo_resnet32(args=args)
|
| 37 |
+
return _basenet, _adaptive_net
|
| 38 |
+
|
| 39 |
+
elif name == 'memo_resnet56':
|
| 40 |
+
_basenet, _adaptive_net = get_memo_resnet56(args=args)
|
| 41 |
+
return _basenet, _adaptive_net
|
| 42 |
+
else:
|
| 43 |
+
raise NotImplementedError("Unknown type {}".format(name))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class BaseNet(nn.Module):
|
| 47 |
+
def __init__(self, args, pretrained):
|
| 48 |
+
super(BaseNet, self).__init__()
|
| 49 |
+
|
| 50 |
+
self.convnet = get_convnet(args, pretrained)
|
| 51 |
+
self.fc = None
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
def feature_dim(self):
|
| 55 |
+
return self.convnet.out_dim
|
| 56 |
+
|
| 57 |
+
def extract_vector(self, x):
|
| 58 |
+
return self.convnet(x)["features"]
|
| 59 |
+
|
| 60 |
+
def forward(self, x):
|
| 61 |
+
x = self.convnet(x)
|
| 62 |
+
out = self.fc(x["features"])
|
| 63 |
+
"""
|
| 64 |
+
{
|
| 65 |
+
'fmaps': [x_1, x_2, ..., x_n],
|
| 66 |
+
'features': features
|
| 67 |
+
'logits': logits
|
| 68 |
+
}
|
| 69 |
+
"""
|
| 70 |
+
out.update(x)
|
| 71 |
+
|
| 72 |
+
return out
|
| 73 |
+
|
| 74 |
+
def update_fc(self, nb_classes):
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
def generate_fc(self, in_dim, out_dim):
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
def copy(self):
|
| 81 |
+
return copy.deepcopy(self)
|
| 82 |
+
|
| 83 |
+
def freeze(self):
|
| 84 |
+
for param in self.parameters():
|
| 85 |
+
param.requires_grad = False
|
| 86 |
+
self.eval()
|
| 87 |
+
|
| 88 |
+
return self
|
| 89 |
+
|
| 90 |
+
def load_checkpoint(self, args):
|
| 91 |
+
if args["init_cls"] == 50:
|
| 92 |
+
pkl_name = "{}_{}_{}_B{}_Inc{}".format(
|
| 93 |
+
args["dataset"],
|
| 94 |
+
args["seed"],
|
| 95 |
+
args["convnet_type"],
|
| 96 |
+
0,
|
| 97 |
+
args["init_cls"],
|
| 98 |
+
)
|
| 99 |
+
checkpoint_name = f"checkpoints/finetune_{pkl_name}_0.pkl"
|
| 100 |
+
else:
|
| 101 |
+
checkpoint_name = f"checkpoints/finetune_{args['csv_name']}_0.pkl"
|
| 102 |
+
model_infos = torch.load(checkpoint_name)
|
| 103 |
+
self.convnet.load_state_dict(model_infos['convnet'])
|
| 104 |
+
self.fc.load_state_dict(model_infos['fc'])
|
| 105 |
+
test_acc = model_infos['test_acc']
|
| 106 |
+
return test_acc
|
| 107 |
+
|
| 108 |
+
class IncrementalNet(BaseNet):
|
| 109 |
+
def __init__(self, args, pretrained, gradcam=False):
|
| 110 |
+
super().__init__(args, pretrained)
|
| 111 |
+
self.gradcam = gradcam
|
| 112 |
+
if hasattr(self, "gradcam") and self.gradcam:
|
| 113 |
+
self._gradcam_hooks = [None, None]
|
| 114 |
+
self.set_gradcam_hook()
|
| 115 |
+
|
| 116 |
+
def update_fc(self, nb_classes):
|
| 117 |
+
|
| 118 |
+
fc = self.generate_fc(self.feature_dim, nb_classes)
|
| 119 |
+
if self.fc is not None:
|
| 120 |
+
nb_output = self.fc.out_features
|
| 121 |
+
weight = copy.deepcopy(self.fc.weight.data)
|
| 122 |
+
bias = copy.deepcopy(self.fc.bias.data)
|
| 123 |
+
fc.weight.data[:nb_output] = weight
|
| 124 |
+
fc.bias.data[:nb_output] = bias
|
| 125 |
+
|
| 126 |
+
del self.fc
|
| 127 |
+
self.fc = fc
|
| 128 |
+
|
| 129 |
+
def weight_align(self, increment):
|
| 130 |
+
weights = self.fc.weight.data
|
| 131 |
+
newnorm = torch.norm(weights[-increment:, :], p=2, dim=1)
|
| 132 |
+
oldnorm = torch.norm(weights[:-increment, :], p=2, dim=1)
|
| 133 |
+
meannew = torch.mean(newnorm)
|
| 134 |
+
meanold = torch.mean(oldnorm)
|
| 135 |
+
gamma = meanold / meannew
|
| 136 |
+
self.fc.weight.data[-increment:, :] *= gamma
|
| 137 |
+
|
| 138 |
+
def generate_fc(self, in_dim, out_dim):
|
| 139 |
+
fc = SimpleLinear(in_dim, out_dim)
|
| 140 |
+
|
| 141 |
+
return fc
|
| 142 |
+
|
| 143 |
+
def forward(self, x):
|
| 144 |
+
x = self.convnet(x)
|
| 145 |
+
out = self.fc(x["features"])
|
| 146 |
+
out.update(x)
|
| 147 |
+
if hasattr(self, "gradcam") and self.gradcam:
|
| 148 |
+
out["gradcam_gradients"] = self._gradcam_gradients
|
| 149 |
+
out["gradcam_activations"] = self._gradcam_activations
|
| 150 |
+
|
| 151 |
+
return out
|
| 152 |
+
|
| 153 |
+
def unset_gradcam_hook(self):
|
| 154 |
+
self._gradcam_hooks[0].remove()
|
| 155 |
+
self._gradcam_hooks[1].remove()
|
| 156 |
+
self._gradcam_hooks[0] = None
|
| 157 |
+
self._gradcam_hooks[1] = None
|
| 158 |
+
self._gradcam_gradients, self._gradcam_activations = [None], [None]
|
| 159 |
+
|
| 160 |
+
def set_gradcam_hook(self):
|
| 161 |
+
self._gradcam_gradients, self._gradcam_activations = [None], [None]
|
| 162 |
+
|
| 163 |
+
def backward_hook(module, grad_input, grad_output):
|
| 164 |
+
self._gradcam_gradients[0] = grad_output[0]
|
| 165 |
+
return None
|
| 166 |
+
|
| 167 |
+
def forward_hook(module, input, output):
|
| 168 |
+
self._gradcam_activations[0] = output
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
self._gradcam_hooks[0] = self.convnet.last_conv.register_backward_hook(
|
| 172 |
+
backward_hook
|
| 173 |
+
)
|
| 174 |
+
self._gradcam_hooks[1] = self.convnet.last_conv.register_forward_hook(
|
| 175 |
+
forward_hook
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
class IL2ANet(IncrementalNet):
|
| 179 |
+
|
| 180 |
+
def update_fc(self, num_old, num_total, num_aux):
|
| 181 |
+
fc = self.generate_fc(self.feature_dim, num_total+num_aux)
|
| 182 |
+
if self.fc is not None:
|
| 183 |
+
weight = copy.deepcopy(self.fc.weight.data)
|
| 184 |
+
bias = copy.deepcopy(self.fc.bias.data)
|
| 185 |
+
fc.weight.data[:num_old] = weight[:num_old]
|
| 186 |
+
fc.bias.data[:num_old] = bias[:num_old]
|
| 187 |
+
del self.fc
|
| 188 |
+
self.fc = fc
|
| 189 |
+
|
| 190 |
+
class CosineIncrementalNet(BaseNet):
|
| 191 |
+
def __init__(self, args, pretrained, nb_proxy=1):
|
| 192 |
+
super().__init__(args, pretrained)
|
| 193 |
+
self.nb_proxy = nb_proxy
|
| 194 |
+
|
| 195 |
+
def update_fc(self, nb_classes, task_num):
|
| 196 |
+
fc = self.generate_fc(self.feature_dim, nb_classes)
|
| 197 |
+
if self.fc is not None:
|
| 198 |
+
if task_num == 1:
|
| 199 |
+
fc.fc1.weight.data = self.fc.weight.data
|
| 200 |
+
fc.sigma.data = self.fc.sigma.data
|
| 201 |
+
else:
|
| 202 |
+
prev_out_features1 = self.fc.fc1.out_features
|
| 203 |
+
fc.fc1.weight.data[:prev_out_features1] = self.fc.fc1.weight.data
|
| 204 |
+
fc.fc1.weight.data[prev_out_features1:] = self.fc.fc2.weight.data
|
| 205 |
+
fc.sigma.data = self.fc.sigma.data
|
| 206 |
+
|
| 207 |
+
del self.fc
|
| 208 |
+
self.fc = fc
|
| 209 |
+
|
| 210 |
+
def generate_fc(self, in_dim, out_dim):
|
| 211 |
+
if self.fc is None:
|
| 212 |
+
fc = CosineLinear(in_dim, out_dim, self.nb_proxy, to_reduce=True)
|
| 213 |
+
else:
|
| 214 |
+
prev_out_features = self.fc.out_features // self.nb_proxy
|
| 215 |
+
# prev_out_features = self.fc.out_features
|
| 216 |
+
fc = SplitCosineLinear(
|
| 217 |
+
in_dim, prev_out_features, out_dim - prev_out_features, self.nb_proxy
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
return fc
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class BiasLayer_BIC(nn.Module):
|
| 224 |
+
def __init__(self):
|
| 225 |
+
super(BiasLayer_BIC, self).__init__()
|
| 226 |
+
self.alpha = nn.Parameter(torch.ones(1, requires_grad=True))
|
| 227 |
+
self.beta = nn.Parameter(torch.zeros(1, requires_grad=True))
|
| 228 |
+
|
| 229 |
+
def forward(self, x, low_range, high_range):
|
| 230 |
+
ret_x = x.clone()
|
| 231 |
+
ret_x[:, low_range:high_range] = (
|
| 232 |
+
self.alpha * x[:, low_range:high_range] + self.beta
|
| 233 |
+
)
|
| 234 |
+
return ret_x
|
| 235 |
+
|
| 236 |
+
def get_params(self):
|
| 237 |
+
return (self.alpha.item(), self.beta.item())
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class IncrementalNetWithBias(BaseNet):
|
| 241 |
+
def __init__(self, args, pretrained, bias_correction=False):
|
| 242 |
+
super().__init__(args, pretrained)
|
| 243 |
+
|
| 244 |
+
# Bias layer
|
| 245 |
+
self.bias_correction = bias_correction
|
| 246 |
+
self.bias_layers = nn.ModuleList([])
|
| 247 |
+
self.task_sizes = []
|
| 248 |
+
|
| 249 |
+
def forward(self, x):
|
| 250 |
+
x = self.convnet(x)
|
| 251 |
+
out = self.fc(x["features"])
|
| 252 |
+
if self.bias_correction:
|
| 253 |
+
logits = out["logits"]
|
| 254 |
+
for i, layer in enumerate(self.bias_layers):
|
| 255 |
+
logits = layer(
|
| 256 |
+
logits, sum(self.task_sizes[:i]), sum(self.task_sizes[: i + 1])
|
| 257 |
+
)
|
| 258 |
+
out["logits"] = logits
|
| 259 |
+
|
| 260 |
+
out.update(x)
|
| 261 |
+
|
| 262 |
+
return out
|
| 263 |
+
|
| 264 |
+
def update_fc(self, nb_classes):
|
| 265 |
+
fc = self.generate_fc(self.feature_dim, nb_classes)
|
| 266 |
+
if self.fc is not None:
|
| 267 |
+
nb_output = self.fc.out_features
|
| 268 |
+
weight = copy.deepcopy(self.fc.weight.data)
|
| 269 |
+
bias = copy.deepcopy(self.fc.bias.data)
|
| 270 |
+
fc.weight.data[:nb_output] = weight
|
| 271 |
+
fc.bias.data[:nb_output] = bias
|
| 272 |
+
|
| 273 |
+
del self.fc
|
| 274 |
+
self.fc = fc
|
| 275 |
+
|
| 276 |
+
new_task_size = nb_classes - sum(self.task_sizes)
|
| 277 |
+
self.task_sizes.append(new_task_size)
|
| 278 |
+
self.bias_layers.append(BiasLayer_BIC())
|
| 279 |
+
|
| 280 |
+
def generate_fc(self, in_dim, out_dim):
|
| 281 |
+
fc = SimpleLinear(in_dim, out_dim)
|
| 282 |
+
|
| 283 |
+
return fc
|
| 284 |
+
|
| 285 |
+
def get_bias_params(self):
|
| 286 |
+
params = []
|
| 287 |
+
for layer in self.bias_layers:
|
| 288 |
+
params.append(layer.get_params())
|
| 289 |
+
|
| 290 |
+
return params
|
| 291 |
+
|
| 292 |
+
def unfreeze(self):
|
| 293 |
+
for param in self.parameters():
|
| 294 |
+
param.requires_grad = True
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class DERNet(nn.Module):
|
| 298 |
+
def __init__(self, args, pretrained):
|
| 299 |
+
super(DERNet, self).__init__()
|
| 300 |
+
self.convnet_type = args["convnet_type"]
|
| 301 |
+
self.convnets = nn.ModuleList()
|
| 302 |
+
self.pretrained = pretrained
|
| 303 |
+
self.out_dim = None
|
| 304 |
+
self.fc = None
|
| 305 |
+
self.aux_fc = None
|
| 306 |
+
self.task_sizes = []
|
| 307 |
+
self.args = args
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def feature_dim(self):
|
| 311 |
+
if self.out_dim is None:
|
| 312 |
+
return 0
|
| 313 |
+
return self.out_dim * len(self.convnets)
|
| 314 |
+
|
| 315 |
+
def extract_vector(self, x):
|
| 316 |
+
features = [convnet(x)["features"] for convnet in self.convnets]
|
| 317 |
+
features = torch.cat(features, 1)
|
| 318 |
+
return features
|
| 319 |
+
|
| 320 |
+
def forward(self, x):
|
| 321 |
+
features = [convnet(x)["features"] for convnet in self.convnets]
|
| 322 |
+
features = torch.cat(features, 1)
|
| 323 |
+
|
| 324 |
+
out = self.fc(features) # {logics: self.fc(features)}
|
| 325 |
+
|
| 326 |
+
aux_logits = self.aux_fc(features[:, -self.out_dim :])["logits"]
|
| 327 |
+
|
| 328 |
+
out.update({"aux_logits": aux_logits, "features": features})
|
| 329 |
+
return out
|
| 330 |
+
"""
|
| 331 |
+
{
|
| 332 |
+
'features': features
|
| 333 |
+
'logits': logits
|
| 334 |
+
'aux_logits':aux_logits
|
| 335 |
+
}
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
def update_fc(self, nb_classes):
|
| 339 |
+
if len(self.convnets) == 0:
|
| 340 |
+
self.convnets.append(get_convnet(self.args))
|
| 341 |
+
else:
|
| 342 |
+
self.convnets.append(get_convnet(self.args))
|
| 343 |
+
self.convnets[-1].load_state_dict(self.convnets[-2].state_dict())
|
| 344 |
+
|
| 345 |
+
if self.out_dim is None:
|
| 346 |
+
self.out_dim = self.convnets[-1].out_dim
|
| 347 |
+
fc = self.generate_fc(self.feature_dim, nb_classes)
|
| 348 |
+
if self.fc is not None:
|
| 349 |
+
nb_output = self.fc.out_features
|
| 350 |
+
weight = copy.deepcopy(self.fc.weight.data)
|
| 351 |
+
bias = copy.deepcopy(self.fc.bias.data)
|
| 352 |
+
fc.weight.data[:nb_output, : self.feature_dim - self.out_dim] = weight
|
| 353 |
+
fc.bias.data[:nb_output] = bias
|
| 354 |
+
|
| 355 |
+
del self.fc
|
| 356 |
+
self.fc = fc
|
| 357 |
+
|
| 358 |
+
new_task_size = nb_classes - sum(self.task_sizes)
|
| 359 |
+
self.task_sizes.append(new_task_size)
|
| 360 |
+
|
| 361 |
+
self.aux_fc = self.generate_fc(self.out_dim, new_task_size + 1)
|
| 362 |
+
|
| 363 |
+
def generate_fc(self, in_dim, out_dim):
|
| 364 |
+
fc = SimpleLinear(in_dim, out_dim)
|
| 365 |
+
|
| 366 |
+
return fc
|
| 367 |
+
|
| 368 |
+
def copy(self):
|
| 369 |
+
return copy.deepcopy(self)
|
| 370 |
+
|
| 371 |
+
def freeze(self):
|
| 372 |
+
for param in self.parameters():
|
| 373 |
+
param.requires_grad = False
|
| 374 |
+
self.eval()
|
| 375 |
+
|
| 376 |
+
return self
|
| 377 |
+
|
| 378 |
+
def freeze_conv(self):
|
| 379 |
+
for param in self.convnets.parameters():
|
| 380 |
+
param.requires_grad = False
|
| 381 |
+
self.convnets.eval()
|
| 382 |
+
|
| 383 |
+
def weight_align(self, increment):
|
| 384 |
+
weights = self.fc.weight.data
|
| 385 |
+
newnorm = torch.norm(weights[-increment:, :], p=2, dim=1)
|
| 386 |
+
oldnorm = torch.norm(weights[:-increment, :], p=2, dim=1)
|
| 387 |
+
meannew = torch.mean(newnorm)
|
| 388 |
+
meanold = torch.mean(oldnorm)
|
| 389 |
+
gamma = meanold / meannew
|
| 390 |
+
#print("alignweights,gamma=", gamma)
|
| 391 |
+
self.fc.weight.data[-increment:, :] *= gamma
|
| 392 |
+
|
| 393 |
+
def load_checkpoint(self, args):
|
| 394 |
+
checkpoint_name = f"checkpoints/finetune_{args['csv_name']}_0.pkl"
|
| 395 |
+
model_infos = torch.load(checkpoint_name)
|
| 396 |
+
assert len(self.convnets) == 1
|
| 397 |
+
self.convnets[0].load_state_dict(model_infos['convnet'])
|
| 398 |
+
self.fc.load_state_dict(model_infos['fc'])
|
| 399 |
+
test_acc = model_infos['test_acc']
|
| 400 |
+
return test_acc
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class SimpleCosineIncrementalNet(BaseNet):
|
| 404 |
+
def __init__(self, args, pretrained):
|
| 405 |
+
super().__init__(args, pretrained)
|
| 406 |
+
|
| 407 |
+
def update_fc(self, nb_classes, nextperiod_initialization=None):
|
| 408 |
+
fc = self.generate_fc(self.feature_dim, nb_classes).cuda()
|
| 409 |
+
if self.fc is not None:
|
| 410 |
+
nb_output = self.fc.out_features
|
| 411 |
+
weight = copy.deepcopy(self.fc.weight.data)
|
| 412 |
+
fc.sigma.data = self.fc.sigma.data
|
| 413 |
+
if nextperiod_initialization is not None:
|
| 414 |
+
|
| 415 |
+
weight = torch.cat([weight, nextperiod_initialization])
|
| 416 |
+
else:
|
| 417 |
+
weight = torch.cat([weight, torch.zeros(nb_classes - nb_output, self.feature_dim).cuda()])
|
| 418 |
+
fc.weight = nn.Parameter(weight)
|
| 419 |
+
del self.fc
|
| 420 |
+
self.fc = fc
|
| 421 |
+
|
| 422 |
+
def generate_fc(self, in_dim, out_dim):
|
| 423 |
+
fc = CosineLinear(in_dim, out_dim)
|
| 424 |
+
return fc
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class FOSTERNet(nn.Module):
|
| 428 |
+
def __init__(self, args, pretrained):
|
| 429 |
+
super(FOSTERNet, self).__init__()
|
| 430 |
+
self.convnet_type = args["convnet_type"]
|
| 431 |
+
self.convnets = nn.ModuleList()
|
| 432 |
+
self.pretrained = pretrained
|
| 433 |
+
self.out_dim = None
|
| 434 |
+
self.fc = None
|
| 435 |
+
self.fe_fc = None
|
| 436 |
+
self.task_sizes = []
|
| 437 |
+
self.oldfc = None
|
| 438 |
+
self.args = args
|
| 439 |
+
|
| 440 |
+
@property
|
| 441 |
+
def feature_dim(self):
|
| 442 |
+
if self.out_dim is None:
|
| 443 |
+
return 0
|
| 444 |
+
return self.out_dim * len(self.convnets)
|
| 445 |
+
|
| 446 |
+
def extract_vector(self, x):
|
| 447 |
+
features = [convnet(x)["features"] for convnet in self.convnets]
|
| 448 |
+
features = torch.cat(features, 1)
|
| 449 |
+
return features
|
| 450 |
+
|
| 451 |
+
def forward(self, x):
|
| 452 |
+
features = [convnet(x)["features"] for convnet in self.convnets]
|
| 453 |
+
features = torch.cat(features, 1)
|
| 454 |
+
out = self.fc(features)
|
| 455 |
+
fe_logits = self.fe_fc(features[:, -self.out_dim :])["logits"]
|
| 456 |
+
|
| 457 |
+
out.update({"fe_logits": fe_logits, "features": features})
|
| 458 |
+
|
| 459 |
+
if self.oldfc is not None:
|
| 460 |
+
old_logits = self.oldfc(features[:, : -self.out_dim])["logits"]
|
| 461 |
+
out.update({"old_logits": old_logits})
|
| 462 |
+
|
| 463 |
+
out.update({"eval_logits": out["logits"]})
|
| 464 |
+
return out
|
| 465 |
+
|
| 466 |
+
def update_fc(self, nb_classes):
|
| 467 |
+
self.convnets.append(get_convnet(self.args))
|
| 468 |
+
if self.out_dim is None:
|
| 469 |
+
self.out_dim = self.convnets[-1].out_dim
|
| 470 |
+
fc = self.generate_fc(self.feature_dim, nb_classes)
|
| 471 |
+
if self.fc is not None:
|
| 472 |
+
nb_output = self.fc.out_features
|
| 473 |
+
weight = copy.deepcopy(self.fc.weight.data)
|
| 474 |
+
bias = copy.deepcopy(self.fc.bias.data)
|
| 475 |
+
fc.weight.data[:nb_output, : self.feature_dim - self.out_dim] = weight
|
| 476 |
+
fc.bias.data[:nb_output] = bias
|
| 477 |
+
self.convnets[-1].load_state_dict(self.convnets[-2].state_dict())
|
| 478 |
+
|
| 479 |
+
self.oldfc = self.fc
|
| 480 |
+
self.fc = fc
|
| 481 |
+
new_task_size = nb_classes - sum(self.task_sizes)
|
| 482 |
+
self.task_sizes.append(new_task_size)
|
| 483 |
+
self.fe_fc = self.generate_fc(self.out_dim, nb_classes)
|
| 484 |
+
|
| 485 |
+
def generate_fc(self, in_dim, out_dim):
|
| 486 |
+
fc = SimpleLinear(in_dim, out_dim)
|
| 487 |
+
return fc
|
| 488 |
+
|
| 489 |
+
def copy(self):
|
| 490 |
+
return copy.deepcopy(self)
|
| 491 |
+
|
| 492 |
+
def copy_fc(self, fc):
|
| 493 |
+
weight = copy.deepcopy(fc.weight.data)
|
| 494 |
+
bias = copy.deepcopy(fc.bias.data)
|
| 495 |
+
n, m = weight.shape[0], weight.shape[1]
|
| 496 |
+
self.fc.weight.data[:n, :m] = weight
|
| 497 |
+
self.fc.bias.data[:n] = bias
|
| 498 |
+
|
| 499 |
+
def freeze(self):
|
| 500 |
+
for param in self.parameters():
|
| 501 |
+
param.requires_grad = False
|
| 502 |
+
self.eval()
|
| 503 |
+
return self
|
| 504 |
+
|
| 505 |
+
def freeze_conv(self):
|
| 506 |
+
for param in self.convnets.parameters():
|
| 507 |
+
param.requires_grad = False
|
| 508 |
+
self.convnets.eval()
|
| 509 |
+
|
| 510 |
+
def weight_align(self, old, increment, value):
|
| 511 |
+
weights = self.fc.weight.data
|
| 512 |
+
newnorm = torch.norm(weights[-increment:, :], p=2, dim=1)
|
| 513 |
+
oldnorm = torch.norm(weights[:-increment, :], p=2, dim=1)
|
| 514 |
+
meannew = torch.mean(newnorm)
|
| 515 |
+
meanold = torch.mean(oldnorm)
|
| 516 |
+
gamma = meanold / meannew * (value ** (old / increment))
|
| 517 |
+
logging.info("align weights, gamma = {} ".format(gamma))
|
| 518 |
+
self.fc.weight.data[-increment:, :] *= gamma
|
| 519 |
+
|
| 520 |
+
def load_checkpoint(self, args):
|
| 521 |
+
if args["init_cls"] == 50:
|
| 522 |
+
pkl_name = "{}_{}_{}_B{}_Inc{}".format(
|
| 523 |
+
args["dataset"],
|
| 524 |
+
args["seed"],
|
| 525 |
+
args["convnet_type"],
|
| 526 |
+
0,
|
| 527 |
+
args["init_cls"],
|
| 528 |
+
)
|
| 529 |
+
checkpoint_name = f"checkpoints/finetune_{pkl_name}_0.pkl"
|
| 530 |
+
else:
|
| 531 |
+
checkpoint_name = f"checkpoints/finetune_{args['csv_name']}_0.pkl"
|
| 532 |
+
model_infos = torch.load(checkpoint_name)
|
| 533 |
+
assert len(self.convnets) == 1
|
| 534 |
+
self.convnets[0].load_state_dict(model_infos['convnet'])
|
| 535 |
+
self.fc.load_state_dict(model_infos['fc'])
|
| 536 |
+
test_acc = model_infos['test_acc']
|
| 537 |
+
return test_acc
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
class BiasLayer(nn.Module):
|
| 541 |
+
def __init__(self):
|
| 542 |
+
super(BiasLayer, self).__init__()
|
| 543 |
+
self.alpha = nn.Parameter(torch.zeros(1, requires_grad=True))
|
| 544 |
+
self.beta = nn.Parameter(torch.zeros(1, requires_grad=True))
|
| 545 |
+
|
| 546 |
+
def forward(self, x , bias=True):
|
| 547 |
+
ret_x = x.clone()
|
| 548 |
+
ret_x = (self.alpha+1) * x # + self.beta
|
| 549 |
+
if bias:
|
| 550 |
+
ret_x = ret_x + self.beta
|
| 551 |
+
return ret_x
|
| 552 |
+
|
| 553 |
+
def get_params(self):
|
| 554 |
+
return (self.alpha.item(), self.beta.item())
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
class BEEFISONet(nn.Module):
|
| 558 |
+
def __init__(self, args, pretrained):
|
| 559 |
+
super(BEEFISONet, self).__init__()
|
| 560 |
+
self.convnet_type = args["convnet_type"]
|
| 561 |
+
self.convnets = nn.ModuleList()
|
| 562 |
+
self.pretrained = pretrained
|
| 563 |
+
self.out_dim = None
|
| 564 |
+
self.old_fc = None
|
| 565 |
+
self.new_fc = None
|
| 566 |
+
self.task_sizes = []
|
| 567 |
+
self.forward_prototypes = None
|
| 568 |
+
self.backward_prototypes = None
|
| 569 |
+
self.args = args
|
| 570 |
+
self.biases = nn.ModuleList()
|
| 571 |
+
|
| 572 |
+
@property
|
| 573 |
+
def feature_dim(self):
|
| 574 |
+
if self.out_dim is None:
|
| 575 |
+
return 0
|
| 576 |
+
return self.out_dim * len(self.convnets)
|
| 577 |
+
|
| 578 |
+
def extract_vector(self, x):
|
| 579 |
+
features = [convnet(x)["features"] for convnet in self.convnets]
|
| 580 |
+
features = torch.cat(features, 1)
|
| 581 |
+
return features
|
| 582 |
+
|
| 583 |
+
def forward(self, x):
|
| 584 |
+
features = [convnet(x)["features"] for convnet in self.convnets]
|
| 585 |
+
features = torch.cat(features, 1)
|
| 586 |
+
|
| 587 |
+
if self.old_fc is None:
|
| 588 |
+
fc = self.new_fc
|
| 589 |
+
out = fc(features)
|
| 590 |
+
else:
|
| 591 |
+
'''
|
| 592 |
+
merge the weights
|
| 593 |
+
'''
|
| 594 |
+
new_task_size = self.task_sizes[-1]
|
| 595 |
+
fc_weight = torch.cat([self.old_fc.weight,torch.zeros((new_task_size,self.feature_dim-self.out_dim)).cuda()],dim=0)
|
| 596 |
+
new_fc_weight = self.new_fc.weight
|
| 597 |
+
new_fc_bias = self.new_fc.bias
|
| 598 |
+
for i in range(len(self.task_sizes)-2,-1,-1):
|
| 599 |
+
new_fc_weight = torch.cat([*[self.biases[i](self.backward_prototypes.weight[i].unsqueeze(0),bias=False) for _ in range(self.task_sizes[i])],new_fc_weight],dim=0)
|
| 600 |
+
new_fc_bias = torch.cat([*[self.biases[i](self.backward_prototypes.bias[i].unsqueeze(0),bias=True) for _ in range(self.task_sizes[i])], new_fc_bias])
|
| 601 |
+
fc_weight = torch.cat([fc_weight,new_fc_weight],dim=1)
|
| 602 |
+
fc_bias = torch.cat([self.old_fc.bias,torch.zeros(new_task_size).cuda()])
|
| 603 |
+
fc_bias=+new_fc_bias
|
| 604 |
+
logits = features@fc_weight.permute(1,0)+fc_bias
|
| 605 |
+
out = {"logits":logits}
|
| 606 |
+
|
| 607 |
+
new_fc_weight = self.new_fc.weight
|
| 608 |
+
new_fc_bias = self.new_fc.bias
|
| 609 |
+
for i in range(len(self.task_sizes)-2,-1,-1):
|
| 610 |
+
new_fc_weight = torch.cat([self.backward_prototypes.weight[i].unsqueeze(0),new_fc_weight],dim=0)
|
| 611 |
+
new_fc_bias = torch.cat([self.backward_prototypes.bias[i].unsqueeze(0), new_fc_bias])
|
| 612 |
+
out["train_logits"] = features[:,-self.out_dim:]@new_fc_weight.permute(1,0)+new_fc_bias
|
| 613 |
+
out.update({"eval_logits": out["logits"],"energy_logits":self.forward_prototypes(features[:,-self.out_dim:])["logits"]})
|
| 614 |
+
return out
|
| 615 |
+
|
| 616 |
+
def update_fc_before(self, nb_classes):
|
| 617 |
+
new_task_size = nb_classes - sum(self.task_sizes)
|
| 618 |
+
self.biases = nn.ModuleList([BiasLayer() for i in range(len(self.task_sizes))])
|
| 619 |
+
self.convnets.append(get_convnet(self.args))
|
| 620 |
+
if self.out_dim is None:
|
| 621 |
+
self.out_dim = self.convnets[-1].out_dim
|
| 622 |
+
if self.new_fc is not None:
|
| 623 |
+
self.fe_fc = self.generate_fc(self.out_dim, nb_classes)
|
| 624 |
+
self.backward_prototypes = self.generate_fc(self.out_dim,len(self.task_sizes))
|
| 625 |
+
self.convnets[-1].load_state_dict(self.convnets[0].state_dict())
|
| 626 |
+
self.forward_prototypes = self.generate_fc(self.out_dim, nb_classes)
|
| 627 |
+
self.new_fc = self.generate_fc(self.out_dim,new_task_size)
|
| 628 |
+
self.task_sizes.append(new_task_size)
|
| 629 |
+
def generate_fc(self, in_dim, out_dim):
|
| 630 |
+
fc = SimpleLinear(in_dim, out_dim)
|
| 631 |
+
return fc
|
| 632 |
+
|
| 633 |
+
def update_fc_after(self):
|
| 634 |
+
if self.old_fc is not None:
|
| 635 |
+
old_fc = self.generate_fc(self.feature_dim, sum(self.task_sizes))
|
| 636 |
+
new_task_size = self.task_sizes[-1]
|
| 637 |
+
old_fc.weight.data = torch.cat([self.old_fc.weight.data,torch.zeros((new_task_size,self.feature_dim-self.out_dim)).cuda()],dim=0)
|
| 638 |
+
new_fc_weight = self.new_fc.weight.data
|
| 639 |
+
new_fc_bias = self.new_fc.bias.data
|
| 640 |
+
for i in range(len(self.task_sizes)-2,-1,-1):
|
| 641 |
+
new_fc_weight = torch.cat([*[self.biases[i](self.backward_prototypes.weight.data[i].unsqueeze(0),bias=False) for _ in range(self.task_sizes[i])], new_fc_weight],dim=0)
|
| 642 |
+
new_fc_bias = torch.cat([*[self.biases[i](self.backward_prototypes.bias.data[i].unsqueeze(0),bias=True) for _ in range(self.task_sizes[i])], new_fc_bias])
|
| 643 |
+
old_fc.weight.data = torch.cat([old_fc.weight.data,new_fc_weight],dim=1)
|
| 644 |
+
old_fc.bias.data = torch.cat([self.old_fc.bias.data,torch.zeros(new_task_size).cuda()])
|
| 645 |
+
old_fc.bias.data+=new_fc_bias
|
| 646 |
+
self.old_fc = old_fc
|
| 647 |
+
else:
|
| 648 |
+
self.old_fc = self.new_fc
|
| 649 |
+
|
| 650 |
+
def copy(self):
|
| 651 |
+
return copy.deepcopy(self)
|
| 652 |
+
|
| 653 |
+
def copy_fc(self, fc):
|
| 654 |
+
weight = copy.deepcopy(fc.weight.data)
|
| 655 |
+
bias = copy.deepcopy(fc.bias.data)
|
| 656 |
+
n, m = weight.shape[0], weight.shape[1]
|
| 657 |
+
self.fc.weight.data[:n, :m] = weight
|
| 658 |
+
self.fc.bias.data[:n] = bias
|
| 659 |
+
|
| 660 |
+
def freeze(self):
|
| 661 |
+
for param in self.parameters():
|
| 662 |
+
param.requires_grad = False
|
| 663 |
+
self.eval()
|
| 664 |
+
return self
|
| 665 |
+
|
| 666 |
+
def freeze_conv(self):
|
| 667 |
+
for param in self.convnets.parameters():
|
| 668 |
+
param.requires_grad = False
|
| 669 |
+
self.convnets.eval()
|
| 670 |
+
|
| 671 |
+
def weight_align(self, old, increment, value):
|
| 672 |
+
weights = self.fc.weight.data
|
| 673 |
+
newnorm = torch.norm(weights[-increment:, :], p=2, dim=1)
|
| 674 |
+
oldnorm = torch.norm(weights[:-increment, :], p=2, dim=1)
|
| 675 |
+
meannew = torch.mean(newnorm)
|
| 676 |
+
meanold = torch.mean(oldnorm)
|
| 677 |
+
gamma = meanold / meannew * (value ** (old / increment))
|
| 678 |
+
logging.info("align weights, gamma = {} ".format(gamma))
|
| 679 |
+
self.fc.weight.data[-increment:, :] *= gamma
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
class AdaptiveNet(nn.Module):
|
| 683 |
+
def __init__(self, args, pretrained):
|
| 684 |
+
super(AdaptiveNet, self).__init__()
|
| 685 |
+
self.convnet_type = args["convnet_type"]
|
| 686 |
+
self.TaskAgnosticExtractor , _ = get_convnet(args, pretrained) #Generalized blocks
|
| 687 |
+
self.TaskAgnosticExtractor.train()
|
| 688 |
+
self.AdaptiveExtractors = nn.ModuleList() #Specialized Blocks
|
| 689 |
+
self.pretrained=pretrained
|
| 690 |
+
self.out_dim=None
|
| 691 |
+
self.fc = None
|
| 692 |
+
self.aux_fc=None
|
| 693 |
+
self.task_sizes = []
|
| 694 |
+
self.args=args
|
| 695 |
+
self.avg_threshold = args["init_cls"] + 2 * args["increment"]
|
| 696 |
+
self.inc_cls = args["increment"]
|
| 697 |
+
|
| 698 |
+
@property
|
| 699 |
+
def feature_dim(self):
|
| 700 |
+
if self.out_dim is None:
|
| 701 |
+
return 0
|
| 702 |
+
return self.out_dim*len(self.AdaptiveExtractors)
|
| 703 |
+
|
| 704 |
+
def extract_vector(self, x):
|
| 705 |
+
base_feature_map = self.TaskAgnosticExtractor(x)
|
| 706 |
+
features = [extractor(base_feature_map) for extractor in self.AdaptiveExtractors]
|
| 707 |
+
features = torch.cat(features, 1)
|
| 708 |
+
return features
|
| 709 |
+
|
| 710 |
+
def forward(self, x):
|
| 711 |
+
base_feature_map = self.TaskAgnosticExtractor(x)
|
| 712 |
+
features = [extractor(base_feature_map) for extractor in self.AdaptiveExtractors]
|
| 713 |
+
features = torch.cat(features, 1)
|
| 714 |
+
out=self.fc(features) #{logits: self.fc(features)}
|
| 715 |
+
|
| 716 |
+
aux_logits=self.aux_fc(features[:,-self.out_dim:])["logits"]
|
| 717 |
+
|
| 718 |
+
out.update({"aux_logits":aux_logits,"features":features})
|
| 719 |
+
out.update({"base_features":base_feature_map})
|
| 720 |
+
return out
|
| 721 |
+
|
| 722 |
+
'''
|
| 723 |
+
{
|
| 724 |
+
'features': features
|
| 725 |
+
'logits': logits
|
| 726 |
+
'aux_logits':aux_logits
|
| 727 |
+
}
|
| 728 |
+
'''
|
| 729 |
+
|
| 730 |
+
def merge_and_average_state_dicts(self, extractors):
|
| 731 |
+
"""
|
| 732 |
+
Merge and average state dictionaries of two modules.
|
| 733 |
+
|
| 734 |
+
Given two modules, this method merges their state dictionaries and averages the values of common keys.
|
| 735 |
+
|
| 736 |
+
Parameters:
|
| 737 |
+
extractors (list): List of module instances.
|
| 738 |
+
|
| 739 |
+
Returns:
|
| 740 |
+
dict: Merged and averaged state dictionary.
|
| 741 |
+
"""
|
| 742 |
+
module1 = extractors[0].state_dict()
|
| 743 |
+
module2 = extractors[1].state_dict()
|
| 744 |
+
all_keys = module1.keys() | module2.keys()
|
| 745 |
+
result_module = {}
|
| 746 |
+
for key in all_keys:
|
| 747 |
+
if key in module1 and key in module2:
|
| 748 |
+
avg_value = (module1[key] + module2[key]) / 2.0
|
| 749 |
+
result_module[key] = avg_value
|
| 750 |
+
elif key in module1:
|
| 751 |
+
result_module[key] = module1[key]
|
| 752 |
+
elif key in module2:
|
| 753 |
+
result_module[key] = module2[key]
|
| 754 |
+
return result_module
|
| 755 |
+
|
| 756 |
+
def merge_prev_layers(self):
|
| 757 |
+
"""
|
| 758 |
+
Merge layers from previous tasks.
|
| 759 |
+
|
| 760 |
+
This method merges layers from the previous two tasks based on their index values.
|
| 761 |
+
|
| 762 |
+
Returns:
|
| 763 |
+
list: Merged list of layers from the previous tasks.
|
| 764 |
+
"""
|
| 765 |
+
curr_task = self.args["curr"]
|
| 766 |
+
p = curr_task - 1
|
| 767 |
+
pp = curr_task - 2
|
| 768 |
+
lst1 = self.args["layers"][p]
|
| 769 |
+
lst2 = self.args["layers"][pp]
|
| 770 |
+
if len(lst1) == 1:
|
| 771 |
+
lst1.append(0)
|
| 772 |
+
if len(lst2) == 1:
|
| 773 |
+
lst2.append(0)
|
| 774 |
+
lst3 = []
|
| 775 |
+
for x, y in zip(lst1, lst2):
|
| 776 |
+
lst3.append(x if x > y else y)
|
| 777 |
+
if lst3[-1] == 0:
|
| 778 |
+
lst3 = lst3[:-1]
|
| 779 |
+
|
| 780 |
+
return lst3
|
| 781 |
+
|
| 782 |
+
def return_specialized_block(self, nconv):
|
| 783 |
+
"""
|
| 784 |
+
Return a specialized block based on the given convolutional layers.
|
| 785 |
+
|
| 786 |
+
This method returns a specialized ResNet block with a specific number of convolutional layers.
|
| 787 |
+
|
| 788 |
+
Parameters:
|
| 789 |
+
nconv (list): list of no of convolutional layers.
|
| 790 |
+
|
| 791 |
+
Returns:
|
| 792 |
+
nn.Module: Specialized ResNet block.
|
| 793 |
+
"""
|
| 794 |
+
return memor.SpecializedResNet_imagenet(memor.BasicBlock, layers=[2,2,2,len(nconv)], nconv=nconv)
|
| 795 |
+
|
| 796 |
+
def update_fc(self,nb_classes):
|
| 797 |
+
_ , _new_extractor = get_convnet(self.args)
|
| 798 |
+
|
| 799 |
+
if len(self.AdaptiveExtractors)==0:
|
| 800 |
+
self.AdaptiveExtractors.append(_new_extractor)
|
| 801 |
+
|
| 802 |
+
else:
|
| 803 |
+
if len(self.AdaptiveExtractors)==2 and self.args["type"] == "avg":
|
| 804 |
+
avg_vals = self.merge_and_average_state_dicts(self.AdaptiveExtractors)
|
| 805 |
+
new_layer = self.merge_prev_layers()
|
| 806 |
+
specialized_block = self.return_specialized_block(nconv=new_layer)
|
| 807 |
+
self.AdaptiveExtractors = nn.ModuleList([specialized_block])
|
| 808 |
+
self.AdaptiveExtractors[0].load_state_dict(avg_vals)
|
| 809 |
+
|
| 810 |
+
self.AdaptiveExtractors.append(_new_extractor)
|
| 811 |
+
self.AdaptiveExtractors[-1].load_state_dict(self.AdaptiveExtractors[-2].state_dict(), strict=False)
|
| 812 |
+
|
| 813 |
+
if self.out_dim is None:
|
| 814 |
+
self.out_dim=self.AdaptiveExtractors[-1].feature_dim
|
| 815 |
+
|
| 816 |
+
if self.fc is not None:
|
| 817 |
+
logging.debug("Previous FC is {}x{}".format(self.fc.in_features, self.fc.out_features))
|
| 818 |
+
|
| 819 |
+
logging.debug("Generating the FC of size --> {}x{}".format(self.feature_dim, nb_classes))
|
| 820 |
+
|
| 821 |
+
fc = self.generate_fc(self.feature_dim, nb_classes)
|
| 822 |
+
|
| 823 |
+
if self.fc is not None:
|
| 824 |
+
nb_output = self.fc.out_features
|
| 825 |
+
weight = copy.deepcopy(self.fc.weight.data)
|
| 826 |
+
|
| 827 |
+
if nb_classes >= self.avg_threshold and self.args["type"] == "avg":
|
| 828 |
+
weight = torch.mean(weight.view(nb_classes-self.inc_cls, self.out_dim, 2), dim=2)
|
| 829 |
+
|
| 830 |
+
bias = copy.deepcopy(self.fc.bias.data)
|
| 831 |
+
fc.weight.data[:nb_output,:self.feature_dim-self.out_dim] = weight
|
| 832 |
+
fc.bias.data[:nb_output] = bias
|
| 833 |
+
|
| 834 |
+
del self.fc
|
| 835 |
+
self.fc = fc
|
| 836 |
+
new_task_size = nb_classes - sum(self.task_sizes)
|
| 837 |
+
self.task_sizes.append(new_task_size)
|
| 838 |
+
self.aux_fc=self.generate_fc(self.out_dim,new_task_size+1)
|
| 839 |
+
|
| 840 |
+
def generate_fc(self, in_dim, out_dim):
|
| 841 |
+
fc = SimpleLinear(in_dim, out_dim)
|
| 842 |
+
return fc
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
def copy(self):
|
| 846 |
+
return copy.deepcopy(self)
|
| 847 |
+
|
| 848 |
+
def weight_align(self, increment):
|
| 849 |
+
weights=self.fc.weight.data
|
| 850 |
+
newnorm=(torch.norm(weights[-increment:,:],p=2,dim=1))
|
| 851 |
+
oldnorm=(torch.norm(weights[:-increment,:],p=2,dim=1))
|
| 852 |
+
meannew=torch.mean(newnorm)
|
| 853 |
+
meanold=torch.mean(oldnorm)
|
| 854 |
+
gamma=meanold/meannew
|
| 855 |
+
print('alignweights,gamma=',gamma)
|
| 856 |
+
self.fc.weight.data[-increment:,:]*=gamma
|
| 857 |
+
|
| 858 |
+
def load_checkpoint(self, args):
|
| 859 |
+
if args["init_cls"] == 50:
|
| 860 |
+
pkl_name = "{}_{}_{}_B{}_Inc{}".format(
|
| 861 |
+
args["dataset"],
|
| 862 |
+
args["seed"],
|
| 863 |
+
args["convnet_type"],
|
| 864 |
+
0,
|
| 865 |
+
args["init_cls"],
|
| 866 |
+
)
|
| 867 |
+
checkpoint_name = f"checkpoints/finetune_{pkl_name}_0.pkl"
|
| 868 |
+
else:
|
| 869 |
+
checkpoint_name = f"checkpoints/finetune_{args['csv_name']}_0.pkl"
|
| 870 |
+
checkpoint_name = checkpoint_name.replace("memo_", "")
|
| 871 |
+
model_infos = torch.load(checkpoint_name)
|
| 872 |
+
model_dict = model_infos['convnet']
|
| 873 |
+
assert len(self.AdaptiveExtractors) == 1
|
| 874 |
+
|
| 875 |
+
base_state_dict = self.TaskAgnosticExtractor.state_dict()
|
| 876 |
+
adap_state_dict = self.AdaptiveExtractors[0].state_dict()
|
| 877 |
+
|
| 878 |
+
pretrained_base_dict = {
|
| 879 |
+
k:v
|
| 880 |
+
for k, v in model_dict.items()
|
| 881 |
+
if k in base_state_dict
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
+
pretrained_adap_dict = {
|
| 885 |
+
k:v
|
| 886 |
+
for k, v in model_dict.items()
|
| 887 |
+
if k in adap_state_dict
|
| 888 |
+
}
|
| 889 |
+
|
| 890 |
+
base_state_dict.update(pretrained_base_dict)
|
| 891 |
+
adap_state_dict.update(pretrained_adap_dict)
|
| 892 |
+
|
| 893 |
+
self.TaskAgnosticExtractor.load_state_dict(base_state_dict)
|
| 894 |
+
self.AdaptiveExtractors[0].load_state_dict(adap_state_dict)
|
| 895 |
+
self.fc.load_state_dict(model_infos['fc'])
|
| 896 |
+
test_acc = model_infos['test_acc']
|
| 897 |
+
return test_acc
|
utils/ops.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image, ImageEnhance, ImageOps
|
| 2 |
+
import random
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
class Cutout(object):
|
| 6 |
+
def __init__(self, n_holes, length):
|
| 7 |
+
self.n_holes = n_holes
|
| 8 |
+
self.length = length
|
| 9 |
+
|
| 10 |
+
def __call__(self, img):
|
| 11 |
+
h = img.size(1)
|
| 12 |
+
w = img.size(2)
|
| 13 |
+
|
| 14 |
+
mask = np.ones((h, w), np.float32)
|
| 15 |
+
|
| 16 |
+
for n in range(self.n_holes):
|
| 17 |
+
y = np.random.randint(h)
|
| 18 |
+
x = np.random.randint(w)
|
| 19 |
+
|
| 20 |
+
y1 = np.clip(y - self.length // 2, 0, h)
|
| 21 |
+
y2 = np.clip(y + self.length // 2, 0, h)
|
| 22 |
+
x1 = np.clip(x - self.length // 2, 0, w)
|
| 23 |
+
x2 = np.clip(x + self.length // 2, 0, w)
|
| 24 |
+
|
| 25 |
+
mask[y1: y2, x1: x2] = 0.
|
| 26 |
+
|
| 27 |
+
mask = torch.from_numpy(mask)
|
| 28 |
+
mask = mask.expand_as(img)
|
| 29 |
+
img = img * mask
|
| 30 |
+
|
| 31 |
+
return img
|
| 32 |
+
|
| 33 |
+
class ShearX(object):
|
| 34 |
+
def __init__(self, fillcolor=(128, 128, 128)):
|
| 35 |
+
self.fillcolor = fillcolor
|
| 36 |
+
|
| 37 |
+
def __call__(self, x, magnitude):
|
| 38 |
+
return x.transform(
|
| 39 |
+
x.size, Image.AFFINE, (1, magnitude * random.choice([-1, 1]), 0, 0, 1, 0),
|
| 40 |
+
Image.BICUBIC, fillcolor=self.fillcolor)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ShearY(object):
|
| 44 |
+
def __init__(self, fillcolor=(128, 128, 128)):
|
| 45 |
+
self.fillcolor = fillcolor
|
| 46 |
+
|
| 47 |
+
def __call__(self, x, magnitude):
|
| 48 |
+
return x.transform(
|
| 49 |
+
x.size, Image.AFFINE, (1, 0, 0, magnitude * random.choice([-1, 1]), 1, 0),
|
| 50 |
+
Image.BICUBIC, fillcolor=self.fillcolor)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class TranslateX(object):
|
| 54 |
+
def __init__(self, fillcolor=(128, 128, 128)):
|
| 55 |
+
self.fillcolor = fillcolor
|
| 56 |
+
|
| 57 |
+
def __call__(self, x, magnitude):
|
| 58 |
+
return x.transform(
|
| 59 |
+
x.size, Image.AFFINE, (1, 0, magnitude * x.size[0] * random.choice([-1, 1]), 0, 1, 0),
|
| 60 |
+
fillcolor=self.fillcolor)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class TranslateY(object):
|
| 64 |
+
def __init__(self, fillcolor=(128, 128, 128)):
|
| 65 |
+
self.fillcolor = fillcolor
|
| 66 |
+
|
| 67 |
+
def __call__(self, x, magnitude):
|
| 68 |
+
return x.transform(
|
| 69 |
+
x.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * x.size[1] * random.choice([-1, 1])),
|
| 70 |
+
fillcolor=self.fillcolor)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class Rotate(object):
|
| 74 |
+
def __call__(self, x, magnitude):
|
| 75 |
+
rot = x.convert("RGBA").rotate(magnitude * random.choice([-1, 1]))
|
| 76 |
+
return Image.composite(rot, Image.new("RGBA", rot.size, (128,) * 4), rot).convert(x.mode)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class Color(object):
|
| 80 |
+
def __call__(self, x, magnitude):
|
| 81 |
+
return ImageEnhance.Color(x).enhance(1 + magnitude * random.choice([-1, 1]))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class Posterize(object):
|
| 85 |
+
def __call__(self, x, magnitude):
|
| 86 |
+
return ImageOps.posterize(x, magnitude)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class Solarize(object):
|
| 90 |
+
def __call__(self, x, magnitude):
|
| 91 |
+
return ImageOps.solarize(x, magnitude)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class Contrast(object):
|
| 95 |
+
def __call__(self, x, magnitude):
|
| 96 |
+
return ImageEnhance.Contrast(x).enhance(1 + magnitude * random.choice([-1, 1]))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class Sharpness(object):
|
| 100 |
+
def __call__(self, x, magnitude):
|
| 101 |
+
return ImageEnhance.Sharpness(x).enhance(1 + magnitude * random.choice([-1, 1]))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class Brightness(object):
|
| 105 |
+
def __call__(self, x, magnitude):
|
| 106 |
+
return ImageEnhance.Brightness(x).enhance(1 + magnitude * random.choice([-1, 1]))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class AutoContrast(object):
|
| 110 |
+
def __call__(self, x, magnitude):
|
| 111 |
+
return ImageOps.autocontrast(x)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class Equalize(object):
|
| 115 |
+
def __call__(self, x, magnitude):
|
| 116 |
+
return ImageOps.equalize(x)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class Invert(object):
|
| 120 |
+
def __call__(self, x, magnitude):
|
| 121 |
+
return ImageOps.invert(x)
|
utils/rl_utils/ddpg.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import torch
|
| 3 |
+
from torch import nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class PolicyNet(torch.nn.Module):
|
| 9 |
+
def __init__(self, state_dim, hidden_dim, action_dim, action_bound):
|
| 10 |
+
super(PolicyNet, self).__init__()
|
| 11 |
+
self.fc1 = torch.nn.Linear(state_dim, hidden_dim)
|
| 12 |
+
self.fc2 = torch.nn.Linear(hidden_dim, action_dim)
|
| 13 |
+
self.action_bound = action_bound
|
| 14 |
+
|
| 15 |
+
def forward(self, x):
|
| 16 |
+
x = F.relu(self.fc1(x))
|
| 17 |
+
return torch.tanh(self.fc2(x)) * self.action_bound
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class RMMPolicyNet(torch.nn.Module):
|
| 21 |
+
def __init__(self, state_dim, hidden_dim, action_dim):
|
| 22 |
+
super(RMMPolicyNet, self).__init__()
|
| 23 |
+
self.fc1 = nn.Sequential(
|
| 24 |
+
nn.Linear(state_dim, hidden_dim),
|
| 25 |
+
nn.ReLU(inplace=True),
|
| 26 |
+
nn.Linear(hidden_dim, action_dim),
|
| 27 |
+
)
|
| 28 |
+
self.fc2 = nn.Sequential(
|
| 29 |
+
nn.Linear(state_dim+action_dim, hidden_dim),
|
| 30 |
+
nn.ReLU(inplace=True),
|
| 31 |
+
nn.Linear(hidden_dim, action_dim),
|
| 32 |
+
)
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
a1 = torch.sigmoid(self.fc1(x))
|
| 35 |
+
x = torch.cat([x,a1],dim=1)
|
| 36 |
+
a2 = torch.tanh(self.fc2(x))
|
| 37 |
+
return torch.cat([a1,a2],dim=1)
|
| 38 |
+
|
| 39 |
+
class QValueNet(torch.nn.Module):
|
| 40 |
+
def __init__(self, state_dim, hidden_dim, action_dim):
|
| 41 |
+
super(QValueNet, self).__init__()
|
| 42 |
+
self.fc1 = torch.nn.Linear(state_dim + action_dim, hidden_dim)
|
| 43 |
+
self.fc2 = torch.nn.Linear(hidden_dim, 1)
|
| 44 |
+
|
| 45 |
+
def forward(self, x, a):
|
| 46 |
+
cat = torch.cat([x, a], dim=1)
|
| 47 |
+
x = F.relu(self.fc1(cat))
|
| 48 |
+
return self.fc2(x)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class TwoLayerFC(torch.nn.Module):
|
| 52 |
+
def __init__(
|
| 53 |
+
self, num_in, num_out, hidden_dim, activation=F.relu, out_fn=lambda x: x
|
| 54 |
+
):
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.fc1 = nn.Linear(num_in, hidden_dim)
|
| 57 |
+
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
|
| 58 |
+
self.fc3 = nn.Linear(hidden_dim, num_out)
|
| 59 |
+
|
| 60 |
+
self.activation = activation
|
| 61 |
+
self.out_fn = out_fn
|
| 62 |
+
|
| 63 |
+
def forward(self, x):
|
| 64 |
+
x = self.activation(self.fc1(x))
|
| 65 |
+
x = self.activation(self.fc2(x))
|
| 66 |
+
x = self.out_fn(self.fc3(x))
|
| 67 |
+
return x
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class DDPG:
|
| 71 |
+
"""DDPG algo"""
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
num_in_actor,
|
| 76 |
+
num_out_actor,
|
| 77 |
+
num_in_critic,
|
| 78 |
+
hidden_dim,
|
| 79 |
+
discrete,
|
| 80 |
+
action_bound,
|
| 81 |
+
sigma,
|
| 82 |
+
actor_lr,
|
| 83 |
+
critic_lr,
|
| 84 |
+
tau,
|
| 85 |
+
gamma,
|
| 86 |
+
device,
|
| 87 |
+
use_rmm=True,
|
| 88 |
+
):
|
| 89 |
+
|
| 90 |
+
out_fn = (lambda x: x) if discrete else (lambda x: torch.tanh(x) * action_bound)
|
| 91 |
+
|
| 92 |
+
if use_rmm:
|
| 93 |
+
self.actor = RMMPolicyNet(
|
| 94 |
+
num_in_actor,
|
| 95 |
+
hidden_dim,
|
| 96 |
+
num_out_actor,
|
| 97 |
+
).to(device)
|
| 98 |
+
self.target_actor = RMMPolicyNet(
|
| 99 |
+
num_in_actor,
|
| 100 |
+
hidden_dim,
|
| 101 |
+
num_out_actor,
|
| 102 |
+
).to(device)
|
| 103 |
+
else:
|
| 104 |
+
self.actor = TwoLayerFC(
|
| 105 |
+
num_in_actor,
|
| 106 |
+
num_out_actor,
|
| 107 |
+
hidden_dim,
|
| 108 |
+
activation=F.relu,
|
| 109 |
+
out_fn=out_fn,
|
| 110 |
+
).to(device)
|
| 111 |
+
self.target_actor = TwoLayerFC(
|
| 112 |
+
num_in_actor,
|
| 113 |
+
num_out_actor,
|
| 114 |
+
hidden_dim,
|
| 115 |
+
activation=F.relu,
|
| 116 |
+
out_fn=out_fn,
|
| 117 |
+
).to(device)
|
| 118 |
+
|
| 119 |
+
self.critic = TwoLayerFC(num_in_critic, 1, hidden_dim).to(device)
|
| 120 |
+
self.target_critic = TwoLayerFC(num_in_critic, 1, hidden_dim).to(device)
|
| 121 |
+
self.target_critic.load_state_dict(self.critic.state_dict())
|
| 122 |
+
self.target_actor.load_state_dict(self.actor.state_dict())
|
| 123 |
+
self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=actor_lr)
|
| 124 |
+
self.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=critic_lr)
|
| 125 |
+
self.gamma = gamma
|
| 126 |
+
self.sigma = sigma
|
| 127 |
+
self.action_bound = action_bound
|
| 128 |
+
self.tau = tau
|
| 129 |
+
self.action_dim = num_out_actor
|
| 130 |
+
self.device = device
|
| 131 |
+
|
| 132 |
+
def take_action(self, state):
|
| 133 |
+
state = torch.tensor(np.expand_dims(state,0), dtype=torch.float).to(self.device)
|
| 134 |
+
action = self.actor(state)[0].detach().cpu().numpy()
|
| 135 |
+
|
| 136 |
+
action = action + self.sigma * np.random.randn(self.action_dim)
|
| 137 |
+
action[0]=np.clip(action[0],0,1)
|
| 138 |
+
action[1]=np.clip(action[1],-1,1)
|
| 139 |
+
return action
|
| 140 |
+
def save_state_dict(self,name):
|
| 141 |
+
dicts = {
|
| 142 |
+
"critic":self.critic.state_dict(),
|
| 143 |
+
"target_critic":self.target_critic.state_dict(),
|
| 144 |
+
"actor":self.actor.state_dict(),
|
| 145 |
+
"target_actor":self.target_actor.state_dict()
|
| 146 |
+
}
|
| 147 |
+
torch.save(dicts,name)
|
| 148 |
+
def load_state_dict(self,name):
|
| 149 |
+
dicts = torch.load(name)
|
| 150 |
+
self.critic.load_state_dict(dicts["critic"])
|
| 151 |
+
self.target_critic.load_state_dict(dicts["target_critic"])
|
| 152 |
+
self.actor.load_state_dict(dicts["actor"])
|
| 153 |
+
self.target_actor.load_state_dict(dicts["target_actor"])
|
| 154 |
+
def soft_update(self, net, target_net):
|
| 155 |
+
for param_target, param in zip(target_net.parameters(), net.parameters()):
|
| 156 |
+
param_target.data.copy_(
|
| 157 |
+
param_target.data * (1.0 - self.tau) + param.data * self.tau
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
def update(self, transition_dict):
|
| 161 |
+
states = torch.tensor(transition_dict["states"], dtype=torch.float).to(
|
| 162 |
+
self.device
|
| 163 |
+
)
|
| 164 |
+
actions = (
|
| 165 |
+
torch.tensor(transition_dict["actions"], dtype=torch.float)
|
| 166 |
+
.to(self.device)
|
| 167 |
+
)
|
| 168 |
+
rewards = (
|
| 169 |
+
torch.tensor(transition_dict["rewards"], dtype=torch.float)
|
| 170 |
+
.view(-1, 1)
|
| 171 |
+
.to(self.device)
|
| 172 |
+
)
|
| 173 |
+
next_states = torch.tensor(
|
| 174 |
+
transition_dict["next_states"], dtype=torch.float
|
| 175 |
+
).to(self.device)
|
| 176 |
+
dones = (
|
| 177 |
+
torch.tensor(transition_dict["dones"], dtype=torch.float)
|
| 178 |
+
.view(-1, 1)
|
| 179 |
+
.to(self.device)
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
next_q_values = self.target_critic(
|
| 183 |
+
torch.cat([next_states, self.target_actor(next_states)], dim=1)
|
| 184 |
+
)
|
| 185 |
+
q_targets = rewards + self.gamma * next_q_values * (1 - dones)
|
| 186 |
+
critic_loss = torch.mean(
|
| 187 |
+
F.mse_loss(
|
| 188 |
+
self.critic(torch.cat([states, actions], dim=1)),
|
| 189 |
+
q_targets,
|
| 190 |
+
)
|
| 191 |
+
)
|
| 192 |
+
self.critic_optimizer.zero_grad()
|
| 193 |
+
critic_loss.backward()
|
| 194 |
+
self.critic_optimizer.step()
|
| 195 |
+
|
| 196 |
+
actor_loss = -torch.mean(
|
| 197 |
+
self.critic(
|
| 198 |
+
torch.cat([states, self.actor(states)], dim=1)
|
| 199 |
+
)
|
| 200 |
+
)
|
| 201 |
+
self.actor_optimizer.zero_grad()
|
| 202 |
+
actor_loss.backward()
|
| 203 |
+
self.actor_optimizer.step()
|
| 204 |
+
logging.info(f"update DDPG: actor loss {actor_loss.item():.3f}, critic loss {critic_loss.item():.3f}, ")
|
| 205 |
+
self.soft_update(self.actor, self.target_actor) # soft-update the target policy net
|
| 206 |
+
self.soft_update(self.critic, self.target_critic) # soft-update the target Q value net
|
utils/rl_utils/rl_utils.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tqdm import tqdm
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import collections
|
| 5 |
+
import random
|
| 6 |
+
|
| 7 |
+
class ReplayBuffer:
|
| 8 |
+
def __init__(self, capacity):
|
| 9 |
+
self.buffer = collections.deque(maxlen=capacity)
|
| 10 |
+
|
| 11 |
+
def add(self, state, action, reward, next_state, done):
|
| 12 |
+
self.buffer.append((state, action, reward, next_state, done))
|
| 13 |
+
|
| 14 |
+
def sample(self, batch_size):
|
| 15 |
+
transitions = random.sample(self.buffer, batch_size)
|
| 16 |
+
state, action, reward, next_state, done = zip(*transitions)
|
| 17 |
+
return np.array(state), np.array(action), reward, np.array(next_state), done
|
| 18 |
+
|
| 19 |
+
def size(self):
|
| 20 |
+
return len(self.buffer)
|
utils/toolkit.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import json
|
| 5 |
+
from enum import Enum
|
| 6 |
+
|
| 7 |
+
class ConfigEncoder(json.JSONEncoder):
|
| 8 |
+
def default(self, o):
|
| 9 |
+
if isinstance(o, type):
|
| 10 |
+
return {'$class': o.__module__ + "." + o.__name__}
|
| 11 |
+
elif isinstance(o, Enum):
|
| 12 |
+
return {
|
| 13 |
+
'$enum': o.__module__ + "." + o.__class__.__name__ + '.' + o.name
|
| 14 |
+
}
|
| 15 |
+
elif callable(o):
|
| 16 |
+
return {
|
| 17 |
+
'$function': o.__module__ + "." + o.__name__
|
| 18 |
+
}
|
| 19 |
+
return json.JSONEncoder.default(self, o)
|
| 20 |
+
|
| 21 |
+
def count_parameters(model, trainable=False):
|
| 22 |
+
if trainable:
|
| 23 |
+
return sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 24 |
+
return sum(p.numel() for p in model.parameters())
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def tensor2numpy(x):
|
| 28 |
+
return x.cpu().data.numpy() if x.is_cuda else x.data.numpy()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def target2onehot(targets, n_classes):
|
| 32 |
+
onehot = torch.zeros(targets.shape[0], n_classes).to(targets.device)
|
| 33 |
+
onehot.scatter_(dim=1, index=targets.long().view(-1, 1), value=1.0)
|
| 34 |
+
return onehot
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def makedirs(path):
|
| 38 |
+
if not os.path.exists(path):
|
| 39 |
+
os.makedirs(path)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def accuracy(y_pred, y_true, nb_old, increment=2):
|
| 43 |
+
assert len(y_pred) == len(y_true), "Data length error."
|
| 44 |
+
all_acc = {}
|
| 45 |
+
all_acc["total"] = np.around(
|
| 46 |
+
(y_pred == y_true).sum() * 100 / len(y_true), decimals=2
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Grouped accuracy
|
| 50 |
+
for class_id in range(0, np.max(y_true), increment):
|
| 51 |
+
idxes = np.where(
|
| 52 |
+
np.logical_and(y_true >= class_id, y_true < class_id + increment)
|
| 53 |
+
)[0]
|
| 54 |
+
label = "{}-{}".format(
|
| 55 |
+
str(class_id).rjust(2, "0"), str(class_id + increment - 1).rjust(2, "0")
|
| 56 |
+
)
|
| 57 |
+
all_acc[label] = np.around(
|
| 58 |
+
(y_pred[idxes] == y_true[idxes]).sum() * 100 / len(idxes), decimals=2
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Old accuracy
|
| 62 |
+
idxes = np.where(y_true < nb_old)[0]
|
| 63 |
+
all_acc["old"] = (
|
| 64 |
+
0
|
| 65 |
+
if len(idxes) == 0
|
| 66 |
+
else np.around(
|
| 67 |
+
(y_pred[idxes] == y_true[idxes]).sum() * 100 / len(idxes), decimals=2
|
| 68 |
+
)
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# New accuracy
|
| 72 |
+
idxes = np.where(y_true >= nb_old)[0]
|
| 73 |
+
all_acc["new"] = np.around(
|
| 74 |
+
(y_pred[idxes] == y_true[idxes]).sum() * 100 / len(idxes), decimals=2
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
return all_acc
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def split_images_labels(imgs):
|
| 81 |
+
# split trainset.imgs in ImageFolder
|
| 82 |
+
#print('*****************split_images_labels******************')
|
| 83 |
+
images = []
|
| 84 |
+
labels = []
|
| 85 |
+
for item in imgs:
|
| 86 |
+
images.append(item[0])
|
| 87 |
+
labels.append(item[1])
|
| 88 |
+
|
| 89 |
+
return np.array(images), np.array(labels)
|
| 90 |
+
|
| 91 |
+
def save_fc(args, model):
|
| 92 |
+
_path = os.path.join(args['logfilename'], "fc.pt")
|
| 93 |
+
if len(args['device']) > 1:
|
| 94 |
+
fc_weight = model._network.fc.weight.data
|
| 95 |
+
else:
|
| 96 |
+
fc_weight = model._network.fc.weight.data.cpu()
|
| 97 |
+
torch.save(fc_weight, _path)
|
| 98 |
+
|
| 99 |
+
_save_dir = os.path.join(f"./results/fc_weights/{args['prefix']}")
|
| 100 |
+
os.makedirs(_save_dir, exist_ok=True)
|
| 101 |
+
_save_path = os.path.join(_save_dir, f"{args['csv_name']}.csv")
|
| 102 |
+
with open(_save_path, "a+") as f:
|
| 103 |
+
f.write(f"{args['time_str']},{args['model_name']},{_path} \n")
|
| 104 |
+
|
| 105 |
+
def save_model(args, model):
|
| 106 |
+
#used in PODNet
|
| 107 |
+
_path = os.path.join(args['logfilename'], "model.pt")
|
| 108 |
+
if len(args['device']) > 1:
|
| 109 |
+
weight = model._network
|
| 110 |
+
else:
|
| 111 |
+
weight = model._network.cpu()
|
| 112 |
+
torch.save(weight, _path)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
|
utils/tsne.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import os
|
| 4 |
+
from glob import glob
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
def Hbeta(D=np.array([]), beta=1.0):
|
| 9 |
+
"""
|
| 10 |
+
Compute the perplexity and the P-row for a specific value of the
|
| 11 |
+
precision of a Gaussian distribution.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
D (numpy.ndarray): Distance array.
|
| 15 |
+
beta (float): Precision of the Gaussian distribution.
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
tuple: A tuple containing perplexity (H) and the P-row (P).
|
| 19 |
+
"""
|
| 20 |
+
P = np.exp(-D.copy() * beta)
|
| 21 |
+
sumP = sum(P)
|
| 22 |
+
H = np.log(sumP) + beta * np.sum(D * P) / sumP
|
| 23 |
+
P = P / sumP
|
| 24 |
+
return H, P
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def pca(X=np.array([]), no_dims=50):
|
| 28 |
+
# Runs PCA on the NxD array X in order to reduce its dimensionality to no_dims dimensions.
|
| 29 |
+
(n, d) = X.shape
|
| 30 |
+
X = X - np.tile(np.mean(X, 0), (n, 1))
|
| 31 |
+
(l, M) = np.linalg.eig(np.dot(X.T, X))
|
| 32 |
+
Y = np.dot(X, M[:, 0:no_dims])
|
| 33 |
+
return Y
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def x2p(X=np.array([]), tol=1e-5, perplexity=30.0):
|
| 37 |
+
"""
|
| 38 |
+
Performs a binary search to get P-values in such a way that each
|
| 39 |
+
conditional Gaussian has the same perplexity.
|
| 40 |
+
"""
|
| 41 |
+
(n, d) = X.shape
|
| 42 |
+
sum_X = np.sum(np.square(X), 1)
|
| 43 |
+
D = np.add(np.add(-2 * np.dot(X, X.T), sum_X).T, sum_X)
|
| 44 |
+
P = np.zeros((n, n))
|
| 45 |
+
beta = np.ones((n, 1))
|
| 46 |
+
logU = np.log(perplexity)
|
| 47 |
+
|
| 48 |
+
# Loop over all datapoints
|
| 49 |
+
for i in range(n):
|
| 50 |
+
if i % 100 == 0:
|
| 51 |
+
print("Computing P-values for point %d of %d..." % (i, n))
|
| 52 |
+
|
| 53 |
+
# Compute the Gaussian kernel and entropy for the current precision
|
| 54 |
+
betamin = -np.inf
|
| 55 |
+
betamax = np.inf
|
| 56 |
+
Di = D[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))]
|
| 57 |
+
(H, thisP) = Hbeta(Di, beta[i])
|
| 58 |
+
|
| 59 |
+
# Evaluate whether the perplexity is within tolerance
|
| 60 |
+
Hdiff = H - logU
|
| 61 |
+
tries = 0
|
| 62 |
+
while np.abs(Hdiff) > tol and tries < 50:
|
| 63 |
+
# If not, increase or decrease precision
|
| 64 |
+
if Hdiff > 0:
|
| 65 |
+
betamin = beta[i].copy()
|
| 66 |
+
if betamax == np.inf or betamax == -np.inf:
|
| 67 |
+
beta[i] = beta[i] * 2.
|
| 68 |
+
else:
|
| 69 |
+
beta[i] = (beta[i] + betamax) / 2.
|
| 70 |
+
else:
|
| 71 |
+
betamax = beta[i].copy()
|
| 72 |
+
if betamin == np.inf or betamin == -np.inf:
|
| 73 |
+
beta[i] = beta[i] / 2.
|
| 74 |
+
else:
|
| 75 |
+
beta[i] = (beta[i] + betamin) / 2.
|
| 76 |
+
|
| 77 |
+
# Recompute the values
|
| 78 |
+
(H, thisP) = Hbeta(Di, beta[i])
|
| 79 |
+
Hdiff = H - logU
|
| 80 |
+
tries += 1
|
| 81 |
+
|
| 82 |
+
# Set the final row of P
|
| 83 |
+
P[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))] = thisP
|
| 84 |
+
|
| 85 |
+
# Return final P-matrix
|
| 86 |
+
print("Mean value of sigma: %f" % np.mean(np.sqrt(1 / beta)))
|
| 87 |
+
return P
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def tsne(X=np.array([]), no_dims=2, initial_dims=50, perplexity=30.0):
|
| 91 |
+
"""
|
| 92 |
+
Runs t-SNE on the dataset in the NxD array X to reduce its
|
| 93 |
+
dimensionality to no_dims dimensions. The syntaxis of the function is
|
| 94 |
+
`Y = tsne.tsne(X, no_dims, perplexity), where X is an NxD NumPy array.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
if isinstance(no_dims, float):
|
| 98 |
+
print("Error: array X should have type float.")
|
| 99 |
+
return -1
|
| 100 |
+
if round(no_dims) != no_dims:
|
| 101 |
+
print("Error: number of dimensions should be an integer.")
|
| 102 |
+
return -1
|
| 103 |
+
|
| 104 |
+
X = pca(X, initial_dims).real
|
| 105 |
+
(n, d) = X.shape
|
| 106 |
+
max_iter = 1000
|
| 107 |
+
initial_momentum = 0.5
|
| 108 |
+
final_momentum = 0.8
|
| 109 |
+
eta = 500
|
| 110 |
+
min_gain = 0.01
|
| 111 |
+
Y = np.random.randn(n, no_dims)
|
| 112 |
+
dY = np.zeros((n, no_dims))
|
| 113 |
+
iY = np.zeros((n, no_dims))
|
| 114 |
+
gains = np.ones((n, no_dims))
|
| 115 |
+
|
| 116 |
+
# Compute P-values
|
| 117 |
+
P = x2p(X, 1e-5, perplexity)
|
| 118 |
+
P = P + np.transpose(P)
|
| 119 |
+
P = P / np.sum(P)
|
| 120 |
+
P = P * 4.
|
| 121 |
+
P = np.maximum(P, 1e-12)
|
| 122 |
+
|
| 123 |
+
for iter in range(max_iter):
|
| 124 |
+
# Compute pairwise affinities
|
| 125 |
+
sum_Y = np.sum(np.square(Y), 1)
|
| 126 |
+
num = -2. * np.dot(Y, Y.T)
|
| 127 |
+
num = 1. / (1. + np.add(np.add(num, sum_Y).T, sum_Y)) #
|
| 128 |
+
num[range(n), range(n)] = 0.
|
| 129 |
+
Q = num / np.sum(num)
|
| 130 |
+
Q = np.maximum(Q, 1e-12)
|
| 131 |
+
|
| 132 |
+
# Compute gradient
|
| 133 |
+
PQ = P - Q
|
| 134 |
+
for i in range(n):
|
| 135 |
+
dY[i, :] = np.sum(np.tile(PQ[:, i] * num[:, i], (no_dims, 1)).T * (Y[i, :] - Y), 0)
|
| 136 |
+
|
| 137 |
+
# Perform the update
|
| 138 |
+
if iter < 20:
|
| 139 |
+
momentum = initial_momentum
|
| 140 |
+
else:
|
| 141 |
+
momentum = final_momentum
|
| 142 |
+
gains = (gains + 0.2) * ((dY > 0.) != (iY > 0.)) + \
|
| 143 |
+
(gains * 0.8) * ((dY > 0.) == (iY > 0.))
|
| 144 |
+
gains[gains < min_gain] = min_gain
|
| 145 |
+
iY = momentum * iY - eta * (gains * dY)
|
| 146 |
+
Y = Y + iY
|
| 147 |
+
Y = Y - np.tile(np.mean(Y, 0), (n, 1))
|
| 148 |
+
|
| 149 |
+
# Compute current value of cost function
|
| 150 |
+
if (iter + 1) % 10 == 0:
|
| 151 |
+
C = np.sum(P * np.log(P / Q))
|
| 152 |
+
print("Iteration %d: error is %f" % (iter + 1, C))
|
| 153 |
+
if iter == 100:
|
| 154 |
+
P = P / 4.
|
| 155 |
+
|
| 156 |
+
return Y
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
import numpy as np
|
| 160 |
+
import matplotlib.pyplot as plt
|
| 161 |
+
import os
|
| 162 |
+
from glob import glob
|
| 163 |
+
from tqdm import tqdm
|
| 164 |
+
import sys
|
| 165 |
+
|
| 166 |
+
def Hbeta(D=np.array([]), beta=1.0):
|
| 167 |
+
"""
|
| 168 |
+
Compute the perplexity and the P-row for a specific value of the
|
| 169 |
+
precision of a Gaussian distribution.
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
D (numpy.ndarray): Distance array.
|
| 173 |
+
beta (float): Precision of the Gaussian distribution.
|
| 174 |
+
|
| 175 |
+
Returns:
|
| 176 |
+
tuple: A tuple containing perplexity (H) and the P-row (P).
|
| 177 |
+
"""
|
| 178 |
+
# Compute P-row and corresponding perplexity
|
| 179 |
+
P = np.exp(-D.copy() * beta)
|
| 180 |
+
sumP = np.sum(P)
|
| 181 |
+
H = np.log(sumP) + beta * np.sum(D * P) / sumP
|
| 182 |
+
P = P / sumP
|
| 183 |
+
return H, P
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def pca(X=np.array([]), no_dims=50):
|
| 187 |
+
"""
|
| 188 |
+
Performs PCA on the NxD array X to reduce its dimensionality to no_dims dimensions.
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
X (numpy.ndarray): Input data array.
|
| 192 |
+
no_dims (int): Number of dimensions to reduce to.
|
| 193 |
+
|
| 194 |
+
Returns:
|
| 195 |
+
numpy.ndarray: The reduced data array.
|
| 196 |
+
"""
|
| 197 |
+
(n, d) = X.shape
|
| 198 |
+
X = X - np.tile(np.mean(X, axis=0), (n, 1))
|
| 199 |
+
(l, M) = np.linalg.eig(np.dot(X.T, X))
|
| 200 |
+
Y = np.dot(X, M[:, 0:no_dims])
|
| 201 |
+
return Y
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def x2p(X=np.array([]), tol=1e-5, perplexity=30.0):
|
| 205 |
+
"""
|
| 206 |
+
Performs a binary search to get P-values such that each
|
| 207 |
+
conditional Gaussian has the same perplexity.
|
| 208 |
+
|
| 209 |
+
Args:
|
| 210 |
+
X (numpy.ndarray): Input data array.
|
| 211 |
+
tol (float): Tolerance for the perplexity.
|
| 212 |
+
perplexity (float): Desired perplexity.
|
| 213 |
+
|
| 214 |
+
Returns:
|
| 215 |
+
numpy.ndarray: The P-values matrix.
|
| 216 |
+
"""
|
| 217 |
+
(n, d) = X.shape
|
| 218 |
+
sum_X = np.sum(np.square(X), axis=1)
|
| 219 |
+
D = np.add(np.add(-2 * np.dot(X, X.T), sum_X).T, sum_X)
|
| 220 |
+
P = np.zeros((n, n))
|
| 221 |
+
beta = np.ones((n, 1))
|
| 222 |
+
logU = np.log(perplexity)
|
| 223 |
+
|
| 224 |
+
# Loop over all data points
|
| 225 |
+
for i in range(n):
|
| 226 |
+
if i % 100 == 0:
|
| 227 |
+
print(f"Computing P-values for point {i} of {n}...")
|
| 228 |
+
|
| 229 |
+
# Compute the Gaussian kernel and entropy for the current precision
|
| 230 |
+
betamin = -np.inf
|
| 231 |
+
betamax = np.inf
|
| 232 |
+
Di = D[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))]
|
| 233 |
+
(H, thisP) = Hbeta(Di, beta[i])
|
| 234 |
+
|
| 235 |
+
# Evaluate whether the perplexity is within tolerance
|
| 236 |
+
Hdiff = H - logU
|
| 237 |
+
tries = 0
|
| 238 |
+
while np.abs(Hdiff) > tol and tries < 50:
|
| 239 |
+
# If not, adjust precision
|
| 240 |
+
if Hdiff > 0:
|
| 241 |
+
betamin = beta[i].copy()
|
| 242 |
+
if betamax in [np.inf, -np.inf]:
|
| 243 |
+
beta[i] *= 2
|
| 244 |
+
else:
|
| 245 |
+
beta[i] = (beta[i] + betamax) / 2
|
| 246 |
+
else:
|
| 247 |
+
betamax = beta[i].copy()
|
| 248 |
+
if betamin in [np.inf, -np.inf]:
|
| 249 |
+
beta[i] /= 2
|
| 250 |
+
else:
|
| 251 |
+
beta[i] = (beta[i] + betamin) / 2
|
| 252 |
+
|
| 253 |
+
# Recompute the values
|
| 254 |
+
(H, thisP) = Hbeta(Di, beta[i])
|
| 255 |
+
Hdiff = H - logU
|
| 256 |
+
tries += 1
|
| 257 |
+
|
| 258 |
+
# Set the final row of P
|
| 259 |
+
P[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))] = thisP
|
| 260 |
+
|
| 261 |
+
print("Mean value of sigma: %f" % np.mean(np.sqrt(1 / beta)))
|
| 262 |
+
return P
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def tsne(X=np.array([]), no_dims=2, initial_dims=50, perplexity=30.0):
|
| 266 |
+
"""
|
| 267 |
+
Runs t-SNE on the dataset in the NxD array X to reduce its
|
| 268 |
+
dimensionality to no_dims dimensions.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
X (numpy.ndarray): Input data array.
|
| 272 |
+
no_dims (int): Number of dimensions to reduce to.
|
| 273 |
+
initial_dims (int): Number of initial dimensions.
|
| 274 |
+
perplexity (float): Desired perplexity.
|
| 275 |
+
|
| 276 |
+
Returns:
|
| 277 |
+
numpy.ndarray: The reduced data array.
|
| 278 |
+
"""
|
| 279 |
+
if isinstance(no_dims, float):
|
| 280 |
+
print("Error: array X should have type float.")
|
| 281 |
+
return -1
|
| 282 |
+
if round(no_dims) != no_dims:
|
| 283 |
+
print("Error: number of dimensions should be an integer.")
|
| 284 |
+
return -1
|
| 285 |
+
|
| 286 |
+
X = pca(X, initial_dims).real
|
| 287 |
+
(n, d) = X.shape
|
| 288 |
+
max_iter = 1000
|
| 289 |
+
initial_momentum = 0.5
|
| 290 |
+
final_momentum = 0.8
|
| 291 |
+
eta = 500
|
| 292 |
+
min_gain = 0.01
|
| 293 |
+
Y = np.random.randn(n, no_dims)
|
| 294 |
+
dY = np.zeros((n, no_dims))
|
| 295 |
+
iY = np.zeros((n, no_dims))
|
| 296 |
+
gains = np.ones((n, no_dims))
|
| 297 |
+
|
| 298 |
+
# Compute P-values
|
| 299 |
+
P = x2p(X, 1e-5, perplexity)
|
| 300 |
+
P = P + np.transpose(P) # Ensure symmetry
|
| 301 |
+
P = P / np.sum(P) # Normalize
|
| 302 |
+
P = P * 4. # Early exaggeration
|
| 303 |
+
P = np.maximum(P, 1e-12) # Avoid numerical issues
|
| 304 |
+
|
| 305 |
+
for iter in range(max_iter):
|
| 306 |
+
# Compute pairwise affinities
|
| 307 |
+
sum_Y = np.sum(np.square(Y), axis=1)
|
| 308 |
+
num = -2. * np.dot(Y, Y.T)
|
| 309 |
+
num = 1. / (1. + np.add(np.add(num, sum_Y).T, sum_Y))
|
| 310 |
+
num[np.arange(n), np.arange(n)] = 0. # Avoid self-affinity
|
| 311 |
+
Q = num / np.sum(num)
|
| 312 |
+
Q = np.maximum(Q, 1e-12) # Avoid numerical issues
|
| 313 |
+
|
| 314 |
+
# Compute gradient
|
| 315 |
+
PQ = P - Q
|
| 316 |
+
for i in range(n):
|
| 317 |
+
dY[i, :] = np.sum(np.tile(PQ[:, i] * num[:, i], (no_dims, 1)).T * (Y[i, :] - Y), axis=0)
|
| 318 |
+
|
| 319 |
+
# Perform the update
|
| 320 |
+
momentum = initial_momentum if iter < 20 else final_momentum
|
| 321 |
+
gains = (gains + 0.2) * ((dY > 0.) != (iY > 0.)) + (gains * 0.8) * ((dY > 0.) == (iY > 0.))
|
| 322 |
+
gains[gains < min_gain] = min_gain
|
| 323 |
+
iY = momentum * iY - eta * (gains * dY)
|
| 324 |
+
Y = Y + iY
|
| 325 |
+
Y -= np.tile(np.mean(Y, axis=0), (n, 1)) # Center the data
|
| 326 |
+
|
| 327 |
+
# Compute current value of cost function
|
| 328 |
+
if (iter + 1) % 10 == 0:
|
| 329 |
+
C = np.sum(P * np.log(P / Q))
|
| 330 |
+
print(f"Iteration {iter + 1}: error is {C:.6f}")
|
| 331 |
+
if iter == 100:
|
| 332 |
+
P /= 4. # Decrease early exaggeration
|
| 333 |
+
|
| 334 |
+
return Y
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
if __name__ == '__main__':
|
| 338 |
+
|
| 339 |
+
task = sys.argv[2]
|
| 340 |
+
if sys.argv[1] == "gnss":
|
| 341 |
+
task_class = {0: 3, 1: 5, 2: 7, 3: 9, 4: 11}
|
| 342 |
+
colors = {0: "#1f77b4", 1: "#ff7f0e", 2: "#2ca02c", 3: "#d62728",
|
| 343 |
+
4: "#9467bd", 5: "#8c564b", 6: "#e377c2", 7: "#7f7f7f",
|
| 344 |
+
8: "#bcbd22", 9: "#17becf", 10: "#000000"}
|
| 345 |
+
elif sys.argv[1] == "cifar":
|
| 346 |
+
task_class = {0: 4, 1: 6, 2: 8, 3: 10}
|
| 347 |
+
colors = {0: "#1f77b4", 1: "#ff7f0e", 2: "#2ca02c", 3: "#d62728",
|
| 348 |
+
4: "#9467bd", 5: "#8c564b", 6: "#e377c2", 7: "#7f7f7f",
|
| 349 |
+
8: "#bcbd22", 9: "#17becf"}
|
| 350 |
+
else:
|
| 351 |
+
raise Exception("Please provide the name of the dataset.")
|
| 352 |
+
|
| 353 |
+
# Load embeddings and ground truth of a task
|
| 354 |
+
emb_file = f"embeddings_{task}.npy"
|
| 355 |
+
ground_truth_file = f"predictions_{task}_tr_pr.npy"
|
| 356 |
+
points = np.load(emb_file)
|
| 357 |
+
ground_truth = np.load(ground_truth_file)
|
| 358 |
+
size = points.shape[1]
|
| 359 |
+
labels = ground_truth[:, 0]
|
| 360 |
+
|
| 361 |
+
# Check if t-SNE embeddings are already computed
|
| 362 |
+
tsne_file = f"tsne_embeddings/emb_tsne_{task}.npy"
|
| 363 |
+
if not os.path.isfile(tsne_file):
|
| 364 |
+
tsne_embs = tsne(points, 2, size, 30.0)
|
| 365 |
+
np.save(tsne_file, tsne_embs)
|
| 366 |
+
|
| 367 |
+
tsne_embs = np.load(tsne_file, allow_pickle=True)
|
| 368 |
+
x = tsne_embs
|
| 369 |
+
print('t-SNE embeddings shape:', x.shape)
|
| 370 |
+
y = labels
|
| 371 |
+
colors_list = [colors[cy] for cy in y]
|
| 372 |
+
|
| 373 |
+
# Plotting the t-SNE results
|
| 374 |
+
plt.figure(figsize=(5, 4))
|
| 375 |
+
for key, val in colors.items():
|
| 376 |
+
if key == task_class[int(task)]:
|
| 377 |
+
break
|
| 378 |
+
cur_x = x[y == key]
|
| 379 |
+
plt.scatter(cur_x[:, 0], cur_x[:, 1], s=8, color=val, label=f"Class: {key}")
|
| 380 |
+
|
| 381 |
+
# Add legend and save the plot
|
| 382 |
+
plt.legend(fontsize=10, loc="lower left", ncol=2, labelspacing=0.03, columnspacing=0.03,
|
| 383 |
+
handletextpad=0.03)
|
| 384 |
+
plt.tight_layout()
|
| 385 |
+
plt.xticks([], [])
|
| 386 |
+
plt.yticks([], [])
|
| 387 |
+
plt.savefig(f"tsne_plots/tsne_{task}.pdf", dpi=1200)
|
| 388 |
+
plt.close()
|