code
stringlengths
17
6.64M
class Coco(BaseDataset): def __init__(self, config, device): super().__init__(config, device) root_dir = Path(os.path.expanduser(config['data_path'])) self._paths = {} train_dir = Path(root_dir, 'train2014') self._paths['train'] = [str(p) for p in list(train_dir.iterdir())] val_dir = Path(root_dir, 'val2014') val_images = list(val_dir.iterdir()) self._paths['val'] = [str(p) for p in val_images[:config['sizes']['val']]] self._paths['test'] = [str(p) for p in val_images[(- config['sizes']['test']):]] def get_dataset(self, split): return _Dataset(self._paths[split], self._config, self._device)
class _Dataset(Dataset): def __init__(self, paths, config, device): self._paths = paths self._config = config self._angle_lim = (np.pi / 4) self._device = device def __getitem__(self, item): img0 = cv2.imread(self._paths[item]) img0 = cv2.cvtColor(img0, cv2.COLOR_BGR2RGB) if ('img_size' in self._config): img0 = resize_and_crop(img0, self._config['img_size']) img_size = img0.shape[:2] rot_invar = True self._config['warped_pair']['params']['rotation'] = False (H_no_rot, _) = sample_homography(img_size, **self._config['warped_pair']['params']) if (np.random.rand() < self._config['warped_pair']['no_rot_proba']): rot_invar = False else: self._config['warped_pair']['params']['rotation'] = True (H, rot_angle) = sample_homography(img_size, **self._config['warped_pair']['params']) rot_angle = np.clip((np.abs(rot_angle) / self._angle_lim), 0.0, 1.0) self._config['warped_pair']['params']['rotation'] = True H_inv = np.linalg.inv(H) img1 = cv2.warpPerspective(img0, H, (img_size[1], img_size[0]), flags=cv2.INTER_LINEAR) img2 = cv2.warpPerspective(img0, H_no_rot, (img_size[1], img_size[0]), flags=cv2.INTER_LINEAR) compute_sift = self._config.get('compute_sift', False) if compute_sift: (kp_lists, mask) = get_keypoints_and_mask([img0, img1, img2], H, H_no_rot, n_kp=self._config['n_kp']) config_aug = self._config['photometric_augmentation'] if config_aug['enable']: img0 = photometric_augmentation(img0, config_aug) img1 = photometric_augmentation(img1, config_aug) img2 = photometric_augmentation(img2, config_aug) img0 = (img0.astype(float) / 255.0) img1 = (img1.astype(float) / 255.0) img2 = (img2.astype(float) / 255.0) outputs = {'light_invariant': False} if compute_sift: outputs['valid_mask'] = torch.tensor(mask, dtype=torch.float, device=self._device) outputs['keypoints0'] = torch.tensor(kp_lists[0], dtype=torch.float, device=self._device) outputs['keypoints1'] = torch.tensor(kp_lists[1], dtype=torch.float, device=self._device) outputs['keypoints2'] = torch.tensor(kp_lists[2], dtype=torch.float, device=self._device) else: valid_mask2_0 = compute_valid_mask(np.linalg.inv(H_no_rot), img_size, self._config['warped_pair']['valid_border_margin']) valid_mask2_2 = compute_valid_mask(H_no_rot, img_size, self._config['warped_pair']['valid_border_margin']) valid_mask0 = compute_valid_mask(H_inv, img_size, self._config['warped_pair']['valid_border_margin']) valid_mask0 *= valid_mask2_0 outputs['valid_mask0'] = torch.tensor(valid_mask0, dtype=torch.float, device=self._device) valid_mask1 = compute_valid_mask(H, img_size, self._config['warped_pair']['valid_border_margin']) valid_mask1 *= valid_mask2_2 outputs['valid_mask1'] = torch.tensor(valid_mask1, dtype=torch.float, device=self._device) outputs['image0'] = torch.tensor(img0.transpose(2, 0, 1), dtype=torch.float, device=self._device) outputs['image1'] = torch.tensor(img1.transpose(2, 0, 1), dtype=torch.float, device=self._device) outputs['image2'] = torch.tensor(img2.transpose(2, 0, 1), dtype=torch.float, device=self._device) outputs['homography'] = torch.tensor(H, dtype=torch.float, device=self._device) outputs['H_no_rot'] = torch.tensor(H_no_rot, dtype=torch.float, device=self._device) outputs['rot_invariant'] = rot_invar outputs['rot_angle'] = torch.tensor([rot_angle], dtype=torch.float, device=self._device) return outputs def __len__(self): return len(self._paths)
class Flashes(BaseDataset): def __init__(self, config, device): super().__init__(config, device) root_dir = Path(os.path.expanduser(config['data_path'])) self._paths = {'train': [], 'val': [], 'test': []} train_dir = Path(root_dir, 'train') train_sequence_paths = [path for path in train_dir.iterdir()] for seq_path in train_sequence_paths: images_path = [str(x) for x in seq_path.iterdir() if (str(x.stem)[:3] == 'dir')] self._paths['train'] += [(images_path[i], images_path[(i + 1)]) for i in range((len(images_path) - 1))] val_dir = Path(root_dir, 'test') val_sequence_paths = [path for path in val_dir.iterdir()] test_sequence_paths = val_sequence_paths[(- config['sizes']['test']):] val_sequence_paths = val_sequence_paths[:config['sizes']['val']] for seq_path in val_sequence_paths: images_path = [str(x) for x in seq_path.iterdir() if (str(x.stem)[:3] == 'dir')] self._paths['val'] += [(images_path[i], images_path[(i + 1)]) for i in range((len(images_path) - 1))] for seq_path in test_sequence_paths: images_path = [str(x) for x in seq_path.iterdir() if (str(x.stem)[:3] == 'dir')] self._paths['test'] += [(images_path[i], images_path[(i + 1)]) for i in range((len(images_path) - 1))] def get_dataset(self, split): return _Dataset(self._paths[split], self._config, self._device)
class _Dataset(Dataset): def __init__(self, paths, config, device): self._paths = paths self._config = config self._angle_lim = (np.pi / 4) self._device = device def __getitem__(self, item): img0 = cv2.imread(self._paths[item][0]) img0 = cv2.cvtColor(img0, cv2.COLOR_BGR2RGB) img1 = cv2.imread(self._paths[item][1]) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) if ('img_size' in self._config): img0 = resize_and_crop(img0, self._config['img_size']) img1 = resize_and_crop(img1, self._config['img_size']) img_size = img0.shape[:2] rot_invar = True self._config['warped_pair']['params']['rotation'] = False (H_no_rot, _) = sample_homography(img_size, **self._config['warped_pair']['params']) if (np.random.rand() < self._config['warped_pair']['no_rot_proba']): rot_invar = False else: self._config['warped_pair']['params']['rotation'] = True (H, rot_angle) = sample_homography(img_size, **self._config['warped_pair']['params']) rot_angle = np.clip((np.abs(rot_angle) / self._angle_lim), 0.0, 1.0) self._config['warped_pair']['params']['rotation'] = True H_inv = np.linalg.inv(H) img1 = cv2.warpPerspective(img1, H, (img_size[1], img_size[0]), flags=cv2.INTER_LINEAR) img2 = cv2.warpPerspective(img0, H_no_rot, (img_size[1], img_size[0]), flags=cv2.INTER_LINEAR) compute_sift = self._config.get('compute_sift', False) if compute_sift: (kp_lists, mask) = get_keypoints_and_mask([img0, img1, img2], H, H_no_rot, n_kp=self._config['n_kp']) config_aug = self._config['photometric_augmentation'] if config_aug['enable']: img0 = photometric_augmentation(img0, config_aug) img2 = photometric_augmentation(img2, config_aug) light_aug = deepcopy(config_aug) light_aug['primitives'] += ['random_brightness', 'random_contrast', 'additive_shade'] img1 = photometric_augmentation(img1, light_aug) img0 = (img0.astype(float) / 255.0) img1 = (img1.astype(float) / 255.0) img2 = (img2.astype(float) / 255.0) outputs = {'light_invariant': True} if compute_sift: outputs['valid_mask'] = torch.tensor(mask, dtype=torch.float, device=self._device) outputs['keypoints0'] = torch.tensor(kp_lists[0], dtype=torch.float, device=self._device) outputs['keypoints1'] = torch.tensor(kp_lists[1], dtype=torch.float, device=self._device) outputs['keypoints2'] = torch.tensor(kp_lists[2], dtype=torch.float, device=self._device) else: valid_mask2_0 = compute_valid_mask(np.linalg.inv(H_no_rot), img_size, self._config['warped_pair']['valid_border_margin']) valid_mask2_2 = compute_valid_mask(H_no_rot, img_size, self._config['warped_pair']['valid_border_margin']) valid_mask0 = compute_valid_mask(H_inv, img_size, self._config['warped_pair']['valid_border_margin']) valid_mask0 *= valid_mask2_0 outputs['valid_mask0'] = torch.tensor(valid_mask0, dtype=torch.float, device=self._device) valid_mask1 = compute_valid_mask(H, img_size, self._config['warped_pair']['valid_border_margin']) valid_mask1 *= valid_mask2_2 outputs['valid_mask1'] = torch.tensor(valid_mask1, dtype=torch.float, device=self._device) outputs['image0'] = torch.tensor(img0.transpose(2, 0, 1), dtype=torch.float, device=self._device) outputs['image1'] = torch.tensor(img1.transpose(2, 0, 1), dtype=torch.float, device=self._device) outputs['image2'] = torch.tensor(img2.transpose(2, 0, 1), dtype=torch.float, device=self._device) outputs['homography'] = torch.tensor(H, dtype=torch.float, device=self._device) outputs['H_no_rot'] = torch.tensor(H_no_rot, dtype=torch.float, device=self._device) outputs['rot_invariant'] = rot_invar outputs['rot_angle'] = torch.tensor([rot_angle], dtype=torch.float, device=self._device) return outputs def __len__(self): return len(self._paths)
class MixedDataset(BaseDataset): def __init__(self, config, device): super().__init__(config, device) base_config = {'sizes': {'train': 30000, 'val': 500, 'test': 1000}} base_config.update(self._config) self._config = base_config.copy() self._datasets = [] for (i, d) in enumerate(config['datasets']): base_config['name'] = d base_config['data_path'] = config['data_paths'][i] base_config['photometric_augmentation']['enable'] = config['photo_aug'][i] self._datasets.append(get_dataset(d)(deepcopy(base_config), device)) self._weights = config['weights'] def get_dataset(self, split): return _Dataset(self._datasets, self._weights, split, self._config['sizes'][split])
class _Dataset(Dataset): def __init__(self, datasets, weights, split, size): self._datasets = [d.get_dataset(split) for d in datasets] self._weights = weights self._size = size def __getitem__(self, item): dataset = self._datasets[np.random.choice(range(len(self._datasets)), p=self._weights)] return dataset[np.random.randint(len(dataset))] def __len__(self): return self._size
class Vidit(BaseDataset): def __init__(self, config, device): super().__init__(config, device) self._root_dir = Path(os.path.expanduser(config['data_path'])) self._paths = {} np.random.seed(config['seed']) files = [str(path) for path in self._root_dir.iterdir()] files = np.sort(files).reshape(300, 40) self._paths['train'] = files[10:] self._paths['val'] = files[:10] self._paths['test'] = [] def get_dataset(self, split): return _Dataset(self._paths[split], self._config, self._device)
class _Dataset(Dataset): def __init__(self, paths, config, device): self._paths = paths self._config = config self._angle_lim = (np.pi / 4) self._device = device def __getitem__(self, item): scene_id = (item // 50) paths = np.random.choice(self._paths[scene_id], 2, replace=False) img0 = cv2.cvtColor(cv2.imread(paths[0]), cv2.COLOR_BGR2RGB) img1 = cv2.cvtColor(cv2.imread(paths[1]), cv2.COLOR_BGR2RGB) if ('img_size' in self._config): img0 = resize_and_crop(img0, self._config['img_size']) img1 = resize_and_crop(img1, self._config['img_size']) img_size = img0.shape[:2] rot_invar = True self._config['warped_pair']['params']['rotation'] = False (H_no_rot, _) = sample_homography(img_size, **self._config['warped_pair']['params']) if (np.random.rand() < self._config['warped_pair']['no_rot_proba']): rot_invar = False else: self._config['warped_pair']['params']['rotation'] = True (H, rot_angle) = sample_homography(img_size, **self._config['warped_pair']['params']) rot_angle = np.clip((np.abs(rot_angle) / self._angle_lim), 0.0, 1.0) self._config['warped_pair']['params']['rotation'] = True H_inv = np.linalg.inv(H) img1 = cv2.warpPerspective(img1, H, (img_size[1], img_size[0]), flags=cv2.INTER_LINEAR) img2 = cv2.warpPerspective(img0, H_no_rot, (img_size[1], img_size[0]), flags=cv2.INTER_LINEAR) compute_sift = self._config.get('compute_sift', False) if compute_sift: (kp_lists, mask) = get_keypoints_and_mask([img0, img1, img2], H, H_no_rot, n_kp=self._config['n_kp']) config_aug = self._config['photometric_augmentation'] if config_aug['enable']: img0 = photometric_augmentation(img0, config_aug) img2 = photometric_augmentation(img2, config_aug) light_aug = deepcopy(config_aug) light_aug['primitives'] += ['random_brightness', 'random_contrast', 'additive_shade'] img1 = photometric_augmentation(img1, light_aug) img0 = (img0.astype(float) / 255.0) img1 = (img1.astype(float) / 255.0) img2 = (img2.astype(float) / 255.0) outputs = {'light_invariant': True} if compute_sift: outputs['valid_mask'] = torch.tensor(mask, dtype=torch.float, device=self._device) outputs['keypoints0'] = torch.tensor(kp_lists[0], dtype=torch.float, device=self._device) outputs['keypoints1'] = torch.tensor(kp_lists[1], dtype=torch.float, device=self._device) outputs['keypoints2'] = torch.tensor(kp_lists[2], dtype=torch.float, device=self._device) else: valid_mask2_0 = compute_valid_mask(np.linalg.inv(H_no_rot), img_size, self._config['warped_pair']['valid_border_margin']) valid_mask2_2 = compute_valid_mask(H_no_rot, img_size, self._config['warped_pair']['valid_border_margin']) valid_mask0 = compute_valid_mask(H_inv, img_size, self._config['warped_pair']['valid_border_margin']) valid_mask0 *= valid_mask2_0 outputs['valid_mask0'] = torch.tensor(valid_mask0, dtype=torch.float, device=self._device) valid_mask1 = compute_valid_mask(H, img_size, self._config['warped_pair']['valid_border_margin']) valid_mask1 *= valid_mask2_2 outputs['valid_mask1'] = torch.tensor(valid_mask1, dtype=torch.float, device=self._device) outputs['image0'] = torch.tensor(img0.transpose(2, 0, 1), dtype=torch.float, device=self._device) outputs['image1'] = torch.tensor(img1.transpose(2, 0, 1), dtype=torch.float, device=self._device) outputs['image2'] = torch.tensor(img2.transpose(2, 0, 1), dtype=torch.float, device=self._device) outputs['homography'] = torch.tensor(H, dtype=torch.float, device=self._device) outputs['H_no_rot'] = torch.tensor(H_no_rot, dtype=torch.float, device=self._device) outputs['rot_invariant'] = rot_invar outputs['rot_angle'] = torch.tensor([rot_angle], dtype=torch.float, device=self._device) return outputs def __len__(self): return (len(self._paths) * 50)
def _train(config, exper_dir, args): with open(os.path.join(exper_dir, 'config.yaml'), 'w') as f: yaml.dump(config, f, default_flow_style=False) checkpoint_dir = os.path.join(exper_dir, 'checkpoints') if (not os.path.exists(checkpoint_dir)): os.makedirs(checkpoint_dir) runs_dir = os.path.join(exper_dir, 'runs') if (not os.path.exists(runs_dir)): os.makedirs(runs_dir) resume_training = args.resume_training_from if ((resume_training != '') and (not os.path.exists(resume_training))): sys.exit((resume_training + ' not found.')) device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) dataset = get_dataset(config['data']['name'])(config['data'], device) net = get_model(config['model']['name'])(dataset, config['model'], device) n_iter = config.get('n_iter', np.inf) n_epoch = config.get('n_epoch', np.inf) assert (not (np.isinf(n_iter) and np.isinf(n_epoch))) try: net.train(n_iter, n_epoch, exper_dir, validation_interval=config.get('validation_interval', 100), save_interval=config.get('save_interval', 500), resume_training=resume_training, device=device) except KeyboardInterrupt: logging.info('Got Keyboard Interrupt, saving model and closing.') net.save(exper_dir)
def _test(config, exper_dir, args): checkpoint_path = args.checkpoint if (not os.path.exists(checkpoint_path)): sys.exit((checkpoint_path + ' not found.')) device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) dataset = get_dataset(config['data']['name'])(config['data'], device) net = get_model(config['model']['name'])(dataset, config['model'], device) net.test(exper_dir, checkpoint_path, device)
def _export(config, exper_dir, args): checkpoint_path = args.checkpoint if (not os.path.exists(checkpoint_path)): sys.exit((checkpoint_path + ' not found.')) (exper_path, experiment_name) = os.path.split(exper_dir.rstrip('/')) export_name = (args.export_name if args.export_name else experiment_name) output_dir = os.path.join(exper_path, 'outputs', export_name) if (not os.path.exists(output_dir)): os.makedirs(output_dir) device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) dataset = get_dataset(config['data']['name'])(config['data'], device) net = get_model(config['model']['name'])(dataset, config['model'], device) net.export(exper_dir, checkpoint_path, output_dir, device)
def get_model(name): mod = __import__('lisrd.models.{}'.format(name), fromlist=['']) return getattr(mod, _module_to_class(name))
def _module_to_class(name): return ''.join((n.capitalize() for n in name.split('_')))
class NetVLAD(nn.Module): '\n NetVLAD layer implementation\n Credits: https://github.com/lyakaap/NetVLAD-pytorch\n ' def __init__(self, num_clusters=64, dim=128, alpha=100.0, normalize_input=True): '\n Args:\n num_clusters: number of clusters.\n dim: dimension of descriptors.\n alpha: parameter of initialization. Larger is harder assignment.\n normalize_input: if true, descriptor-wise L2 normalization\n is applied to input.\n ' super().__init__() self.num_clusters = num_clusters self.dim = dim self.alpha = alpha self.normalize_input = normalize_input self.conv = nn.Conv2d(dim, num_clusters, kernel_size=(1, 1), bias=True) self.centroids = nn.Parameter(torch.rand(num_clusters, dim)) self._init_params() def _init_params(self): self.conv.weight = nn.Parameter(((2.0 * self.alpha) * self.centroids).unsqueeze((- 1)).unsqueeze((- 1))) self.conv.bias = nn.Parameter(((- self.alpha) * self.centroids.norm(dim=1))) def forward(self, x): (N, C) = x.shape[:2] if self.normalize_input: x = func.normalize(x, p=2, dim=1) soft_assign = self.conv(x).view(N, self.num_clusters, (- 1)) soft_assign = func.softmax(soft_assign, dim=1) x_flatten = x.view(N, C, (- 1)) residual = (x_flatten.expand(self.num_clusters, (- 1), (- 1), (- 1)).permute(1, 0, 2, 3) - self.centroids.expand(x_flatten.size((- 1)), (- 1), (- 1)).permute(1, 2, 0).unsqueeze(0)) residual *= soft_assign.unsqueeze(2) vlad = residual.sum(dim=(- 1)) vlad = func.normalize(vlad, p=2, dim=2) vlad = vlad.view(x.size(0), (- 1)) vlad = func.normalize(vlad, p=2, dim=1) return vlad
class VGGLikeModule(torch.nn.Module): def __init__(self): super().__init__() self._relu = torch.nn.ReLU(inplace=True) self._pool = torch.nn.AvgPool2d(kernel_size=2, stride=2) self._conv1_1 = torch.nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1) self._bn1_1 = torch.nn.BatchNorm2d(64) self._conv1_2 = torch.nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self._bn1_2 = torch.nn.BatchNorm2d(64) self._conv2_1 = torch.nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self._bn2_1 = torch.nn.BatchNorm2d(64) self._conv2_2 = torch.nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self._bn2_2 = torch.nn.BatchNorm2d(64) self._conv3_1 = torch.nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1) self._bn3_1 = torch.nn.BatchNorm2d(128) self._conv3_2 = torch.nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1) self._bn3_2 = torch.nn.BatchNorm2d(128) self._conv4_1 = torch.nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1) self._bn4_1 = torch.nn.BatchNorm2d(256) self._conv4_2 = torch.nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1) self._bn4_2 = torch.nn.BatchNorm2d(256) def forward(self, inputs): x = self._bn1_1(self._relu(self._conv1_1(inputs))) x = self._bn1_2(self._relu(self._conv1_2(x))) x = self._pool(x) x = self._bn2_1(self._relu(self._conv2_1(x))) x = self._bn2_2(self._relu(self._conv2_2(x))) x = self._pool(x) x = self._bn3_1(self._relu(self._conv3_1(x))) x = self._bn3_2(self._relu(self._conv3_2(x))) x = self._pool(x) x = self._bn4_1(self._relu(self._conv4_1(x))) x = self._bn4_2(self._relu(self._conv4_2(x))) return x
class Mode(): TRAIN = 'train' VAL = 'validation' TEST = 'test' EXPORT = 'export'
class BaseModel(metaclass=ABCMeta): 'Base model class.\n\n Arguments:\n dataset: A BaseDataset object.\n config: A dictionary containing the configuration parameters.\n The Entry `learning_rate` is required.\n\n Models should inherit from this class and implement the following methods:\n `_model`, `_loss`, `_metrics` and `initialize_weights`.\n\n Additionally, the static attribute required_config_keys is a list\n containing the required config entries.\n ' required_baseconfig = ['learning_rate'] @abstractmethod def _model(self, config): ' Implements the model.\n\n Arguments:\n config: A configuration dictionary.\n\n Returns:\n A torch.nn.Module that implements the model.\n ' raise NotImplementedError @abstractmethod def _forward(self, inputs, mode, config): ' Calls the model on some input.\n This method is called three times: for training, testing and\n prediction (see the `mode` argument) and can return different tensors\n depending on the mode. It only supports NCHW format for now.\n\n Arguments:\n inputs: A dictionary of input features, where the keys are their\n names (e.g. `"image"`) and the values of type `torch.Tensor`.\n mode: An attribute of the `Mode` class, either `Mode.TRAIN`,\n `Mode.TEST` or `Mode.PRED`.\n config: A configuration dictionary.\n\n Returns:\n A dictionary of outputs, where the keys are their names\n (e.g. `"logits"`) and the values are the corresponding Tensor.\n ' raise NotImplementedError @abstractmethod def _loss(self, outputs, inputs, config): ' Implements the training loss.\n This method is called on the outputs of the `_model` method\n in training mode.\n\n Arguments:\n outputs: A dictionary, as returned by `_model` called with\n `mode=Mode.TRAIN`.\n inputs: A dictionary of input features (same as for `_model`).\n config: A configuration dictionary.\n\n Returns:\n A Tensor corresponding to the loss to minimize during training.\n ' raise NotImplementedError @abstractmethod def _metrics(self, outputs, inputs, config): ' Implements the evaluation metrics.\n This method is called on the outputs of the `_model` method\n in test mode.\n\n Arguments:\n outputs: A dictionary, as returned by `_model` called with\n `mode=Mode.EVAL`.\n inputs: A dictionary of input features (same as for `_model`).\n config: A configuration dictionary.\n\n Returns:\n A dictionary of metrics, where the keys are their names\n (e.g. "`accuracy`") and the values are the corresponding Tensor.\n ' raise NotImplementedError @abstractmethod def initialize_weights(self): ' Initialize all the weights in the network. ' return NotImplementedError def __init__(self, dataset, config, device): self._dataset = dataset self._config = config required = (self.required_baseconfig + getattr(self, 'required_config_keys', [])) for r in required: assert (r in self._config), "Required configuration entry: '{}'".format(r) self._net = self._model(config) if (torch.cuda.device_count() > 1): logging.info('Using {} GPU(s).'.format(torch.cuda.device_count())) self._net = torch.nn.DataParallel(self._net) self._net = self._net.to(device) self._solver = optim.Adam(self._net.parameters(), lr=self._config['learning_rate']) self._it = 0 self._epoch = 0 def _to_dict(self, d, device): ' Send all the values of a dict of Tensor to a specific device. ' return {k: (v.to(device) if isinstance(v, torch.Tensor) else v) for (k, v) in d.items()} def train(self, n_iter, n_epoch, exper_dir, validation_interval=100, save_interval=500, resume_training='', device='cpu'): " Train the model.\n\n Arguments:\n n_iter: max number of iterations.\n n_epoch: max number of epochs.\n exper_dir: folder containing the outputs of the training.\n validation_interval: evaluate the model every\n 'validation_interval' iter.\n save_interval: save the model every 'save_interval' iter.\n resume_training: path to the checkpoint file when training is\n resumed from a previous training.\n device: device on which to perform the operations.\n " self.initialize_weights() if (resume_training == ''): logging.info('Initializing new weights.') self._it = 0 self._epoch = 0 else: logging.info(('Loading weights from ' + resume_training)) self.load(resume_training) self._net.train() runs_dir = os.path.join(exper_dir, 'runs') self._writer = SummaryWriter(runs_dir) train_data_loader = self._dataset.get_data_loader('train') val_data_loader = self._dataset.get_data_loader('val') train_loss = [] logging.info('Start training') while (self._epoch < n_epoch): for x in train_data_loader: if (self._it > n_iter): break inputs = self._to_dict(x, device) outputs = self._forward(inputs, Mode.TRAIN, self._config) loss = self._loss(outputs, inputs, self._config) train_loss.append(loss.item()) self._solver.zero_grad() loss.backward() self._solver.step() if ((self._it % validation_interval) == 0): validation_loss = [] metrics = {} for x in val_data_loader: inputs = self._to_dict(x, device) outputs = self._forward(inputs, Mode.VAL, self._config) loss = self._loss(outputs, inputs, self._config) validation_loss.append(loss.item()) metric = self._metrics(outputs, inputs, self._config) metrics = {k: ([metric[k].item()] if (k not in metrics) else (metrics[k] + [metric[k].item()])) for k in metric} total_train_loss = np.mean(train_loss) total_validation_loss = np.mean(validation_loss) total_metrics = {k: np.mean(v) for (k, v) in metrics.items()} logging.info(('Iter {:4d}: train loss {:.4f}, validation loss {:.4f}'.format(self._it, total_train_loss, total_validation_loss) + ''.join([', {} {:.4f}'.format(m, total_metrics[m]) for m in total_metrics]))) self._writer.add_scalar('train_loss', total_train_loss, self._it) self._writer.add_scalar('validation_loss', total_validation_loss, self._it) for m in total_metrics: self._writer.add_scalar(m, total_metrics[m], self._it) if ((self._it % save_interval) == 0): self.save(exper_dir) self._it += 1 self._epoch += 1 if (self._it > n_iter): break self._writer.close() logging.info('Training finished.') def test(self, exper_dir, checkpoint_path, device='cpu'): ' Test the model on a test dataset.\n\n Arguments:\n exper_dir: folder containing the outputs of the training.\n checkpoint_path: path to the checkpoint.\n device: device on which to perform the operations.\n ' logging.info(('Loading weights from ' + checkpoint_path)) self.load(checkpoint_path, Mode.TEST) self._net.eval() test_data_loader = self._dataset.get_data_loader('test') logging.info('Start evaluation.') metrics = {} for x in tqdm(test_data_loader): inputs = self._to_dict(x, device) outputs = self._forward(inputs, Mode.TEST, self._config) metric = self._metrics(outputs, inputs, self._config) metrics = {k: ([metric[k].item()] if (k not in metrics) else (metrics[k] + [metric[k].item()])) for k in metric} total_metrics = {k: np.mean(v) for (k, v) in metrics.items()} logging.info(('Test metrics: ' + ''.join(['{} {:.4f};'.format(m, total_metrics[m]) for m in total_metrics]))) def export(self, exper_dir, checkpoint_path, output_dir, device='cpu'): ' Export the descriptors on a given dataset.\n\n Arguments:\n exper_dir: folder containing the outputs of the training.\n checkpoint_path: path to the checkpoint.\n output_dir: for each item in the dataset, write a .npz file\n in output_dir with the exported descriptors.\n device: device on which to perform the operations.\n ' logging.info(('Loading weights from ' + checkpoint_path)) self.load(checkpoint_path, Mode.TEST) self._net.eval() test_data_loader = self._dataset.get_data_loader('test') logging.info('Start exporting.') i = 0 for x in tqdm(test_data_loader): inputs = self._to_dict(x, device) outputs = self._forward(inputs, Mode.EXPORT, self._config) outputs.update(inputs) for (k, v) in outputs.items(): outputs[k] = v.detach().cpu().numpy()[0] if (len(outputs[k].shape) == 3): outputs[k] = outputs[k].transpose(1, 2, 0) out_file = os.path.join(output_dir, (str(i) + '.npz')) np.savez_compressed(out_file, **outputs) i += 1 logging.info(('Descriptors exported in ' + output_dir)) def _adapt_weight_names(self, state_dict): ' Adapt the weight names when the training and testing are done\n with a different GPU configuration (with/without DataParallel). ' train_parallel = (list(state_dict.keys())[0][:7] == 'module.') test_parallel = (torch.cuda.device_count() > 1) new_state_dict = {} if (train_parallel and (not test_parallel)): for (k, v) in state_dict.items(): new_state_dict[k[7:]] = v elif (test_parallel and (not train_parallel)): for (k, v) in state_dict.items(): new_k = ('module.' + k) new_state_dict[new_k] = v else: new_state_dict = state_dict return new_state_dict def _match_state_dict(self, old_state_dict, new_state_dict): ' Return a new state dict that has exactly the same entries\n as old_state_dict and that is updated with the values of\n new_state_dict whose entries are shared with old_state_dict.\n This allows loading a pre-trained network. ' return ({k: (new_state_dict[k] if (k in new_state_dict) else v) for (k, v) in old_state_dict.items()}, (old_state_dict.keys() == new_state_dict.keys())) def save(self, exper_dir): ' Save the current training in a .pth file. ' save_file = os.path.join(exper_dir, (('checkpoints/checkpoint_' + str(self._it)) + '.pth')) torch.save({'iter': self._it, 'model_state_dict': self._net.state_dict(), 'optimizer_state_dict': self._solver.state_dict()}, save_file) def load(self, checkpoint_path, mode=Mode.TRAIN): ' Load a model stored on disk. ' checkpoint = torch.load(checkpoint_path, map_location='cpu') (updated_state_dict, same_net) = self._match_state_dict(self._net.state_dict(), self._adapt_weight_names(checkpoint['model_state_dict'])) self._net.load_state_dict(updated_state_dict) if same_net: self._solver.load_state_dict(checkpoint['optimizer_state_dict']) self._it = checkpoint['iter'] if (mode == Mode.TRAIN): self._epoch = ((self._it * self._dataset._config['batch_size']) // len(self._dataset))
class LisrdModule(nn.Module): def __init__(self, config, device): super().__init__() self._config = config self.relu = torch.nn.ReLU(inplace=True) self._backbone = VGGLikeModule() self._variances = ['rot_var_illum_var', 'rot_invar_illum_var', 'rot_var_illum_invar', 'rot_invar_illum_invar'] self._desc_size = self._config['desc_size'] self.conv_illum_var_rot_var_1 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1) self.bn_illum_var_rot_var_1 = nn.BatchNorm2d(256) self.conv_illum_var_rot_var_2 = nn.Conv2d(256, self._desc_size, kernel_size=1, stride=1, padding=0) self.conv_illum_var_rot_invar_1 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1) self.bn_illum_var_rot_invar_1 = nn.BatchNorm2d(256) self.conv_illum_var_rot_invar_2 = nn.Conv2d(256, self._desc_size, kernel_size=1, stride=1, padding=0) self.conv_illum_invar_rot_var_1 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1) self.bn_illum_invar_rot_var_1 = nn.BatchNorm2d(256) self.conv_illum_invar_rot_var_2 = nn.Conv2d(256, self._desc_size, kernel_size=1, stride=1, padding=0) self.conv_illum_invar_rot_invar_1 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1) self.bn_illum_invar_rot_invar_1 = nn.BatchNorm2d(256) self.conv_illum_invar_rot_invar_2 = nn.Conv2d(256, self._desc_size, kernel_size=1, stride=1, padding=0) if config['compute_meta_desc']: self.vlad_rot_var_illum_var = NetVLAD(num_clusters=self._config['n_clusters'], dim=self._config['meta_desc_dim']).to(device) self.vlad_rot_invar_illum_var = NetVLAD(num_clusters=self._config['n_clusters'], dim=self._config['meta_desc_dim']).to(device) self.vlad_rot_var_illum_invar = NetVLAD(num_clusters=self._config['n_clusters'], dim=self._config['meta_desc_dim']).to(device) self.vlad_rot_invar_illum_invar = NetVLAD(num_clusters=self._config['n_clusters'], dim=self._config['meta_desc_dim']).to(device) self.vlad_layers = {'rot_var_illum_var': self.vlad_rot_var_illum_var, 'rot_invar_illum_var': self.vlad_rot_invar_illum_var, 'rot_var_illum_invar': self.vlad_rot_var_illum_invar, 'rot_invar_illum_invar': self.vlad_rot_invar_illum_invar} def forward(self, inputs, mode): if self._config['freeze_local_desc']: with torch.no_grad(): features = self._backbone(inputs) outputs = self._multi_descriptors(features, mode) else: features = self._backbone(inputs) outputs = self._multi_descriptors(features, mode) if self._config['compute_meta_desc']: self._compute_meta_descriptors(outputs) return outputs def _multi_descriptors(self, features, mode): '\n Compute multiple descriptors from pre-extracted features\n with different variances / invariances.\n ' illum_var_rot_var_head = self.relu(self.conv_illum_var_rot_var_1(features)) illum_var_rot_var_head = self.bn_illum_var_rot_var_1(illum_var_rot_var_head) illum_var_rot_var_head = self.conv_illum_var_rot_var_2(illum_var_rot_var_head) illum_var_rot_invar_head = self.relu(self.conv_illum_var_rot_invar_1(features)) illum_var_rot_invar_head = self.bn_illum_var_rot_invar_1(illum_var_rot_invar_head) illum_var_rot_invar_head = self.conv_illum_var_rot_invar_2(illum_var_rot_invar_head) illum_invar_rot_var_head = self.relu(self.conv_illum_invar_rot_var_1(features)) illum_invar_rot_var_head = self.bn_illum_invar_rot_var_1(illum_invar_rot_var_head) illum_invar_rot_var_head = self.conv_illum_invar_rot_var_2(illum_invar_rot_var_head) illum_invar_rot_invar_head = self.relu(self.conv_illum_invar_rot_invar_1(features)) illum_invar_rot_invar_head = self.bn_illum_invar_rot_invar_1(illum_invar_rot_invar_head) illum_invar_rot_invar_head = self.conv_illum_invar_rot_invar_2(illum_invar_rot_invar_head) outputs = {'raw_rot_var_illum_var': illum_var_rot_var_head, 'raw_rot_invar_illum_var': illum_var_rot_invar_head, 'raw_rot_var_illum_invar': illum_invar_rot_var_head, 'raw_rot_invar_illum_invar': illum_invar_rot_invar_head} return outputs def _compute_meta_descriptor(self, raw_desc, netvlad): tile = self._config['tile'] meta_desc = raw_desc.clone() (b, c, h, w) = meta_desc.size() if (((h % tile) != 0) or ((w % tile) != 0)): (h, w) = ((tile * (h // tile)), (tile * (w // tile))) meta_desc = func.interpolate(meta_desc, size=(h, w), mode='bilinear', align_corners=False) (sub_h, sub_w) = ((h // tile), (w // tile)) meta_desc = meta_desc.reshape(b, c, tile, sub_h, tile, sub_w) meta_desc = meta_desc.permute(0, 2, 4, 1, 3, 5) meta_desc = meta_desc.reshape(((b * tile) * tile), c, sub_h, sub_w) meta_desc = netvlad(meta_desc).reshape(b, tile, tile, (self._config['meta_desc_dim'] * self._config['n_clusters'])).permute(0, 3, 1, 2) return meta_desc def _compute_meta_descriptors(self, outputs): '\n For each kind of descriptor, compute a meta descriptor encoding\n a sub area of the total image.\n ' for v in self._variances: outputs[(v + '_meta_desc')] = self._compute_meta_descriptor(outputs[('raw_' + v)], self.vlad_layers[v])
class Lisrd(BaseModel): required_config_keys = [] def __init__(self, dataset, config, device): self._device = device super().__init__(dataset, config, device) self._variances = ['rot_var_illum_var', 'rot_invar_illum_var', 'rot_var_illum_invar', 'rot_invar_illum_invar'] self._compute_meta_desc = config['compute_meta_desc'] self._desc_weights = {'rot_var_illum_var': 1.0, 'rot_invar_illum_var': 0.5, 'rot_var_illum_invar': 0.5, 'rot_invar_illum_invar': 0.25} def _model(self, config): return LisrdModule(config, self._device) def _forward(self, inputs, mode, config): outputs = {} if (mode == Mode.EXPORT): outputs['descriptors'] = {} if self._compute_meta_desc: outputs['meta_descriptors'] = {} with torch.no_grad(): desc = self._net.forward(inputs['image0'], mode) for v in self._variances: outputs['descriptors'][v] = desc[('raw_' + v)] if self._compute_meta_desc: outputs['meta_descriptors'][v] = desc[(v + '_meta_desc')] else: desc0 = self._net.forward(inputs['image0'], mode) for v in self._variances: outputs[(('raw_' + v) + '0')] = desc0[('raw_' + v)] if self._compute_meta_desc: outputs[(v + '_meta_desc0')] = desc0[(v + '_meta_desc')] if ('image1' in inputs): desc1 = self._net.forward(inputs['image1'], mode) for v in self._variances: outputs[(('raw_' + v) + '1')] = desc1[('raw_' + v)] if self._compute_meta_desc: outputs[(v + '_meta_desc1')] = desc1[(v + '_meta_desc')] if ('image2' in inputs): desc2 = self._net.forward(inputs['image2'], mode) for v in self._variances: outputs[(('raw_' + v) + '2')] = desc2[('raw_' + v)] if self._compute_meta_desc: outputs[(v + '_meta_desc2')] = desc2[(v + '_meta_desc')] return outputs def _loss(self, outputs, inputs, config): b_size = inputs['image0'].size()[0] one = torch.ones(1, dtype=torch.float, device=self._device) if (not config['freeze_local_desc']): local_desc_losses = [] invar_descs = ['raw_rot_invar_illum_invar'] var_descs = [] for i in range(b_size): if (not inputs['rot_invariant'][i]): invar_descs.append('raw_rot_var_illum_invar') else: var_descs.append(('raw_rot_var_illum_invar', inputs['rot_angle'][i])) if (not inputs['light_invariant'][i]): invar_descs.append('raw_rot_invar_illum_var') else: var_descs.append(('raw_rot_invar_illum_var', one)) if ((not inputs['rot_invariant'][i]) and (not inputs['light_invariant'][i])): invar_descs.append('raw_rot_var_illum_var') else: var_descs.append(('raw_rot_var_illum_var', one)) for desc in invar_descs: sub_input = {k: v[i:(i + 1)] for (k, v) in inputs.items()} local_desc_losses.append(invar_desc_triplet_loss(outputs[(desc + '0')][i:(i + 1)], outputs[(desc + '1')][i:(i + 1)], sub_input, config, self._device)) for (desc, gap) in var_descs: sub_input = {k: v[i:(i + 1)] for (k, v) in inputs.items()} local_desc_losses.append(var_desc_triplet_loss(outputs[(desc + '0')][i:(i + 1)], outputs[(desc + '1')][i:(i + 1)], outputs[(desc + '2')][i:(i + 1)], gap, sub_input, config, self._device)) local_desc_loss = torch.stack(local_desc_losses, dim=0).mean() else: local_desc_loss = torch.tensor(0, dtype=torch.float, device=self._device) if self._compute_meta_desc: meta_desc_losses = [] for i in range(b_size): sub_input = {k: v[i:(i + 1)] for (k, v) in inputs.items()} sub_output = {k: v[i:(i + 1)] for (k, v) in outputs.items()} meta_desc_losses.append(meta_desc_triplet_loss(sub_output, sub_input, self._variances, config, self._device)) meta_desc_loss = torch.stack(meta_desc_losses, dim=0).mean() else: meta_desc_loss = torch.tensor(0, dtype=torch.float, device=self._device) self._writer.add_scalar('local_desc_loss', local_desc_loss, self._it) self._writer.add_scalar('meta_desc_loss', (config['lambda'] * meta_desc_loss), self._it) loss = (local_desc_loss + (config['lambda'] * meta_desc_loss)) return loss def _metrics(self, outputs, inputs, config): b_size = inputs['image0'].size()[0] m_scores = [] if self._compute_meta_desc: for i in range(b_size): sub_input = {k: v[i:(i + 1)] for (k, v) in inputs.items()} sub_output = {k: v[i:(i + 1)] for (k, v) in outputs.items()} (descs, meta_descs) = ([], []) for v in self._variances: descs.append([sub_output[(('raw_' + v) + '0')], sub_output[(('raw_' + v) + '1')]]) meta_descs.append([sub_output[(v + '_meta_desc0')], sub_output[(v + '_meta_desc1')]]) m_scores.append(matching_score(sub_input, descs, meta_descs, device=self._device)) m_score = torch.stack(m_scores, dim=0).mean() else: normalization = 0.0 for i in range(b_size): optim_desc = ['raw_rot_invar_illum_invar'] if (not inputs['rot_invariant'][i]): optim_desc.append('raw_rot_var_illum_invar') if (not inputs['light_invariant'][i]): optim_desc.append('raw_rot_invar_illum_var') if (not inputs['rot_invariant'][i]): optim_desc.append('raw_rot_var_illum_var') for desc in optim_desc: sub_input = {k: v[i:(i + 1)] for (k, v) in inputs.items()} normalization += self._desc_weights[desc[4:]] m_scores.append((self._desc_weights[desc[4:]] * matching_score(sub_input, [[outputs[(desc + '0')][i:(i + 1)], outputs[(desc + '1')][i:(i + 1)]]], device=self._device))) m_score = (torch.sum(torch.tensor(m_scores)) / normalization) return {'matching_score': m_score} def initialize_weights(self): def init_weights(m): if (type(m) == nn.Conv2d): torch.nn.init.kaiming_normal_(m.weight, nonlinearity='relu') m.bias.data.fill_(0.01) self._net.apply(init_weights)
def matching_score(inputs, descs, meta_descs=None, device='cuda:0'): (b_size, _, Hc, Wc) = descs[0][0].size() img_size = ((Hc * 8), (Wc * 8)) valid_mask = inputs['valid_mask'] n_points = valid_mask.size()[1] n_correct_points = torch.sum(valid_mask.int()).item() if (n_correct_points == 0): return torch.tensor(0.0, dtype=torch.float, device=device) if (torch.__version__ >= '1.2'): valid_mask = valid_mask.bool().flatten() else: valid_mask = valid_mask.byte().flatten() keypoints0 = inputs['keypoints0'] keypoints1 = inputs['keypoints1'] keypoints0 = keypoints0.reshape((b_size * n_points), 2)[valid_mask] keypoints1 = keypoints1.reshape((b_size * n_points), 2)[valid_mask] grid0 = keypoints_to_grid(keypoints0, img_size) grid1 = keypoints_to_grid(keypoints1, img_size) if meta_descs: (descs_n, meta_descs_n) = ([], []) for i in range(len(descs)): desc0 = func.grid_sample(descs[i][0], grid0).permute(0, 2, 3, 1).reshape(n_correct_points, (- 1)) desc0 = func.normalize(desc0, dim=1) desc1 = func.grid_sample(descs[i][1], grid1).permute(0, 2, 3, 1).reshape(n_correct_points, (- 1)) desc1 = func.normalize(desc1, dim=1) descs_n.append([desc0, desc1]) meta_desc0 = func.grid_sample(meta_descs[i][0], grid0).permute(0, 2, 3, 1).reshape(n_correct_points, (- 1)) meta_desc0 = func.normalize(meta_desc0, dim=1) meta_desc1 = func.grid_sample(meta_descs[i][1], grid1).permute(0, 2, 3, 1).reshape(n_correct_points, (- 1)) meta_desc1 = func.normalize(meta_desc1, dim=1) meta_descs_n.append([meta_desc0, meta_desc1]) desc_dist = get_lisrd_desc_dist(descs_n, meta_descs_n) else: desc0 = func.grid_sample(descs[0][0], grid0).permute(0, 2, 3, 1).reshape(n_correct_points, (- 1)) desc0 = func.normalize(desc0, dim=1) desc1 = func.grid_sample(descs[0][1], grid1).permute(0, 2, 3, 1).reshape(n_correct_points, (- 1)) desc1 = func.normalize(desc1, dim=1) desc_dist = (2 - (2 * (desc0 @ desc1.t()))) matches0 = torch.min(desc_dist, dim=1)[1] matches1 = torch.min(desc_dist, dim=0)[1] matching_score = (matches1[matches0] == torch.arange(len(matches0)).to(device)) return matching_score.float().mean()
def keypoints_to_grid(keypoints, img_size): '\n Convert a tensor [N, 2] or batched tensor [B, N, 2] of N keypoints into\n a grid in [-1, 1]² that can be used in torch.nn.functional.interpolate.\n ' n_points = keypoints.size()[(- 2)] device = keypoints.device grid_points = (((keypoints.float() * 2.0) / torch.tensor(img_size, dtype=torch.float, device=device)) - 1.0) grid_points = grid_points[(..., [1, 0])].view((- 1), n_points, 1, 2) return grid_points
def flush(): 'Try to flush all stdio buffers, both from python and from C.' try: sys.stdout.flush() sys.stderr.flush() except (AttributeError, ValueError, IOError): pass
@contextmanager def capture_outputs(filename): 'Duplicate stdout and stderr to a file on the file descriptor level.' with open(filename, 'a+') as target: original_stdout_fd = 1 original_stderr_fd = 2 target_fd = target.fileno() saved_stdout_fd = os.dup(original_stdout_fd) saved_stderr_fd = os.dup(original_stderr_fd) tee_stdout = subprocess.Popen(['tee', '-a', '/dev/stderr'], start_new_session=True, stdin=subprocess.PIPE, stderr=target_fd, stdout=1) tee_stderr = subprocess.Popen(['tee', '-a', '/dev/stderr'], start_new_session=True, stdin=subprocess.PIPE, stderr=target_fd, stdout=2) flush() os.dup2(tee_stdout.stdin.fileno(), original_stdout_fd) os.dup2(tee_stderr.stdin.fileno(), original_stderr_fd) try: (yield) finally: flush() tee_stdout.stdin.close() tee_stderr.stdin.close() os.dup2(saved_stdout_fd, original_stdout_fd) os.dup2(saved_stderr_fd, original_stderr_fd) def kill_tees(): tee_stdout.kill() tee_stderr.kill() tee_timer = Timer(1, kill_tees) try: tee_timer.start() tee_stdout.wait() tee_stderr.wait() finally: tee_timer.cancel() os.close(saved_stdout_fd) os.close(saved_stderr_fd)
def plot_mma(config, captions, mma_i, mma_v): models = config['models_name'] n_models = len(models) colors = np.array(brewer2mpl.get_map('Set2', 'qualitative', 8).mpl_colors)[:n_models] linestyles = (['-'] * n_models) plt_lim = [1, config['max_mma_threshold']] plt_rng = np.arange(plt_lim[0], (plt_lim[1] + 1)) plt.rc('axes', titlesize=25) plt.rc('axes', labelsize=25) plt.figure(figsize=(15, 5)) plt.subplot(1, 3, 1) n_i = 285 n_v = 295 for (model, caption, color, ls) in zip(models, captions, colors, linestyles): (i_err, v_err) = (mma_i[model], mma_v[model]) plt.plot(plt_rng, (((n_i * i_err) + (n_v * v_err)) / (n_i + n_v)), color=color, ls=ls, linewidth=3, label=caption) plt.title('Overall') plt.xlabel('Threshold [px]') plt.xlim(plt_lim) plt.xticks(plt_rng) plt.ylabel('Precision') plt.ylim([0.3, 1]) plt.grid() plt.tick_params(axis='both', which='major', labelsize=20) plt.subplot(1, 3, 2) for (model, caption, color, ls) in zip(models, captions, colors, linestyles): plt.plot(plt_rng, mma_i[model], color=color, ls=ls, linewidth=3, label=caption) plt.title('Illumination') plt.xlabel('Threshold [px]') plt.xlim(plt_lim) plt.xticks(plt_rng) plt.ylim([0.3, 1]) plt.gca().axes.set_yticklabels([]) plt.grid() plt.tick_params(axis='both', which='major', labelsize=20) plt.subplot(1, 3, 3) for (model, caption, color, ls) in zip(models, captions, colors, linestyles): plt.plot(plt_rng, mma_v[model], color=color, ls=ls, linewidth=3, label=caption) plt.title('Viewpoint') plt.xlabel('Threshold [px]') plt.xlim(plt_lim) plt.xticks(plt_rng) plt.ylim([0.3, 1]) plt.gca().axes.set_yticklabels([]) plt.grid() plt.tick_params(axis='both', which='major', labelsize=20) plt.legend(bbox_to_anchor=(1.04, 0.5), loc='center left', borderaxespad=0, fontsize=20)
def plot_mma(config, captions, mma_day, mma_night): models = config['models_name'] n_models = len(models) colors = np.array(brewer2mpl.get_map('Set2', 'qualitative', 8).mpl_colors)[:n_models] linestyles = (['-'] * n_models) plt_lim = [1, config['max_mma_threshold']] plt_rng = np.arange(plt_lim[0], (plt_lim[1] + 1)) plt.rc('axes', titlesize=25) plt.rc('axes', labelsize=25) plt.figure(figsize=(15, 5)) plt.subplot(1, 2, 1) for (model, caption, color, ls) in zip(models, captions, colors, linestyles): plt.plot(plt_rng, mma_day[model], color=color, ls=ls, linewidth=3, label=caption) plt.title('Day reference') plt.xlabel('Threshold [px]') plt.xlim(plt_lim) plt.xticks(plt_rng) plt.ylabel('Precision') plt.ylim([0, 0.7]) plt.grid() plt.tick_params(axis='both', which='major', labelsize=20) plt.subplot(1, 2, 2) for (model, caption, color, ls) in zip(models, captions, colors, linestyles): plt.plot(plt_rng, mma_night[model], color=color, ls=ls, linewidth=3, label=caption) plt.title('Night reference') plt.xlabel('Threshold [px]') plt.xlim(plt_lim) plt.xticks(plt_rng) plt.ylim([0, 0.7]) plt.gca().axes.set_yticklabels([]) plt.grid() plt.tick_params(axis='both', which='major', labelsize=20) plt.legend(bbox_to_anchor=(1.04, 0.5), loc='center left', borderaxespad=0, fontsize=20)
def get_dataloaders(dataset='mnist', batch_size=128, augmentation_on=False, cuda=False, num_workers=0): kwargs = ({'num_workers': num_workers, 'pin_memory': True} if cuda else {}) if (dataset == 'mnist'): if augmentation_on: transform_train = transforms.Compose([transforms.RandomCrop(28, padding=2), transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) else: transform_train = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) mnist_train = datasets.MNIST('../data', train=True, download=True, transform=transform_train) mnist_valid = datasets.MNIST('../data', train=True, download=True, transform=transform_test) mnist_test = datasets.MNIST('../data', train=False, transform=transform_test) TOTAL_NUM = 60000 NUM_VALID = int(round((TOTAL_NUM * 0.1))) NUM_TRAIN = int(round((TOTAL_NUM - NUM_VALID))) train_loader = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, sampler=ChunkSampler(NUM_TRAIN, 0, shuffle=True), **kwargs) valid_loader = torch.utils.data.DataLoader(mnist_valid, batch_size=batch_size, sampler=ChunkSampler(NUM_VALID, NUM_TRAIN, shuffle=True), **kwargs) test_loader = torch.utils.data.DataLoader(mnist_test, batch_size=1000, shuffle=False, **kwargs) elif (dataset == 'cifar10'): if augmentation_on: transform_train = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))]) transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))]) else: transform_train = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) cifar10_train = torchvision.datasets.CIFAR10(root='../data', train=True, download=True, transform=transform_train) cifar10_valid = torchvision.datasets.CIFAR10(root='../data', train=True, download=True, transform=transform_test) cifar10_test = torchvision.datasets.CIFAR10(root='../data', train=False, download=True, transform=transform_test) TOTAL_NUM = 50000 NUM_VALID = int(round((TOTAL_NUM * 0.02))) NUM_TRAIN = int(round((TOTAL_NUM - NUM_VALID))) train_loader = torch.utils.data.DataLoader(cifar10_train, batch_size=batch_size, sampler=ChunkSampler(NUM_TRAIN, 0, shuffle=True), **kwargs) valid_loader = torch.utils.data.DataLoader(cifar10_valid, batch_size=batch_size, sampler=ChunkSampler(NUM_VALID, NUM_TRAIN, shuffle=True), **kwargs) test_loader = torch.utils.data.DataLoader(cifar10_test, batch_size=1000, shuffle=False, **kwargs) else: raise NotImplementedError('Specified data set is not available.') return (train_loader, valid_loader, test_loader, NUM_TRAIN, NUM_VALID)
def get_dataset_details(dataset): if (dataset == 'mnist'): (input_nc, input_width, input_height) = (1, 28, 28) classes = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) elif (dataset == 'cifar10'): (input_nc, input_width, input_height) = (3, 32, 32) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') else: raise NotImplementedError('Specified data set is not available.') return (input_nc, input_width, input_height, classes)
class Tree(nn.Module): ' Adaptive Neural Tree module. ' def __init__(self, tree_struct, tree_modules, split=False, node_split=None, child_left=None, child_right=None, extend=False, node_extend=None, child_extension=None, cuda_on=True, breadth_first=True, soft_decision=True): ' Initialise the class.\n\n Args:\n tree_struct (list): List of dictionaries each of which contains\n meta information about each node of the tree.\n tree_modules (list): List of dictionaries, each of which contains\n modules (nn.Module) of each node in the tree and takes the form\n module = {\'transform\': transformer_module (nn.Module),\n \'classifier\': solver_module (nn.Module),\n \'router\': router_module (nn.Module) }\n split (bool): Set True if the model is testing \'split\' growth option\n node_split (int): Index of the node that is being split\n child_left (dict): Left child of the node node_split and takes the\n form of {\'transform\': transformer_module (nn.Module),\n \'classifier\': solver_module (nn.Module),\n \'router\': router_module (nn.Module) }\n child_right (dict): Right child of the node node_split and takes the\n form of {\'transform\': transformer_module (nn.Module),\n \'classifier\': solver_module (nn.Module),\n \'router\': router_module (nn.Module) }\n extend (bool): Set True if the model is testing \'extend\'\n growth option\n node_extend (int): Index of the node that is being extended\n child_extension (dict): The extra node used to extend node\n node_extend.\n cuda_on (bool): Set True to train on a GPU.\n breadth_first (bool): Set True to perform bread-first forward pass.\n If set to False, depth-first forward pass is performed.\n soft_decision (bool): Set True to perform multi-path inference,\n which computes the predictive distribution as the mean\n of the conditional distributions from all the leaf nodes,\n weighted by the corresponding reaching probabilities.\n If set to False, inference based on "hard" decisions is\n performed. If the routers are defined with\n stochastic=True, then the stochastic single-path inference\n is used. Otherwise, the greedy single-path inference is carried\n out whereby the input sample traverses the tree in the\n directions of the highest confidence of routers.\n ' super(Tree, self).__init__() assert (not (split and extend)) self.soft_decision = soft_decision self.cuda_on = cuda_on self.split = split self.extend = extend self.tree_struct = tree_struct self.node_split = node_split self.node_extend = node_extend self.breadth_first = breadth_first self.leaves_list = get_leaf_nodes(tree_struct) self.paths_list = [get_path_to_root(i, tree_struct) for i in self.leaves_list] self.tree_modules = nn.ModuleList() for (i, node) in enumerate(tree_modules): node_modules = nn.Sequential() node_modules.add_module('transform', node['transform']) node_modules.add_module('classifier', node['classifier']) node_modules.add_module('router', node['router']) self.tree_modules.append(node_modules) if split: self.child_left = nn.Sequential() self.child_left.add_module('transform', child_left['transform']) self.child_left.add_module('classifier', child_left['classifier']) self.child_left.add_module('router', child_left['router']) self.child_right = nn.Sequential() self.child_right.add_module('transform', child_right['transform']) self.child_right.add_module('classifier', child_right['classifier']) self.child_right.add_module('router', child_right['router']) if extend: self.child_extension = nn.Sequential() self.child_extension.add_module('transform', child_extension['transform']) self.child_extension.add_module('classifier', child_extension['classifier']) self.child_extension.add_module('router', child_extension['router']) def forward(self, input): 'Choose breadth-first/depth-first inference' if self.breadth_first: return self.forward_breadth_first(input) else: return self.forward_depth_first(input) def forward_depth_first(self, input): ' Depth first forward pass.\n Args:\n input: A tensor of size (batch, channels, width, height)\n Return:\n log soft-max probabilities (tensor) of size (batch, classes)\n If self.training = True, it also returns the probability of reaching\n the last node.\n ' y_pred = 0.0 prob_last = None for (nodes, edges) in self.paths_list: if (self.split and (nodes[(- 1)] == self.node_split)): (y_tmp, prob_last) = self.node_pred_split(input, nodes, edges) y_pred += y_tmp elif (self.extend and (nodes[(- 1)] == self.node_extend)): (y_tmp, prob_last) = self.node_pred_extend(input, nodes, edges) y_pred += y_tmp else: y_pred += self.node_pred(input, nodes, edges) if self.training: return (torch.log((1e-10 + y_pred)), prob_last) else: return torch.log((1e-10 + y_pred)) def forward_breadth_first(self, input): ' Breadth first forward pass.\n\n Notes:\n In the current implementation, tree_struct is constructed level\n by level. So, sequentially iterating tree_struct naturally leads\n to breadth first inference.\n ' t_list = [self.tree_modules[0].transform(input)] r_list = [1.0] s_list = [] prob_last = 1.0 for node in self.tree_struct: inp = t_list.pop(0) ro = r_list.pop(0) if (self.split and (node['index'] == self.node_split)): s_list.append(self.child_left.classifier(self.child_left.transform(inp))) s_list.append(self.child_right.classifier(self.child_right.transform(inp))) p_left = self.tree_modules[node['index']].router(inp) p_left = torch.unsqueeze(p_left, 1) prob_last = p_left r_list.append((ro * p_left)) r_list.append((ro * (1.0 - p_left))) elif (self.extend and (node['index'] == self.node_extend)): s_list.append(self.child_extension.classifier(self.child_extension.transform(inp))) p_left = 1.0 r_list.append((ro * p_left)) elif node['is_leaf']: s_list.append(self.tree_modules[node['index']].classifier(inp)) r_list.append(ro) elif node['extended']: t_list.append(self.tree_modules[node['left_child']].transform(inp)) p_left = self.tree_modules[node['index']].router(inp) r_list.append((ro * p_left)) else: t_list.append(self.tree_modules[node['left_child']].transform(inp)) t_list.append(self.tree_modules[node['right_child']].transform(inp)) p_left = self.tree_modules[node['index']].router(inp) p_left = torch.unsqueeze(p_left, 1) r_list.append((ro * p_left)) r_list.append((ro * (1.0 - p_left))) y_pred = 0.0 for (r, s) in zip(r_list, s_list): y_pred += (r * torch.exp(s)) out = torch.log((1e-10 + y_pred)) if self.training: return (out, prob_last) else: return out def node_pred(self, input, nodes, edges): ' Perform prediction on a given node given its path on the tree.\n e.g.\n nodes = [0, 1, 4, 10]\n edges = [True, False, False]\n ' prob = 1.0 for (node, state) in zip(nodes[:(- 1)], edges): input = self.tree_modules[node].transform(input) if state: prob = (prob * self.tree_modules[node].router(input)) else: prob = (prob * (1.0 - self.tree_modules[node].router(input))) if (not isinstance(prob, float)): prob = torch.unsqueeze(prob, 1) node_final = nodes[(- 1)] input = self.tree_modules[node_final].transform(input) y_pred = (prob * torch.exp(self.tree_modules[node_final].classifier(input))) return y_pred def node_pred_split(self, input, nodes, edges): ' Perform prediction on a split node given its path on the tree.\n Here, the last node in the list "nodes" is assumed to be split.\n e.g.\n nodes = [0, 1, 4, 10]\n edges = [True, False, False]\n then, node 10 is assumed to be split.\n\n Args:\n input (torch.Variable): input images\n nodes (list): list of all nodes (index) on the path between root\n and given node\n edges (list): list of left-child-status (boolean) of each edge\n between nodes in the list \'nodes\'\n Returns:\n y_pred (torch.Variable): predicted label\n prob_last (torch.Variable): output of the parent router\n (if self.training=True)\n ' prob = 1.0 for (node, state) in zip(nodes[:(- 1)], edges): input = self.tree_modules[node].transform(input) if state: prob = (prob * self.tree_modules[node].router(input)) else: prob = (prob * (1.0 - self.tree_modules[node].router(input))) if (not isinstance(prob, float)): prob = torch.unsqueeze(prob, 1) node_final = nodes[(- 1)] input = self.tree_modules[node_final].transform(input) prob_last = torch.unsqueeze(self.tree_modules[node_final].router(input), 1) y_pred = (prob * ((prob_last * torch.exp(self.child_left.classifier(self.child_left.transform(input)))) + ((1.0 - prob_last) * torch.exp(self.child_right.classifier(self.child_right.transform(input)))))) return (y_pred, prob_last) def node_pred_extend(self, input, nodes, edges): ' Perform prediction on an extended node given its path on the tree.\n Here, the last node in the list "nodes" is assumed to be split.\n e.g.\n nodes = [0, 1, 4, 10]\n edges = [True, False, False]\n then, node 10 is assumed to be split.\n\n Args:\n input (torch.Variable): input images\n nodes (list): list of all nodes (index) on the path between root and given node\n edges (list): list of left-child-status (boolean) of each edge between nodes in\n the list \'nodes\'\n Return:\n y_pred (torch.Variable): predicted label\n prob_last (torch.Variable): output of the parent router (if self.training=True)\n ' prob = 1.0 for (node, state) in zip(nodes[:(- 1)], edges): input = self.tree_modules[node].transform(input) if state: prob = (prob * self.tree_modules[node].router(input)) else: prob = (prob * (1.0 - self.tree_modules[node].router(input))) if (not isinstance(prob, float)): prob = torch.unsqueeze(prob, 1) prob_last = 1.0 node_final = nodes[(- 1)] input = self.tree_modules[node_final].transform(input) y_pred = (prob * torch.exp(self.child_extension.classifier(self.child_extension.transform(input)))) return (y_pred, prob_last) def compute_routing_probabilities(self, input): ' Compute routing probabilities for all nodes in the tree.\n\n Return:\n routing probabilities tensor (tensor) : torch tensor (N, num_nodes)\n ' for (i, (nodes, edges)) in enumerate(self.paths_list): prob = 1.0 for (node, state) in zip(nodes[:(- 1)], edges): input = self.tree_modules[node].transform(input) if state: prob = (prob * self.tree_modules[node].router(input)) else: prob = (prob * (1.0 - self.tree_modules[node].router(input))) if (not isinstance(prob, float)): prob = torch.unsqueeze(prob, 1) if (self.split and (nodes[(- 1)] == self.node_split)): node_final = nodes[(- 1)] input = self.tree_modules[node_final].transform(input) prob_last = torch.unsqueeze(self.tree_modules[node_final].router(input), 1) prob = torch.cat(((prob_last * prob), ((1.0 - prob_last) * prob)), dim=1) if (i == 0): prob_tensor = prob else: prob_tensor = torch.cat((prob_tensor, prob), dim=1) return prob_tensor def compute_routing_probability_specificnode(self, input, node_idx): ' Compute the probability of reaching a selected node.\n If a batch is provided, then the sum of probabilities is computed.\n ' (nodes, edges) = get_path_to_root(node_idx, self.tree_struct) prob = 1.0 for (node, edge) in zip(nodes[:(- 1)], edges): input = self.tree_modules[node].transform(input) if edge: prob = (prob * self.tree_modules[node].router(input)) else: prob = (prob * (1.0 - self.tree_modules[node].router(input))) if (not isinstance(prob, float)): prob = torch.unsqueeze(prob, 1) prob_sum = prob.sum(dim=0) return prob_sum.data[0] else: return (prob * input.size(0)) def compute_routing_probabilities_uptonode(self, input, node_idx): ' Compute the routing probabilities up to a node.\n\n Return:\n routing probabilities tensor (tensor) : torch tensor (N, nodes)\n\n ' leaves_up_to_node = get_past_leaf_nodes(self.tree_struct, node_idx) paths_list_up_to_node = [get_path_to_root(i, self.tree_struct) for i in leaves_up_to_node] for (i, (nodes, edges)) in enumerate(paths_list_up_to_node): dtype = (torch.cuda.FloatTensor if self.cuda_on else torch.FloatTensor) prob = Variable(torch.ones(input.size(0)).type(dtype)) output = input.clone() for (node, state) in zip(nodes[:(- 1)], edges): output = self.tree_modules[node].transform(output) if state: prob = (prob * self.tree_modules[node].router(output)) else: prob = (prob * (1.0 - self.tree_modules[node].router(output))) if (not isinstance(prob, float)): prob = torch.unsqueeze(prob, 1) if (self.split and (nodes[(- 1)] == self.node_split)): node_final = nodes[(- 1)] output = self.tree_modules[node_final].transform(output) prob_last = torch.unsqueeze(self.tree_modules[node_final].router(output), 1) prob = torch.cat(((prob_last * prob), ((1.0 - prob_last) * prob)), dim=1) if (i == 0): prob_tensor = prob else: prob_tensor = torch.cat((prob_tensor, prob), dim=1) return (prob_tensor, leaves_up_to_node) def update_tree_modules(self): '\n Return tree_modules (list) with the current parameters.\n ' tree_modules_new = [] for node_module in self.tree_modules: node = {'transform': node_module.transform, 'classifier': node_module.classifier, 'router': node_module.router} tree_modules_new.append(node) return tree_modules_new def update_children(self): assert (self.split or self.extend) if self.split: child_left = {'transform': self.child_left.transform, 'classifier': self.child_left.classifier, 'router': self.child_left.router} child_right = {'transform': self.child_right.transform, 'classifier': self.child_right.classifier, 'router': self.child_right.router} print('returning left and right children') return (child_left, child_right) elif self.extend: child_extension = {'transform': self.child_extension.transform, 'classifier': self.child_extension.classifier, 'router': self.child_extension.router} print('returning an extended child') return child_extension
class Identity(nn.Module): def __init__(self, input_nc, input_width, input_height, **kwargs): super(Identity, self).__init__() self.outputshape = (1, input_nc, input_width, input_height) def forward(self, x): return x
class JustConv(nn.Module): ' 1 convolution ' def __init__(self, input_nc, input_width, input_height, ngf=6, kernel_size=5, stride=1, **kwargs): super(JustConv, self).__init__() if (max(input_width, input_height) < kernel_size): warnings.warn('Router kernel too large, shrink it') kernel_size = max(input_width, input_height) self.conv1 = nn.Conv2d(input_nc, ngf, kernel_size, stride=stride) self.outputshape = self.get_outputshape(input_nc, input_width, input_height) def get_outputshape(self, input_nc, input_width, input_height): ' Run a single forward pass through the transformer to get the \n output size\n ' dtype = torch.FloatTensor x = Variable(torch.randn(1, input_nc, input_width, input_height).type(dtype), requires_grad=False) return self.forward(x).size() def forward(self, x): out = F.relu(self.conv1(x)) return out
class ConvPool(nn.Module): ' 1 convolution + 1 max pooling ' def __init__(self, input_nc, input_width, input_height, ngf=6, kernel_size=5, downsample=True, **kwargs): super(ConvPool, self).__init__() self.downsample = downsample if (max(input_width, input_height) < kernel_size): warnings.warn('Router kernel too large, shrink it') kernel_size = max(input_width, input_height) self.downsample = False self.conv1 = nn.Conv2d(input_nc, ngf, kernel_size) self.outputshape = self.get_outputshape(input_nc, input_width, input_height) def get_outputshape(self, input_nc, input_width, input_height): ' Run a single forward pass through the transformer to get the \n output size\n ' dtype = torch.FloatTensor x = Variable(torch.randn(1, input_nc, input_width, input_height).type(dtype), requires_grad=False) return self.forward(x).size() def forward(self, x): out = F.relu(self.conv1(x)) if self.downsample: return F.max_pool2d(out, 2) else: return out
class ResidualTransformer(nn.Module): ' Bottleneck without batch-norm\n Got the base codes from\n https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\n ' def __init__(self, input_nc, input_width, input_height, ngf=6, stride=1, **kwargs): super(ResidualTransformer, self).__init__() self.conv1 = nn.Conv2d(input_nc, ngf, kernel_size=1, bias=False) self.conv2 = nn.Conv2d(ngf, ngf, kernel_size=3, stride=stride, padding=1, bias=False) self.conv3 = nn.Conv2d(ngf, input_nc, kernel_size=1, bias=False) self.relu = nn.ReLU(inplace=True) self.stride = stride self.outputshape = self.get_outputshape(input_nc, input_width, input_height) def get_outputshape(self, input_nc, input_width, input_height): ' Run a single forward pass through the transformer to get the \n output size\n ' dtype = torch.FloatTensor x = Variable(torch.randn(1, input_nc, input_width, input_height).type(dtype), requires_grad=False) return self.forward(x).data.numpy().shape def forward(self, x): residual = x out = self.conv1(x) out = self.relu(out) out = self.conv2(out) out = self.relu(out) out = self.conv3(out) out += residual out = self.relu(out) return out
class VGG13ConvPool(nn.Module): ' n convolution + 1 max pooling ' def __init__(self, input_nc, input_width, input_height, ngf=64, kernel_size=3, batch_norm=True, downsample=True, **kwargs): super(VGG13ConvPool, self).__init__() self.downsample = downsample self.batch_norm = batch_norm self.conv1 = nn.Conv2d(input_nc, ngf, kernel_size=kernel_size, padding=((kernel_size - 1) / 2)) self.conv2 = nn.Conv2d(ngf, ngf, kernel_size=kernel_size, padding=1) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2) if batch_norm: self.bn1 = nn.BatchNorm2d(ngf) self.bn2 = nn.BatchNorm2d(ngf) self.outputshape = self.get_outputshape(input_nc, input_width, input_height) def get_outputshape(self, input_nc, input_width, input_height): ' Run a single forward pass through the transformer to get the \n output size\n ' dtype = torch.FloatTensor x = Variable(torch.randn(1, input_nc, input_width, input_height).type(dtype), requires_grad=False) return self.forward(x).size() def forward(self, x): if self.batch_norm: out = self.relu(self.bn1(self.conv1(x))) out = self.relu(self.bn2(self.conv2(out))) else: out = self.relu(self.conv1(x)) out = self.relu(self.conv2(out)) if self.downsample: return F.max_pool2d(out, 2) else: return out
class One(nn.Module): 'Route all data points to the left branch branch ' def __init__(self): super(One, self).__init__() def forward(self, x): return 1.0
class Router(nn.Module): 'Convolution + Relu + Global Average Pooling + Sigmoid' def __init__(self, input_nc, input_width, input_height, kernel_size=28, soft_decision=True, stochastic=False, **kwargs): super(Router, self).__init__() self.soft_decision = soft_decision self.stochastic = stochastic if (max(input_width, input_height) < kernel_size): warnings.warn('Router kernel too large, shrink it') kernel_size = max(input_width, input_height) self.conv1 = nn.Conv2d(input_nc, 1, kernel_size=kernel_size) self.sigmoid = nn.Sigmoid() def forward(self, x): x = self.conv1(x) x = x.mean(dim=(- 1)).mean(dim=(- 1)).squeeze() x = self.output_controller(x) return x def output_controller(self, x): if self.soft_decision: return self.sigmoid(x) if self.stochastic: x = self.sigmoid(x) return ops.ST_StochasticIndicator()(x) else: x = self.sigmoid(x) return ops.ST_Indicator()(x)
class RouterGAP(nn.Module): ' Convolution + Relu + Global Average Pooling + FC + Sigmoid ' def __init__(self, input_nc, input_width, input_height, ngf=5, kernel_size=7, soft_decision=True, stochastic=False, **kwargs): super(RouterGAP, self).__init__() self.ngf = ngf self.soft_decision = soft_decision self.stochastic = stochastic if (max(input_width, input_height) < kernel_size): warnings.warn('Router kernel too large, shrink it') kernel_size = max(input_width, input_height) self.conv1 = nn.Conv2d(input_nc, ngf, kernel_size=kernel_size) self.linear1 = nn.Linear(ngf, 1) self.sigmoid = nn.Sigmoid() def forward(self, x): x = self.conv1(x) if (self.ngf == 1): x = x.mean(dim=(- 1)).mean(dim=(- 1)).squeeze() else: x = F.relu(x) x = x.mean(dim=(- 1)).mean(dim=(- 1)).squeeze() x = self.linear1(x).squeeze() output = self.sigmoid(x) if self.soft_decision: return output if self.stochastic: return ops.ST_StochasticIndicator()(output) else: return ops.ST_Indicator()(output)
class RouterGAPwithDoubleConv(nn.Module): ' 2 x (Convolution + Relu) + Global Average Pooling + FC + Sigmoid ' def __init__(self, input_nc, input_width, input_height, ngf=32, kernel_size=3, soft_decision=True, stochastic=False, **kwargs): super(RouterGAPwithDoubleConv, self).__init__() self.ngf = ngf self.soft_decision = soft_decision self.stochastic = stochastic if (max(input_width, input_height) < kernel_size): warnings.warn('Router kernel too large, shrink it') kernel_size = max(input_width, input_height) if ((max(input_width, input_height) % 2) == 0): kernel_size += 1 padding = ((kernel_size - 1) / 2) self.conv1 = nn.Conv2d(input_nc, ngf, kernel_size=kernel_size, padding=padding) self.conv2 = nn.Conv2d(ngf, ngf, kernel_size=kernel_size, padding=padding) self.relu = nn.ReLU(inplace=True) self.linear1 = nn.Linear(ngf, 1) self.sigmoid = nn.Sigmoid() def forward(self, x): out = self.relu(self.conv1(x)) out = self.relu(self.conv2(out)) out = out.mean(dim=(- 1)).mean(dim=(- 1)).squeeze() out = self.linear1(out).squeeze() out = self.output_controller(out) return out def output_controller(self, x): if self.soft_decision: return self.sigmoid(x) if self.stochastic: x = self.sigmoid(x) return ops.ST_StochasticIndicator()(x) else: x = self.sigmoid(x) return ops.ST_Indicator()(x)
class Router_MLP_h1(nn.Module): ' MLP with 1 hidden layer ' def __init__(self, input_nc, input_width, input_height, kernel_size=28, soft_decision=True, stochastic=False, reduction_rate=2, **kwargs): super(Router_MLP_h1, self).__init__() self.soft_decision = soft_decision self.stochastic = stochastic width = ((input_nc * input_width) * input_height) self.fc1 = nn.Linear(width, ((width / reduction_rate) + 1)) self.sigmoid = nn.Sigmoid() def forward(self, x): x = x.view(x.size(0), (- 1)) x = F.relu(self.fc1(x)).squeeze() x = self.output_controller(x) return x def output_controller(self, x): if self.soft_decision: return self.sigmoid(x) if self.stochastic: x = self.sigmoid(x) return ops.ST_StochasticIndicator()(x) else: x = self.sigmoid(x) return ops.ST_Indicator()(x)
class RouterGAP_TwoFClayers(nn.Module): ' Routing function:\n GAP + fc1 + fc2 \n ' def __init__(self, input_nc, input_width, input_height, kernel_size=28, soft_decision=True, stochastic=False, reduction_rate=2, dropout_prob=0.0, **kwargs): super(RouterGAP_TwoFClayers, self).__init__() self.soft_decision = soft_decision self.stochastic = stochastic self.dropout_prob = dropout_prob self.fc1 = nn.Linear(input_nc, ((input_nc / reduction_rate) + 1)) self.fc2 = nn.Linear(((input_nc / reduction_rate) + 1), 1) self.sigmoid = nn.Sigmoid() def forward(self, x): x = x.mean(dim=(- 1)).mean(dim=(- 1)).squeeze() x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training, p=self.dropout_prob) x = self.fc2(x).squeeze() x = self.output_controller(x) return x def output_controller(self, x): if self.soft_decision: return self.sigmoid(x) if self.stochastic: x = self.sigmoid(x) return ops.ST_StochasticIndicator()(x) else: x = self.sigmoid(x) return ops.ST_Indicator()(x)
class RouterGAPwithConv_TwoFClayers(nn.Module): ' Routing function:\n Conv2D + GAP + fc1 + fc2 \n ' def __init__(self, input_nc, input_width, input_height, ngf=10, kernel_size=3, soft_decision=True, stochastic=False, reduction_rate=2, dropout_prob=0.0, **kwargs): super(RouterGAPwithConv_TwoFClayers, self).__init__() self.ngf = ngf self.soft_decision = soft_decision self.stochastic = stochastic self.dropout_prob = dropout_prob if (max(input_width, input_height) < kernel_size): warnings.warn('Router kernel too large, shrink it') kernel_size = max(input_width, input_height) self.conv1 = nn.Conv2d(input_nc, ngf, kernel_size=kernel_size) self.fc1 = nn.Linear(ngf, ((ngf / reduction_rate) + 1)) self.fc2 = nn.Linear(((ngf / reduction_rate) + 1), 1) self.sigmoid = nn.Sigmoid() def forward(self, x): x = F.relu(self.conv1(x)) x = x.mean(dim=(- 1)).mean(dim=(- 1)).squeeze() x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training, p=self.dropout_prob) x = self.fc2(x).squeeze() x = self.output_controller(x) return x def output_controller(self, x): if self.soft_decision: return self.sigmoid(x) if self.stochastic: x = self.sigmoid(x) return ops.ST_StochasticIndicator()(x) else: x = self.sigmoid(x) return ops.ST_Indicator()(x)
class LR(nn.Module): ' Logistinc regression\n ' def __init__(self, input_nc, input_width, input_height, no_classes=10, **kwargs): super(LR, self).__init__() self.fc = nn.Linear(((input_nc * input_width) * input_height), no_classes) def forward(self, x): x = x.view(x.size(0), (- 1)) return F.log_softmax(self.fc(x))
class MLP_LeNet(nn.Module): ' The last fully-connected part of LeNet\n ' def __init__(self, input_nc, input_width, input_height, no_classes=10, **kwargs): super(MLP_LeNet, self).__init__() assert (((input_nc * input_width) * input_height) > 120) self.fc1 = nn.Linear(((input_nc * input_width) * input_height), 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, no_classes) def forward(self, x): out = x.view(x.size(0), (- 1)) out = F.relu(self.fc1(out)) out = F.relu(self.fc2(out)) out = self.fc3(out) return F.log_softmax(out)
class MLP_LeNetMNIST(nn.Module): ' The last fully connected part of LeNet MNIST:\n https://github.com/BVLC/caffe/blob/master/examples/mnist/lenet.prototxt\n ' def __init__(self, input_nc, input_width, input_height, dropout_prob=0.0, **kwargs): super(MLP_LeNetMNIST, self).__init__() self.dropout_prob = dropout_prob ngf = ((input_nc * input_width) * input_height) self.fc1 = nn.Linear(ngf, int(round((ngf / 1.6)))) self.fc2 = nn.Linear(int(round((ngf / 1.6))), 10) def forward(self, x): x = x.view(x.size(0), (- 1)) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training, p=self.dropout_prob) x = self.fc2(x) return F.log_softmax(x)
class Solver_GAP_TwoFClayers(nn.Module): ' GAP + fc1 + fc2 ' def __init__(self, input_nc, input_width, input_height, dropout_prob=0.0, reduction_rate=2, **kwargs): super(Solver_GAP_TwoFClayers, self).__init__() self.dropout_prob = dropout_prob self.reduction_rate = reduction_rate self.fc1 = nn.Linear(input_nc, ((input_nc / reduction_rate) + 1)) self.fc2 = nn.Linear(((input_nc / reduction_rate) + 1), 10) self.sigmoid = nn.Sigmoid() def forward(self, x): x = x.mean(dim=(- 1)).mean(dim=(- 1)).squeeze() x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training, p=self.dropout_prob) x = self.fc2(x).squeeze() return F.log_softmax(x)
class MLP_AlexNet(nn.Module): ' The last fully connected part of LeNet MNIST:\n https://github.com/BVLC/caffe/blob/master/examples/mnist/lenet.prototxt\n ' def __init__(self, input_nc, input_width, input_height, dropout_prob=0.0, **kwargs): super(MLP_AlexNet, self).__init__() self.dropout_prob = dropout_prob ngf = ((input_nc * input_width) * input_height) self.fc1 = nn.Linear(ngf, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = x.view(x.size(0), (- 1)) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training, p=self.dropout_prob) x = self.fc2(x) return F.log_softmax(x)
class Solver_GAP_OneFClayers(nn.Module): ' GAP + fc1 ' def __init__(self, input_nc, input_width, input_height, dropout_prob=0.0, reduction_rate=2, **kwargs): super(Solver_GAP_OneFClayers, self).__init__() self.dropout_prob = dropout_prob self.reduction_rate = reduction_rate self.fc1 = nn.Linear(input_nc, 10) self.sigmoid = nn.Sigmoid() def forward(self, x): x = x.mean(dim=(- 1)).mean(dim=(- 1)).squeeze() x = F.dropout(x, training=self.training, p=self.dropout_prob) x = self.fc1(x) return F.log_softmax(x)
def weight_init(m): classname = m.__class__.__name__ print(classname) if (classname.find('Conv2d') != (- 1)): nn.init.xavier_normal(m.weight, gain=np.sqrt(2)) if (m.bias is not None): nn.init.constant(m.bias, 0.0) elif (classname.find('Linear') != (- 1)): nn.init.xavier_uniform(m.weight, gain=np.sqrt(2)) if (m.bias is not None): nn.init.constant(m.bias, 0.0)
class ST_Indicator(torch.autograd.Function): ' Straight-through indicator function 1(0.5 =< input):\n rounds a tensor whose values are in [0,1] to a tensor with values in {0, 1},\n using identity for its gradient.\n ' def forward(self, input): return torch.round(input) def backward(self, grad_output): '\n In the backward pass, just use unscaled straight-through estimator.\n ' return grad_output
class ST_StochasticIndicator(torch.autograd.Function): ' Stochastic version of ST_Indicator:\n indicator function 1(z =< input) where z is drawn from Uniform[0,1]\n with identity for its gradient.\n ' def forward(self, input): '\n Args:\n input (float tensor of values between 0 and 1): threshold prob\n\n Return:\n input: float tensor of values 0 or 1\n ' z = input.new(input.size()).uniform_(0, 1) return torch.abs(torch.round(((input - z) + 0.5))) def backward(self, grad_output): '\n In the backward pass, just use unscaled straight-through estimator.\n ' return grad_output
def neg_ce_fairflip(p, coeff): ' Compute the negative CE between p and Bernouli(0.5)\n ' nce = (((- 0.5) * coeff) * (torch.log((p + 1e-10)) + torch.log(((1.0 - p) + 1e-10))).mean()) return nce
def weighted_cross_entropy(input, target, weights): ' Compute cross entropy weighted per example\n got most ideas from https://github.com/pytorch/pytorch/issues/563\n\n Args:\n input (torch tensor): (N,C) log probabilities e.g. F.log_softmax(y_hat)\n target (torch tensor): (N) where each value is 0 <= targes[i] <=C-1\n weights (torch tensor): (N) per-example weight\n\n Return:\n nlhd: negative loglijelihood\n ' logpy = torch.gather(input, 1, target.view((- 1), 1)).view((- 1)) nlhd = (- (logpy * weights).mean()) return nlhd
def differential_entropy(input, bins=10, min=0.0, max=1.0): ' Approximate dfferential entropy: H(x) = E[-log P(x)]\n Fit a histogram and compute the maximum likelihood estimator of entropy\n i.e. H^{hat}(x) = - \\sum_{i} P(x_i) log(P(x_i))\n\n See https://en.wikipedia.org/wiki/Entropy_estimation\n\n Args:\n input (torch tensor): (N) probabilities\n\n ' p_x_list = (torch.histc(input, bins=bins, min=min, max=max) / input.size(0)) h = ((- p_x_list) * torch.log((p_x_list + 1e-08))).sum() return h
def coefficient_of_variation(input): ' Compute the coefficient of varation std/mean:\n ' epsilon = 1e-10 return (input.std() / (input.mean() + epsilon))
def count_number_transforms(node_idx, tree_struct): ' Get the number of transforms up to and including node_idx \n ' (nodes, _) = get_path_to_root(node_idx, tree_struct) count = 0 for i in nodes: if tree_struct[i]['transformed']: count += 1 return count
def count_number_transforms_after_last_downsample(node_idx, tree_struct): (nodes, _) = get_path_to_root(node_idx, tree_struct) last_idx = 0 for i in nodes: if (tree_struct[i]['transformed'] and tree_struct[i]['downsampled']): last_idx = i count = 0 for i in nodes[last_idx:]: if (tree_struct[i]['transformed'] and (not tree_struct[i]['downsampled'])): count += 1 return count
def get_leaf_nodes(struct): ' Get the list of leaf nodes.\n ' leaf_list = [] for (idx, node) in enumerate(struct): if node['is_leaf']: leaf_list.append(idx) return leaf_list
def get_past_leaf_nodes(struct, current_idx): ' Get the list of nodes that were leaves when the specified node is added\n to the tree.\n ' if (current_idx == 0): return [0] leaf_list = [current_idx] node_current = struct[current_idx] parent_idx = struct[current_idx]['parent'] node_r = struct[parent_idx]['right_child'] node_l = struct[parent_idx]['left_child'] if (current_idx == node_r): bro_idx = node_l else: bro_idx = node_r if (not struct[parent_idx]['extended']): leaf_list.append(bro_idx) leaf_nodes_below_parent = [node['index'] for node in struct if ((node['index'] < parent_idx) and node['is_leaf'])] leaf_list = (leaf_list + leaf_nodes_below_parent) leaf_same_level = [node['index'] for node in struct if ((node['index'] < current_idx) and (node['index'] != bro_idx) and (node['level'] == node_current['level']))] leaf_list = (leaf_list + leaf_same_level) leaf_above_level = [node['index'] for node in struct if ((node['index'] > parent_idx) and (node['level'] == (node_current['level'] - 1)))] leaf_list = (leaf_list + leaf_above_level) leaf_list.sort() return leaf_list
def get_path_to_root_old(node_idx, struct): ' Get the list of nodes from the current node to the root.\n [0, n1,....., node_idx]\n ' paths_list = [] while (node_idx >= 0): paths_list.append(node_idx) node_idx = get_parent(node_idx, struct) return paths_list[::(- 1)]
def get_path_to_root(node_idx, struct): ' Get two lists:\n First, list of all nodes from the root node to the given node\n Second, list of left-child-status (boolean) of each edge between nodes in the first list\n ' paths_list = [] left_child_status = [] while (node_idx >= 0): if (node_idx > 0): lcs = get_left_or_right(node_idx, struct) left_child_status.append(lcs) paths_list.append(node_idx) node_idx = get_parent(node_idx, struct) paths_list = paths_list[::(- 1)] left_child_status = left_child_status[::(- 1)] return (paths_list, left_child_status)
def get_parent(node_idx, struct): ' Get index of parent node\n ' return struct[node_idx]['parent']
def get_left_or_right(node_idx, struct): ' Return True if the node is a left child of its parent.\n o/w return false.\n ' parent_node = struct[node_idx]['parent'] return (struct[parent_node]['left_child'] == node_idx)
def node_pred(nodes, edges, tree_modules, input): ' Perform prediction on a given node given its path on the tree.\n e.g.\n nodes = [0, 1, 4, 10]\n edges = [True, False, False]\n ' prob = 1.0 for (node, state) in zip(nodes[:(- 1)], edges): input = tree_modules[node]['transform'](input) prob *= (tree_modules[node]['router'](input) if state else (1.0 - tree_modules[node]['router'](input))) node_final = nodes[(- 1)] input = tree_modules[node_final]['transform'](input) prob = torch.unsqueeze(prob, 1) y_pred = (prob * tree_modules[node_final]['LR'](input)) return y_pred
def node_pred_split(input, nodes, edges, tree_modules, node_left, node_right): ' Perform prediction on a split node given its path on the tree.\n Here, the last node in the list "nodes" is assumed to be split.\n e.g.\n nodes = [0, 1, 4, 10]\n edges = [True, False, False]\n then, node 10 is assumed to be split.\n\n Args:\n input (torch.Variable): input images\n nodes (list): list of all nodes (index) on the path between root and given node\n edges (list): list of left-child-status (boolean) of each edge between nodes in\n the list \'nodes\'\n tree_modules (list): list of all node modules in the tree\n\n node_left (dict) : candidate node for the left child of node\n node_right (dict): candidate node for the right child of node\n Return:\n ' prob = 1.0 for (node, state) in zip(nodes[:(- 1)], edges): input = tree_modules[node]['transform'](input) prob *= (tree_modules[node]['router'](input) if state else (1.0 - tree_modules[node]['router'](input))) node_final = nodes[(- 1)] input = tree_modules[node_final]['transform'](input) prob = torch.unsqueeze(prob, 1) prob_last = (tree_modules[node_final]['router'](input) if state else (1.0 - tree_modules[node_final]['router'](input))) prob_last = torch.unsqueeze(prob_last, 1) y_pred = (prob * ((prob_last * node_left['LR'](node_left['transform'](input))) + ((1.0 - prob_last) * node_right['LR'](node_right['transform'](input))))) return y_pred
def get_params_node(grow, node_idx, model): 'Get the list of trainable parameters at the given node.\n\n If grow=True, then fetch the local parameters\n (i.e. parent router + 2 children transformers and solvers)\n ' if grow: names = [name for (name, param) in model.named_parameters() if (((('.' + str(node_idx)) + '.router') in name) or (('child' in name) and (not ('router' in name))))] print('\nSelectively optimising the parameters below: ') for name in names: print((' ' + name)) params = [param for (name, param) in model.named_parameters() if (((('.' + str(node_idx)) + '.router') in name) or (('child' in name) and (not ('router' in name))))] for p in params: p.requires_grad = True return (params, names) else: print('\nPerform global training') return (list(model.parameters()), [name for (name, param) in model.named_parameters()])
class ChunkSampler(sampler.Sampler): " Samples elements sequentially from some offset.\n Args:\n num_samples: # of desired datapoints\n start: offset where we should start selecting from\n\n Source:\n https://github.com/pytorch/vision/issues/168\n\n Examples:\n NUM_TRAIN = 49000\n NUM_VAL = 1000\n cifar10_train = dset.CIFAR10('./cs231n/datasets', train=True, download=True,\n transform=T.ToTensor())\n loader_train = DataLoader(cifar10_train, batch_size=64, sampler=ChunkSampler(NUM_TRAIN, 0))\n\n cifar10_val = dset.CIFAR10('./cs231n/datasets', train=True, download=True, transform=T.ToTensor())\n loader_val = DataLoader(cifar10_val, batch_size=64, sampler=ChunkSampler(NUM_VAL, NUM_TRAIN))\n\n " def __init__(self, num_samples, start=0, shuffle=False): self.num_samples = num_samples self.start = start self.shuffle = shuffle def __iter__(self): if self.shuffle: return iter((torch.randperm(self.num_samples) + self.start).long()) else: return iter(range(self.start, (self.start + self.num_samples))) def __len__(self): return self.num_samples
def train(model, data_loader, optimizer, node_idx): ' Train step' model.train() train_loss = 0 no_points = 0 train_epoch_loss = 0 for (batch_idx, (x, y)) in enumerate(data_loader): optimizer.zero_grad() if args.cuda: (x, y) = (x.cuda(), y.cuda()) (x, y) = (Variable(x), Variable(y)) (y_pred, p_out) = model(x) loss = F.nll_loss(y_pred, y) train_epoch_loss += (loss.data[0] * y.size(0)) train_loss += (loss.data[0] * y.size(0)) loss.backward() optimizer.step() records['counter'] += 1 no_points += y.size(0) if ((batch_idx % args.log_interval) == 0): train_loss /= no_points records['train_loss'].append(train_loss) records['train_nodes'].append(node_idx) sys.stdout.flush() sys.stdout.write('\t [{}/{} ({:.0f}%)] Loss: {:.6f} \r'.format((batch_idx * len(x)), NUM_TRAIN, ((100.0 * batch_idx) / NUM_TRAIN), train_loss)) train_loss = 0 no_points = 0 train_epoch_loss /= NUM_TRAIN records['train_epoch_loss'].append(train_epoch_loss) if (train_epoch_loss < records['train_best_loss']): records['train_best_loss'] = train_epoch_loss print('\nTrain set: Average loss: {:.4f}'.format(train_epoch_loss))
def valid(model, data_loader, node_idx, struct): ' Validation step ' model.eval() valid_epoch_loss = 0 correct = 0 for (data, target) in data_loader: if args.cuda: (data, target) = (data.cuda(), target.cuda()) (data, target) = (Variable(data, volatile=True), Variable(target)) output = model(data) valid_epoch_loss += F.nll_loss(output, target, size_average=False).data[0] pred = output.data.max(1, keepdim=True)[1] correct += pred.eq(target.data.view_as(pred)).cpu().sum() valid_epoch_loss /= NUM_VALID valid_epoch_accuracy = ((100.0 * correct) / NUM_VALID) records['valid_epoch_loss'].append(valid_epoch_loss) records['valid_epoch_accuracy'].append(valid_epoch_accuracy) if (valid_epoch_loss < records['valid_best_loss']): records['valid_best_loss'] = valid_epoch_loss if (valid_epoch_accuracy > records['valid_best_accuracy']): records['valid_best_accuracy'] = valid_epoch_accuracy is_init_root_train = ((not model.split) and (not model.extend) and (node_idx == 0)) if ((not is_init_root_train) and model.split and (valid_epoch_loss < records['valid_best_loss_nodes_split'][node_idx])): records['valid_best_loss_nodes_split'][node_idx] = valid_epoch_loss checkpoint_model('model_tmp.pth', model=model) checkpoint_msc(struct, records) if ((not is_init_root_train) and model.extend and (valid_epoch_loss < records['valid_best_loss_nodes_ext'][node_idx])): records['valid_best_loss_nodes_ext'][node_idx] = valid_epoch_loss checkpoint_model('model_ext.pth', model=model) checkpoint_msc(struct, records) if (is_init_root_train and (valid_epoch_loss < records['valid_best_root_nosplit'])): records['valid_best_root_nosplit'] = valid_epoch_loss checkpoint_model('model_tmp.pth', model=model) checkpoint_msc(struct, records) if ((not is_init_root_train) and (valid_epoch_loss < records['valid_best_loss_nodes'][node_idx])): records['valid_best_loss_nodes'][node_idx] = valid_epoch_loss if ((not model.split) and (not model.extend)): checkpoint_model('model_tmp.pth', model=model) checkpoint_msc(struct, records) end = time.time() records['time'] = (end - start) print('Valid set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\nTook {} seconds. '.format(valid_epoch_loss, correct, NUM_VALID, ((100.0 * correct) / NUM_VALID), records['time'])) return valid_epoch_loss
def test(model, data_loader): ' Test step ' model.eval() test_loss = 0 correct = 0 for (data, target) in data_loader: if args.cuda: (data, target) = (data.cuda(), target.cuda()) (data, target) = (Variable(data, volatile=True), Variable(target)) output = model(data) test_loss += F.nll_loss(output, target, size_average=False).data[0] pred = output.data.max(1, keepdim=True)[1] correct += pred.eq(target.data.view_as(pred)).cpu().sum() test_loss /= len(data_loader.dataset) test_accuracy = ((100.0 * correct) / len(data_loader.dataset)) records['test_epoch_loss'].append(test_loss) records['test_epoch_accuracy'].append(test_accuracy) if (test_loss < records['test_best_loss']): records['test_best_loss'] = test_loss if (test_accuracy > records['test_best_accuracy']): records['test_best_accuracy'] = test_accuracy end = time.time() print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\nTook {} seconds. '.format(test_loss, correct, len(data_loader.dataset), ((100.0 * correct) / len(data_loader.dataset)), (end - start)))
def _load_checkpoint(model_file_name): save_dir = './experiments/{}/{}/{}/{}'.format(args.dataset, args.experiment, args.subexperiment, 'checkpoints') model = torch.load(((save_dir + '/') + model_file_name)) if args.cuda: model.cuda() return model
def checkpoint_model(model_file_name, struct=None, modules=None, model=None, figname='hist.png', data_loader=None): if (not os.path.exists(os.path.join('./experiments', args.dataset, args.experiment, args.subexperiment))): os.makedirs(os.path.join('./experiments', args.dataset, args.experiment, args.subexperiment, 'figures')) os.makedirs(os.path.join('./experiments', args.dataset, args.experiment, args.subexperiment, 'checkpoints')) if ((not model) and modules and struct): model = Tree(struct, modules, cuda_on=args.cuda) save_dir = './experiments/{}/{}/{}/{}'.format(args.dataset, args.experiment, args.subexperiment, 'checkpoints') model_path = ((save_dir + '/') + model_file_name) torch.save(model, model_path) print('Model saved to {}'.format(model_path)) if (args.visualise_split and (not (data_loader is None))): save_hist_dir = './experiments/{}/{}/{}/{}'.format(args.dataset, args.experiment, args.subexperiment, 'figures') visualise_routers_behaviours(model, data_loader, fig_scale=6, axis_font=20, subtitle_font=20, cuda_on=args.cuda, objects=args.classes, plot_on=False, save_as=((save_hist_dir + '/') + figname))
def checkpoint_msc(struct, data_dict): ' Save structural information of the model and experimental results.\n\n Args:\n struct (list) : list of dictionaries each of which contains\n meta information about each node of the tree.\n data_dict (dict) : data about the experiment (e.g. loss, configurations)\n ' if (not os.path.exists(os.path.join('./experiments', args.dataset, args.experiment, args.subexperiment))): os.makedirs(os.path.join('./experiments', args.dataset, args.experiment, args.subexperiment, 'figures')) os.makedirs(os.path.join('./experiments', args.dataset, args.experiment, args.subexperiment, 'checkpoints')) save_dir = './experiments/{}/{}/{}/{}'.format(args.dataset, args.experiment, args.subexperiment, 'checkpoints') struct_path = (save_dir + '/tree_structures.json') with open(struct_path, 'w') as f: json.dump(struct, f) print('Tree structure saved to {}'.format(struct_path)) dict_path = (save_dir + '/records.json') with open(dict_path, 'w') as f_d: json.dump(data_dict, f_d) print('Other data saved to {}'.format(dict_path))
def get_decision(criteria, node_idx, tree_struct): " Define the splitting criteria\n\n Args:\n criteria (str): Growth criteria.\n node_idx (int): Index of the current node.\n tree_struct (list) : list of dictionaries each of which contains\n meta information about each node of the tree.\n\n Returns:\n The function returns one of the following strings\n 'split': split the node\n 'extend': extend the node\n 'keep': keep the node as it is\n " if (criteria == 'always'): if (tree_struct[node_idx]['valid_accuracy_gain_ext'] > tree_struct[node_idx]['valid_accuracy_gain_split'] > 0.0): return 'extend' else: return 'split' elif (criteria == 'avg_valid_loss'): if ((tree_struct[node_idx]['valid_accuracy_gain_ext'] > tree_struct[node_idx]['valid_accuracy_gain_split']) and (tree_struct[node_idx]['valid_accuracy_gain_ext'] > 0.0)): print('Average valid loss is reduced by {} '.format(tree_struct[node_idx]['valid_accuracy_gain_ext'])) return 'extend' elif (tree_struct[node_idx]['valid_accuracy_gain_split'] > 0.0): print('Average valid loss is reduced by {} '.format(tree_struct[node_idx]['valid_accuracy_gain_split'])) return 'split' else: print('Average valid loss is aggravated by split/extension. Keep the node as it is.') return 'keep' else: raise NotImplementedError('specified growth criteria is not available. ')
def optimize_fixed_tree(model, tree_struct, train_loader, valid_loader, test_loader, no_epochs, node_idx): ' Train a tree with fixed architecture.\n\n Args:\n model (torch.nn.module): tree model\n tree_struct (list): list of dictionaries which contain information\n about all nodes in the tree.\n train_loader (torch.utils.data.DataLoader) : data loader of train data\n valid_loader (torch.utils.data.DataLoader) : data loader of valid data\n test_loader (torch.utils.data.DataLoader) : data loader of test data\n no_epochs (int): number of epochs for training\n node_idx (int): index of the node you want to optimize\n\n Returns:\n returns the trained model and newly added nodes (if grown).\n ' grow = (model.split or model.extend) (params, names) = get_params_node(grow, node_idx, model) for (i, (n, p)) in enumerate(model.named_parameters()): if (not (n in names)): p.requires_grad = False else: p.requires_grad = True for (i, p) in enumerate(params): if (not p.requires_grad): print(('(Grad not required)' + names[i])) optimizer = optim.Adam(filter((lambda p: p.requires_grad), params), lr=args.lr) if args.scheduler: scheduler = get_scheduler(args.scheduler, optimizer, grow) if ((not ((not grow) and (node_idx == 0))) and (len(records['valid_best_loss_nodes']) == node_idx)): records['valid_best_loss_nodes'].append(np.inf) if ((not ((not grow) and (node_idx == 0))) and (len(records['valid_best_loss_nodes_split']) == node_idx)): records['valid_best_loss_nodes_split'].append(np.inf) if ((not ((not grow) and (node_idx == 0))) and (len(records['valid_best_loss_nodes_ext']) == node_idx)): records['valid_best_loss_nodes_ext'].append(np.inf) min_improvement = 0.0 valid_loss = np.inf patience_cnt = 1 for epoch in range(1, (no_epochs + 1)): print('\n----- Layer {}, Node {}, Epoch {}/{}, Patience {}/{}---------'.format(tree_struct[node_idx]['level'], node_idx, epoch, no_epochs, patience_cnt, args.epochs_patience)) train(model, train_loader, optimizer, node_idx) valid_loss_new = valid(model, valid_loader, node_idx, tree_struct) if (args.scheduler == 'plateau'): scheduler.step(valid_loss_new) elif (args.scheduler == 'step_lr'): scheduler.step() test(model, test_loader) if ((not ((valid_loss - valid_loss_new) > min_improvement)) and grow): patience_cnt += 1 valid_loss = (valid_loss_new * 1.0) if (patience_cnt > args.epochs_patience > 0): print('Early stopping') break if ((no_epochs > 0) and grow): if model.extend: print('return the node-wise best extended model') model = _load_checkpoint('model_ext.pth') else: print('return the node-wise best split model') model = _load_checkpoint('model_tmp.pth') tree_modules = model.update_tree_modules() if model.split: (child_left, child_right) = model.update_children() return (model, tree_modules, child_left, child_right) elif model.extend: child_extension = model.update_children() return (model, tree_modules, child_extension) else: return (model, tree_modules)
def grow_ant_nodewise(): 'The main function for optimising an ANT ' tree_struct = [] tree_modules = [] (root_meta, root_module) = define_node(args, node_index=0, level=0, parent_index=(- 1), tree_struct=tree_struct) tree_struct.append(root_meta) tree_modules.append(root_module) model = Tree(tree_struct, tree_modules, split=False, extend=False, cuda_on=args.cuda) if args.cuda: model.cuda() (model, tree_modules) = optimize_fixed_tree(model, tree_struct, train_loader, valid_loader, test_loader, args.epochs_node, node_idx=0) checkpoint_model('model.pth', struct=tree_struct, modules=tree_modules) checkpoint_msc(tree_struct, records) nextind = 1 last_node = 0 for lyr in range(args.maxdepth): print('---------------------------------------------------------------') print(('\nAt layer ' + str(lyr))) for node_idx in range(len(tree_struct)): change = False if (tree_struct[node_idx]['is_leaf'] and (not tree_struct[node_idx]['visited'])): print(('\nProcessing node ' + str(node_idx))) identity = True (meta_l, node_l) = define_node(args, node_index=nextind, level=(lyr + 1), parent_index=node_idx, tree_struct=tree_struct, identity=identity) (meta_r, node_r) = define_node(args, node_index=(nextind + 1), level=(lyr + 1), parent_index=node_idx, tree_struct=tree_struct, identity=identity) if (args.solver_inherit and meta_l['identity'] and meta_r['identity'] and (not (node_idx == 0))): node_l['classifier'] = tree_modules[node_idx]['classifier'] node_r['classifier'] = tree_modules[node_idx]['classifier'] model_split = Tree(tree_struct, tree_modules, split=True, node_split=node_idx, child_left=node_l, child_right=node_r, extend=False, cuda_on=args.cuda) (meta_e, node_e) = define_node(args, node_index=nextind, level=(lyr + 1), parent_index=node_idx, tree_struct=tree_struct, identity=False) tree_modules[node_idx]['router'] = One() model_ext = Tree(tree_struct, tree_modules, split=False, extend=True, node_extend=node_idx, child_extension=node_e, cuda_on=args.cuda) best_tr_loss = records['train_best_loss'] best_va_loss = records['valid_best_loss'] best_te_loss = records['test_best_loss'] print('\n---------- Optimizing a binary split ------------') if args.cuda: model_split.cuda() (model_split, tree_modules_split, node_l, node_r) = optimize_fixed_tree(model_split, tree_struct, train_loader, valid_loader, test_loader, args.epochs_node, node_idx) best_tr_loss_after_split = records['train_best_loss'] best_va_loss_adter_split = records['valid_best_loss_nodes_split'][node_idx] best_te_loss_after_split = records['test_best_loss'] tree_struct[node_idx]['train_accuracy_gain_split'] = (best_tr_loss - best_tr_loss_after_split) tree_struct[node_idx]['valid_accuracy_gain_split'] = (best_va_loss - best_va_loss_adter_split) tree_struct[node_idx]['test_accuracy_gain_split'] = (best_te_loss - best_te_loss_after_split) print('\n----------- Optimizing an extension --------------') if (not meta_e['identity']): if args.cuda: model_ext.cuda() (model_ext, tree_modules_ext, node_e) = optimize_fixed_tree(model_ext, tree_struct, train_loader, valid_loader, test_loader, args.epochs_node, node_idx) best_tr_loss_after_ext = records['train_best_loss'] best_va_loss_adter_ext = records['valid_best_loss_nodes_ext'][node_idx] best_te_loss_after_ext = records['test_best_loss'] tree_struct[node_idx]['train_accuracy_gain_ext'] = (best_tr_loss - best_tr_loss_after_ext) tree_struct[node_idx]['valid_accuracy_gain_ext'] = (best_va_loss - best_va_loss_adter_ext) tree_struct[node_idx]['test_accuracy_gain_ext'] = (best_te_loss - best_te_loss_after_ext) else: print('No extension as the transformer is an identity function.') criteria = get_decision(args.criteria, node_idx, tree_struct) if (criteria == 'split'): print(('\nSplitting node ' + str(node_idx))) tree_struct[node_idx]['is_leaf'] = False tree_struct[node_idx]['left_child'] = nextind tree_struct[node_idx]['right_child'] = (nextind + 1) tree_struct[node_idx]['split'] = True tree_struct.append(meta_l) tree_modules_split.append(node_l) tree_struct.append(meta_r) tree_modules_split.append(node_r) tree_modules = tree_modules_split nextind += 2 change = True elif (criteria == 'extend'): print(('\nExtending node ' + str(node_idx))) tree_struct[node_idx]['is_leaf'] = False tree_struct[node_idx]['left_child'] = nextind tree_struct[node_idx]['extended'] = True tree_struct.append(meta_e) tree_modules_ext.append(node_e) tree_modules = tree_modules_ext nextind += 1 change = True else: print(('No splitting at node ' + str(node_idx))) print('Revert the weights to the pre-split state.') model = _load_checkpoint('model.pth') tree_modules = model.update_tree_modules() tree_struct[node_idx]['visited'] = True checkpoint_model('model.pth', struct=tree_struct, modules=tree_modules, data_loader=test_loader, figname='hist_split_node_{:03d}.png'.format(node_idx)) checkpoint_msc(tree_struct, records) last_node = node_idx if (args.finetune_during_growth and ((criteria == 1) or (criteria == 2))): print('\n-------------- Global refinement --------------') model = Tree(tree_struct, tree_modules, split=False, node_split=last_node, extend=False, node_extend=last_node, cuda_on=args.cuda) if args.cuda: model.cuda() (model, tree_modules) = optimize_fixed_tree(model, tree_struct, train_loader, valid_loader, test_loader, args.epochs_finetune_node, node_idx) if (not change): break print('\n\n------------------- Fine-tuning the tree --------------------') best_valid_accuracy_before = records['valid_best_accuracy'] model = Tree(tree_struct, tree_modules, split=False, node_split=last_node, child_left=None, child_right=None, extend=False, node_extend=last_node, child_extension=None, cuda_on=args.cuda) if args.cuda: model.cuda() (model, tree_modules) = optimize_fixed_tree(model, tree_struct, train_loader, valid_loader, test_loader, args.epochs_finetune, last_node) best_valid_accuracy_after = records['valid_best_accuracy'] if ((best_valid_accuracy_after - best_valid_accuracy_before) > 0): checkpoint_model('model.pth', struct=tree_struct, modules=tree_modules, data_loader=test_loader, figname='hist_split_node_finetune.png') checkpoint_msc(tree_struct, records)
def define_node(args, node_index, level, parent_index, tree_struct, identity=False): ' Define node operations.\n \n In this function, we assume that 3 building blocks of node operations\n i.e. transformer, solver and router are of fixed complexity. \n ' num_transforms = (0 if (node_index == 0) else count_number_transforms(parent_index, tree_struct)) meta = {'index': node_index, 'parent': parent_index, 'left_child': 0, 'right_child': 0, 'level': level, 'extended': False, 'split': False, 'visited': False, 'is_leaf': True, 'train_accuracy_gain_split': (- np.inf), 'valid_accuracy_gain_split': (- np.inf), 'test_accuracy_gain_split': (- np.inf), 'train_accuracy_gain_ext': (- np.inf), 'valid_accuracy_gain_ext': (- np.inf), 'test_accuracy_gain_ext': (- np.inf), 'num_transforms': num_transforms} if (not tree_struct): meta['in_shape'] = (1, args.input_nc, args.input_width, args.input_height) else: meta['in_shape'] = tree_struct[parent_index]['out_shape'] if ((meta['in_shape'][2] < 3) or (meta['in_shape'][3] < 3)): identity = True if (identity or (args.transformer_ver == 1)): meta['transformed'] = False else: meta['transformed'] = True num_downsample = (0 if (node_index == 0) else count_number_transforms_after_last_downsample(parent_index, tree_struct)) if ((args.downsample_interval == num_downsample) or (node_index == 0)): meta['downsampled'] = True else: meta['downsampled'] = False config_t = {'kernel_size': args.transformer_k, 'ngf': args.transformer_ngf, 'batch_norm': args.batch_norm, 'downsample': meta['downsampled'], 'expansion_rate': args.transformer_expansion_rate, 'reduction_rate': args.transformer_reduction_rate} transformer_ver = args.transformer_ver if identity: transformer = models.Identity(meta['in_shape'][1], meta['in_shape'][2], meta['in_shape'][3], **config_t) else: transformer = define_transformer(transformer_ver, meta['in_shape'][1], meta['in_shape'][2], meta['in_shape'][3], **config_t) meta['identity'] = identity meta['out_shape'] = transformer.outputshape print('---------------- data shape before/after transformer -------------') print(meta['in_shape'], type(meta['in_shape'])) print(meta['out_shape'], type(meta['out_shape'])) config_s = {'no_classes': args.no_classes, 'dropout_prob': args.solver_dropout_prob, 'batch_norm': args.batch_norm} solver = define_solver(args.solver_ver, meta['out_shape'][1], meta['out_shape'][2], meta['out_shape'][3], **config_s) config_r = {'kernel_size': args.router_k, 'ngf': args.router_ngf, 'soft_decision': True, 'stochastic': False, 'dropout_prob': args.router_dropout_prob, 'batch_norm': args.batch_norm} router = define_router(args.router_ver, meta['out_shape'][1], meta['out_shape'][2], meta['out_shape'][3], **config_r) module = {'transform': transformer, 'classifier': solver, 'router': router} return (meta, module)
def define_transformer(version, input_nc, input_width, input_height, **kwargs): if (version == 1): return models.Identity(input_nc, input_width, input_height, **kwargs) elif (version == 2): return models.JustConv(input_nc, input_width, input_height, **kwargs) elif (version == 3): return models.ConvPool(input_nc, input_width, input_height, **kwargs) elif (version == 4): return models.ResidualTransformer(input_nc, input_width, input_height, **kwargs) elif (version == 5): return models.VGG13ConvPool(input_nc, input_width, input_height, **kwargs) else: raise NotImplementedError('Specified transformer module not available.')
def define_router(version, input_nc, input_width, input_height, **kwargs): if (version == 1): return models.Router(input_nc, input_width, input_height, **kwargs) elif (version == 2): return models.RouterGAP(input_nc, input_width, input_height, **kwargs) elif (version == 3): return models.RouterGAPwithDoubleConv(input_nc, input_width, input_height, **kwargs) elif (version == 4): return models.Router_MLP_h1(input_nc, input_width, input_height, **kwargs) elif (version == 5): return models.RouterGAP_TwoFClayers(input_nc, input_width, input_height, **kwargs) elif (version == 6): return models.RouterGAPwithConv_TwoFClayers(input_nc, input_width, input_height, **kwargs) else: raise NotImplementedError('Specified router module not available!')
def define_solver(version, input_nc, input_width, input_height, **kwargs): if (version == 1): return models.LR(input_nc, input_width, input_height, **kwargs) elif (version == 2): return models.MLP_LeNet(input_nc, input_width, input_height, **kwargs) elif (version == 3): return models.MLP_LeNetMNIST(input_nc, input_width, input_height, **kwargs) elif (version == 4): return models.Solver_GAP_TwoFClayers(input_nc, input_width, input_height, **kwargs) elif (version == 5): return models.MLP_AlexNet(input_nc, input_width, input_height, **kwargs) elif (version == 6): return models.Solver_GAP_OneFClayers(input_nc, input_width, input_height, **kwargs) else: raise NotImplementedError('Specified solver module not available!')
def get_scheduler(scheduler_type, optimizer, grow): if (scheduler_type == 'step_lr'): scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[100, 150], gamma=0.1) elif (scheduler_type == 'plateau'): scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.1, patience=10) elif (scheduler_type == 'hybrid'): if grow: scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.1, patience=10) else: scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[100, 150], gamma=0.1) else: scheduler = None return scheduler
def imshow(img): npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0)))
def plot_hist(data, save_as='./figure'): fig = plt.figure() plt.hist(data, normed=True, bins=150, range=(0, 1.0)) fig.savefig(save_as)
def plot_hist_root(labels, split_status, save_as='./figures/hist_labels_split.png'): ' Plot the distribution of labels of a binary routing function.\n Args:\n labels (np array): labels (N) each entry contains a label\n split_status (np array bool): boolean array (N) where 0 indicates the entry\n belongs to the right and 1 indicates left.\n ' fig = plt.figure() plt.hist(labels[split_status], bins=range(11), alpha=0.75, label='right branch') plt.hist(labels[(split_status == False)], bins=range(11), alpha=0.5, label='left branch') plt.legend(loc='upper right') print(('save the histogram as ' + save_as)) fig.savefig(save_as)
def print_performance(jasonfile, model_name='model_1', figsize=(5, 5)): ' Inspect performance of a single model\n ' records = json.load(open(jasonfile, 'r')) print(('\n' + model_name)) print(' train_best_loss: {}'.format(records['train_best_loss'])) print(' valid_best_loss: {}'.format(records['valid_best_loss'])) print(' test_best_loss: {}'.format(records['test_best_loss'])) fig = plt.figure(figsize=figsize) plt.plot(np.arange(len(records['test_epoch_loss'])), np.array(records['test_epoch_loss']), linestyle='-.', color='b', label='test epoch loss') plt.plot(np.arange(len(records['train_epoch_loss']), dtype=float), np.array(records['train_epoch_loss']), color='r', linestyle='-', label='train epoch loss') plt.legend(loc='upper right') plt.ylabel('epoch wise loss (average CE loss)') plt.xlabel('epoch number')
def plot_performance(jasonfiles, model_names=[], figsize=(5, 5), title=''): ' Visualise the results for several models\n\n Args:\n jasonfiles (list): List of jason files\n model_names (list): List of model names\n ' fig = plt.figure(figsize=figsize) color = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'] if (not model_names): model_names = [str(i) for i in range(len(jasonfiles))] for (i, f) in enumerate(jasonfiles): records = json.load(open(f, 'r')) plt.plot(np.arange(len(records['test_epoch_loss'])), np.array(records['test_epoch_loss']), color=color[i], linestyle='-.', label=('test epoch loss: ' + model_names[i])) plt.plot(np.arange(len(records['train_epoch_loss']), dtype=float), np.array(records['train_epoch_loss']), color=color[i], linestyle='-', label=('train epoch loss: ' + model_names[i])) plt.ylabel('epoch wise loss (average CE loss)') plt.xlabel('epoch number') plt.legend(loc='upper right') plt.title(title)
def plot_accuracy(jasonfiles, model_names=[], figsize=(5, 5), ymax=100.0, title=''): fig = plt.figure(figsize=figsize) color = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'] if (not model_names): model_names = [str(i) for i in range(len(jasonfiles))] for (i, f) in enumerate(jasonfiles): records = json.load(open(f, 'r')) plt.plot(np.arange(len(records['test_epoch_accuracy']), dtype=float), np.array(records['test_epoch_accuracy']), color=color[i], linestyle='-', label=model_names[i]) plt.ylabel('test accuracy (%)') plt.xlabel('epoch number') plt.ylim(ymax=ymax) print((model_names[i] + ': accuracy = {}'.format(max(records['test_epoch_accuracy'])))) plt.legend(loc='lower right') plt.title(title)
def compute_error(model_file, data_loader, cuda_on=False, name=''): 'Load a model and compute errors on a held-out dataset\n Args:\n model_file (str): model parameters\n data_dataloader (torch.utils.data.DataLoader): data loader\n ' model = torch.load(model_file) if cuda_on: model.cuda() model.eval() test_loss = 0 correct = 0 for (data, target) in data_loader: if cuda_on: (data, target) = (data.cuda(), target.cuda()) (data, target) = (Variable(data, volatile=True), Variable(target)) output = model(data) test_loss += F.nll_loss(output, target, size_average=False).data[0] pred = output.data.max(1, keepdim=True)[1] correct += pred.eq(target.data.view_as(pred)).cpu().sum() test_loss /= len(data_loader.dataset) print((name + 'Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(test_loss, correct, len(data_loader.dataset), ((100.0 * correct) / len(data_loader.dataset)))))
def load_tree_model(model_file, cuda_on=False, soft_decision=True, stochastic=False, breadth_first=False, fast=False): 'Load a tree model. ' map_location = None if (not cuda_on): map_location = 'cpu' tree_tmp = torch.load(model_file, map_location=map_location) (tree_struct, tree_modules) = (tree_tmp.tree_struct, tree_tmp.update_tree_modules()) for node in tree_modules: node['router'].stochastic = stochastic node['router'].soft_decision = soft_decision node['router'].dropout_prob = 0.0 for node_meta in tree_struct: if (not ('extended' in node_meta.keys())): node_meta['extended'] = False model = models.Tree(tree_struct, tree_modules, split=False, cuda_on=cuda_on, soft_decision=soft_decision, breadth_first=breadth_first) if cuda_on: model.cuda() return model
def compute_error_general(model_file, data_loader, cuda_on=False, soft_decision=True, stochastic=False, breadth_first=False, fast=False, task='classification', name=''): 'Load a model and perform stochastic inferenc\n Args:\n model_file (str): model parameters\n data_dataloader (torch.utils.data.DataLoader): data loader\n\n ' map_location = None if (not cuda_on): map_location = 'cpu' tree_tmp = torch.load(model_file, map_location=map_location) (tree_struct, tree_modules) = (tree_tmp.tree_struct, tree_tmp.update_tree_modules()) for node in tree_modules: node['router'].stochastic = stochastic node['router'].soft_decision = soft_decision node['router'].dropout_prob = 0.0 for node_meta in tree_struct: if (not ('extended' in node_meta.keys())): node_meta['extended'] = False if (task == 'classification'): model = models.Tree(tree_struct, tree_modules, split=False, cuda_on=cuda_on, soft_decision=soft_decision, breadth_first=breadth_first) if cuda_on: model.cuda() model.eval() test_loss = 0 correct = 0 for (data, target) in data_loader: if cuda_on: (data, target) = (data.cuda(), target.cuda()) (data, target) = (Variable(data, volatile=True), Variable(target)) if fast: output = model.fast_forward_BF(data) else: output = model.forward(data) if (task == 'classification'): test_loss += F.nll_loss(output, target, size_average=False).data[0] pred = output.data.max(1, keepdim=True)[1] correct += pred.eq(target.data.view_as(pred)).cpu().sum() else: raise NotImplementedError('The specified task is not supported') if (task == 'classification'): test_loss /= len(data_loader.dataset) print((name + 'Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(test_loss, correct, len(data_loader.dataset), ((100.0 * correct) / len(data_loader.dataset))))) elif (task == 'regression'): test_loss = ((test_loss / 7.0) / len(data_loader.dataset)) print('Average loss: {:.4f}'.format(test_loss))
def compute_error_general_ensemble(model_file_list, data_loader, cuda_on=False, soft_decision=True, stochastic=False, breadth_first=False, fast=False, task='classification', name=''): 'Load an ensemble of models and compute the average prediction. ' model_list = [] map_location = None if (not cuda_on): map_location = 'cpu' for model_file in model_file_list: tree_tmp = torch.load(model_file, map_location=map_location) (tree_struct, tree_modules) = (tree_tmp.tree_struct, tree_tmp.update_tree_modules()) for node in tree_modules: node['router'].stochastic = stochastic node['router'].soft_decision = soft_decision node['router'].dropout_prob = 0.0 for node_meta in tree_struct: if (not ('extended' in node_meta.keys())): node_meta['extended'] = False if (task == 'classification'): model = models.Tree(tree_struct, tree_modules, split=False, cuda_on=cuda_on, soft_decision=soft_decision, breadth_first=breadth_first) if cuda_on: model.cuda() model_list.append(model) for model in model_list: model.eval() test_loss = 0 correct = 0 for (data, target) in data_loader: if cuda_on: (data, target) = (data.cuda(), target.cuda()) (data, target) = (Variable(data, volatile=True), Variable(target)) output = 0.0 for model in model_list: if fast: output += model.fast_forward_BF(data) else: output += model.forward(data) output /= len(model_list) if (task == 'classification'): test_loss += F.nll_loss(output, target, size_average=False).data[0] pred = output.data.max(1, keepdim=True)[1] correct += pred.eq(target.data.view_as(pred)).cpu().sum() elif (task == 'regression'): test_loss += F.mse_loss(output, target, size_average=False).data[0] if (task == 'classification'): test_loss /= len(data_loader.dataset) print((name + 'Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(test_loss, correct, len(data_loader.dataset), ((100.0 * correct) / len(data_loader.dataset))))) elif (task == 'regression'): test_loss = ((test_loss / 7.0) / len(data_loader.dataset)) print('Average loss: {:.4f}'.format(test_loss))
def try_different_inference_methods(model_file, dataset, task='classification', augmentation_on=False, cuda_on=True): ' Try different inference methods and compute accuracy \n ' if (dataset == 'cifar10'): if augmentation_on: transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))]) else: transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) cifar10_test = torchvision.datasets.CIFAR10(root='../../data', train=False, download=True, transform=transform_test) test_loader = torch.utils.data.DataLoader(cifar10_test, batch_size=100, shuffle=False, num_workers=2) elif (dataset == 'mnist'): transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) mnist_test = datasets.MNIST('../../data', train=False, transform=transform_test) test_loader = torch.utils.data.DataLoader(mnist_test, batch_size=100, shuffle=False, num_workers=2) else: raise NotImplementedError('The specified dataset is not supported') start = time.time() compute_error_general(model_file, test_loader, task=task, cuda_on=cuda_on, soft_decision=True, stochastic=False, breadth_first=True, name='soft + BF : ') end = time.time() print('took {} seconds'.format((end - start))) compute_error_general(model_file, test_loader, task=task, cuda_on=cuda_on, soft_decision=False, stochastic=False, breadth_first=True, name='hard + max + BF : ') end = time.time() print('took {} seconds'.format((end - start))) compute_error_general(model_file, test_loader, cuda_on=cuda_on, soft_decision=False, stochastic=True, breadth_first=True, name='hard + stochastic + BF : ') end = time.time() print('took {} seconds'.format((end - start)))
def try_different_inference_methods_ensemble(model_file_list, dataset, task='classification', augmentation_on=False, cuda_on=True): ' Try different inference methods and compute accuracy\n ' if (dataset == 'cifar10'): if augmentation_on: transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))]) else: transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) cifar10_test = torchvision.datasets.CIFAR10(root='../../data', train=False, download=True, transform=transform_test) test_loader = torch.utils.data.DataLoader(cifar10_test, batch_size=100, shuffle=False, num_workers=2) elif (dataset == 'mnist'): transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) mnist_test = datasets.MNIST('../../data', train=False, transform=transform_test) test_loader = torch.utils.data.DataLoader(mnist_test, batch_size=100, shuffle=False, num_workers=2) else: raise NotImplementedError('The specified dataset is not availble') start = time.time() compute_error_general_ensemble(model_file_list, test_loader, task=task, cuda_on=cuda_on, soft_decision=True, stochastic=False, breadth_first=True, name='soft + BF : ') end = time.time() print('took {} seconds'.format((end - start))) compute_error_general_ensemble(model_file_list, test_loader, task=task, cuda_on=cuda_on, soft_decision=False, stochastic=False, breadth_first=True, name='hard + max + BF : ') end = time.time() print('took {} seconds'.format((end - start)))
def get_total_number_of_params(model, print_on=False): tree_struct = model.tree_struct (names, params) = ([], []) for (node_idx, node_meta) in enumerate(tree_struct): for (name, param) in model.named_parameters(): if (((not node_meta['is_leaf']) and ((('.' + str(node_idx)) + '.router') in name)) or ((('.' + str(node_idx)) + '.transform') in name) or (node_meta['is_leaf'] and ((('.' + str(node_idx)) + '.classifier') in name))): names.append(name) params.append(param) if print_on: print('Count the number of parameters below: ') for name in names: print((' ' + name)) return sum((p.numel() for p in params))
def get_number_of_params_path(model, nodes, print_on=False, include_routers=True): (names, params) = ([], []) if include_routers: for (name, param) in model.named_parameters(): if (((('.' + str(nodes[(- 1)])) + '.classifier') in name) or any([((('.' + str(node)) + '.transform') in name) for node in nodes]) or any([((('.' + str(node)) + '.router') in name) for node in nodes[:(- 1)]])): names.append(name) params.append(param) else: for (name, param) in model.named_parameters(): if (((('.' + str(nodes[(- 1)])) + '.classifier') in name) or any([((('.' + str(node)) + '.transform') in name) for node in nodes])): names.append(name) params.append(param) if print_on: print('\nCount the number of parameters below: ') for name in names: print((' ' + name)) return sum((p.numel() for p in params))
def get_number_of_params_summary(model, name='', print_on=True, include_routers=True): total_num = get_total_number_of_params(model) paths_list = model.paths_list num_list = [] for (nodes, _) in paths_list: num = get_number_of_params_path(model, nodes, include_routers=include_routers) num_list.append(num) if print_on: print(('\n' + name)) print('Number of parameters summary:') print(' Total: {} '.format(total_num)) print(' Max per branch: {} '.format(max(num_list))) print(' Min per branch: {} '.format(min(num_list))) print(' Average per branch: {}'.format(((sum(num_list) * 1.0) / len(num_list)))) return (total_num, max(num_list), min(num_list), ((sum(num_list) * 1.0) / len(num_list)))
def round_value(value, binary=False): divisor = (1024.0 if binary else 1000.0) if ((value // (divisor ** 4)) > 0): return (str(round((value / (divisor ** 4)), 2)) + 'T') elif ((value // (divisor ** 3)) > 0): return (str(round((value / (divisor ** 3)), 2)) + 'G') elif ((value // (divisor ** 2)) > 0): return (str(round((value / (divisor ** 2)), 2)) + 'M') elif ((value // divisor) > 0): return (str(round((value / divisor), 2)) + 'K') return str(value)
def set_random_seed(seed, cuda): np.random.seed(seed) torch.manual_seed(seed) random.seed(seed) if cuda: torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
def convert_path_to_npy(*, path='train_64x64', outfile='train_64x64.npy'): assert isinstance(path, str), 'Expected a string input for the path' assert os.path.exists(path), "Input path doesn't exist" files = [f for f in listdir(path) if isfile(join(path, f))] print('Number of valid images is:', len(files)) imgs = [] for i in tqdm(range(len(files))): img = scipy.ndimage.imread(join(path, files[i])) img = img.astype('uint8') assert (np.max(img) <= 255) assert (np.min(img) >= 0) assert (img.dtype == 'uint8') assert isinstance(img, np.ndarray) imgs.append(img) (resolution_x, resolution_y) = (img.shape[0], img.shape[1]) imgs = np.asarray(imgs).astype('uint8') assert (imgs.shape[1:] == (resolution_x, resolution_y, 3)) assert (np.max(imgs) <= 255) assert (np.min(imgs) >= 0) print('Total number of images is:', imgs.shape[0]) print('All assertions done, dumping into npy file') np.save(outfile, imgs)
class Dataset(object): def __init__(self, loc, transform=None, in_mem=True): self.in_mem = in_mem self.dataset = torch.load(loc) if in_mem: self.dataset = self.dataset.float().div(255) self.transform = transform def __len__(self): return self.dataset.size(0) @property def ndim(self): return self.dataset.size(1) def __getitem__(self, index): x = self.dataset[index] if (not self.in_mem): x = x.float().div(255) x = (self.transform(x) if (self.transform is not None) else x) return (x, 0)
class MNIST(object): def __init__(self, dataroot, train=True, transform=None): self.mnist = vdsets.MNIST(dataroot, train=train, download=True, transform=transform) def __len__(self): return len(self.mnist) @property def ndim(self): return 1 def __getitem__(self, index): return self.mnist[index]
class CIFAR10(object): def __init__(self, dataroot, train=True, transform=None): self.cifar10 = vdsets.CIFAR10(dataroot, train=train, download=True, transform=transform) def __len__(self): return len(self.cifar10) @property def ndim(self): return 3 def __getitem__(self, index): return self.cifar10[index]