python_code
stringlengths
0
66.4k
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. from scipy.spatial.transform import Rotation as R import os from glob import glob from tqdm import tqdm import scipy.io as sio import random from PIL import Image import numpy as np import torch from torchvision import transforms preprocess = transforms.Compose([ transforms.Resize((256, 256)), transforms.ToTensor() ]) # class used for obtaining an instance of the dataset for training vision chart prediction # to be passed to a pytorch dataloader # input: # - classes: list of object classes used # - args: set of input parameters from the training file # - set_type: the set type used # - sample_num: the size of the point cloud to be returned in a given batch class mesh_loader_vision(object): def __init__(self, classes, args, set_type='train', sample_num=3000): # initialization of data locations self.args = args self.surf_location = '../data/surfaces/' self.img_location = '../data/images/' self.touch_location = '../data/scene_info/' self.sheet_location = '../data/sheets/' self.sample_num = sample_num self.set_type = set_type self.set_list = np.load('../data/split.npy', allow_pickle='TRUE').item() names = [[f.split('/')[-1], f.split('/')[-2]] for f in glob((f'{self.img_location}/*/*'))] self.names = [] self.classes_names = [[] for _ in classes] np.random.shuffle(names) for n in tqdm(names): if n[1] in classes: if os.path.exists(self.surf_location + n[1] + '/' + n[0] + '.npy'): if os.path.exists(self.touch_location + n[1] + '/' + n[0]): if n[0] + n[1] in self.set_list[self.set_type]: if n[0] +n[1] in self.set_list[self.set_type]: self.names.append(n) self.classes_names[classes.index(n[1])].append(n) print(f'The number of {set_type} set objects found : {len(self.names)}') def __len__(self): return len(self.names) # select the object and grasps for training def get_training_instance(self): # select an object and and a principle grasp randomly class_choice = random.choice(self.classes_names) object_choice = random.choice(class_choice) obj, obj_class = object_choice # select the remaining grasps and shuffle the select grasps num_choices = [0, 1, 2, 3, 4] nums = [] for i in range(self.args.num_grasps): choice = random.choice(num_choices) nums.append(choice) del (num_choices[num_choices.index(choice)]) random.shuffle(nums) return obj, obj_class, nums[-1], nums # select the object and grasps for validating def get_validation_examples(self, index): # select an object and a principle grasp obj, obj_class = self.names[index] orig_num = 0 # select the remaining grasps deterministically nums = [(orig_num + i) % 5 for i in range(self.args.num_grasps)] return obj, obj_class, orig_num, nums # load surface point cloud def get_gt_points(self, obj_class, obj): samples = np.load(self.surf_location +obj_class + '/' + obj + '.npy') if self.args.eval: np.random.seed(0) np.random.shuffle(samples) gt_points = torch.FloatTensor(samples[:self.sample_num]) gt_points *= .5 # scales the models to the size of shape we use gt_points[:, -1] += .6 # this is to make the hand and the shape the right releative sizes return gt_points # load vision signal def get_images(self, obj_class, obj, grasp_number): # load images img_occ = Image.open(f'{self.img_location}/{obj_class}/{obj}/{grasp_number}.png') img_unocc = Image.open(f'{self.img_location}/{obj_class}/{obj}/unoccluded.png') # apply pytorch image preprocessing img_occ = preprocess(img_occ) img_unocc = preprocess(img_unocc) return torch.FloatTensor(img_occ), torch.FloatTensor(img_unocc) # load touch sheet mask indicating toch success def get_touch_info(self, obj_class, obj, grasps): sheets, successful = [], [] # cycle though grasps and load touch sheets for grasp in grasps: sheet_location = self.sheet_location + f'{obj_class}/{obj}/sheets_{grasp}_finger_num.npy' hand_info = np.load(f'{self.touch_location}/{obj_class}/{obj}/{grasp}.npy', allow_pickle=True).item() sheet, success = self.get_touch_sheets(sheet_location, hand_info) sheets.append(sheet) successful += success return torch.cat(sheets), successful # load the touch sheet def get_touch_sheets(self, location, hand_info): sheets = [] successful = [] touches = hand_info['touch_success'] finger_pos = torch.FloatTensor(hand_info['cam_pos']) # cycle through fingers in the grasp for i in range(4): sheet = np.load(location.replace('finger_num', str(i))) # if the touch was unsuccessful if not touches[i] or sheet.shape[0] == 1: sheets.append(finger_pos[i].view(1, 3).expand(25, 3)) # save the finger position instead in every vertex successful.append(False) # binary mask for unsuccessful touch # if the touch was successful else: sheets.append(torch.FloatTensor(sheet)) # save the sheet successful.append(True) # binary mask for successful touch sheets = torch.stack(sheets) return sheets, successful def __getitem__(self, index): if self.set_type == 'train': obj, obj_class, grasp_number, grasps = self.get_training_instance() else: obj, obj_class, grasp_number, grasps = self.get_validation_examples(index) data = {} # meta data data['names'] = obj, obj_class, grasp_number data['class'] = obj_class # load sampled ground truth points data['gt_points'] = self.get_gt_points(obj_class, obj) # load images data['img_occ'], data['img_unocc'] = self.get_images(obj_class, obj, grasp_number) # get touch information data['sheets'], data['successful'] = self.get_touch_info(obj_class, obj, grasps) return data def collate(self, batch): data = {} data['names'] = [item['names'] for item in batch] data['class'] = [item['class'] for item in batch] data['sheets'] = torch.cat([item['sheets'].unsqueeze(0) for item in batch]) data['gt_points'] = torch.cat([item['gt_points'].unsqueeze(0) for item in batch]) data['img_occ'] = torch.cat([item['img_occ'].unsqueeze(0) for item in batch]) data['img_unocc'] = torch.cat([item['img_unocc'].unsqueeze(0) for item in batch]) data['successful'] = [item['successful'] for item in batch] return data # class used for obtaining an instance of the dataset for training touch chart prediction # to be passed to a pytorch dataloader # input: # - classes: list of object classes used # - args: set of input parameters from the training file # - set_type: the set type used # - num: if specified only returns a given grasp number # - all: if True use all objects, regarless of set type # - finger: if specified only returns a given finger number class mesh_loader_touch(object): def __init__(self, classes, args, set_type='train', produce_sheets = False): # initialization of data locations self.args = args self.surf_location = '../data/surfaces/' self.img_location = '../data/images/' self.touch_location = '../data/scene_info/' self.sheet_location = '../data/remake_sheets/' self.set_type = set_type self.set_list = np.load('../data/split.npy', allow_pickle='TRUE').item() self.empty = torch.FloatTensor(np.load('../data/empty_gel.npy')) self.produce_sheets = produce_sheets names = [[f.split('/')[-1], f.split('/')[-2]] for f in glob((f'{self.img_location}/*/*'))] self.names = [] import os for n in tqdm(names): if n[1] in classes: if os.path.exists(self.surf_location + n[1] + '/' + n[0] + '.npy'): if os.path.exists(self.touch_location + n[1] + '/' + n[0]): if self.produce_sheets or (n[0] + n[1]) in self.set_list[self.set_type]: if produce_sheets: for i in range(5): for j in range(4): self.names.append(n + [i, j]) else: for i in range(5): hand_info = np.load(f'{self.touch_location}/{n[1]}/{n[0]}/{i}.npy', allow_pickle=True).item() for j in range(4): if hand_info['touch_success'][j]: self.names.append(n + [i, j]) print(f'The number of {set_type} set objects found : {len(self.names)}') def __len__(self): return len(self.names) def standerdize_point_size(self, points): if points.shape[0] == 0: return torch.zeros((self.args.num_samples, 3)) np.random.shuffle(points) points = torch.FloatTensor(points) while points.shape[0] < self.args.num_samples : points = torch.cat((points, points, points, points)) perm = torch.randperm(points.shape[0]) idx = perm[:self.args.num_samples ] return points[idx] def get_finger_transforms(self, hand_info, finger_num, args): rot = hand_info['cam_rot'][finger_num] rot = R.from_euler('xyz', rot, degrees=False).as_matrix() rot_q = R.from_matrix(rot).as_quat() pos = hand_info['cam_pos'][finger_num] return torch.FloatTensor(rot_q), torch.FloatTensor(rot), torch.FloatTensor(pos) def __getitem__(self, index): obj, obj_class, num, finger_num = self.names[index] # meta data data = {} data['names'] = [obj, num , finger_num] data['class'] = obj_class # hand infomation hand_info = np.load(f'{self.touch_location}/{obj_class}/{obj}/{num}.npy', allow_pickle=True).item() data['rot'], data['rot_M'], data['pos'] = self.get_finger_transforms(hand_info, finger_num, self.args) data['good_touch'] = hand_info['touch_success'] # simulated touch information scene_info = np.load(f'{self.touch_location}/{obj_class}/{obj}/{num}.npy', allow_pickle=True).item() data['depth'] = torch.clamp(torch.FloatTensor(scene_info['depth'][finger_num]).unsqueeze(0), 0, 1) data['sim_touch'] = torch.FloatTensor(np.array(scene_info['gel'][finger_num]) / 255.).permute(2, 0, 1).contiguous().view(3, 100, 100) data['empty'] = torch.FloatTensor(self.empty / 255.).permute(2, 0, 1).contiguous().view(3, 100, 100) # point cloud information data['samples'] = self.standerdize_point_size(scene_info['points'][finger_num]) data['num_samples'] = scene_info['points'][finger_num].shape # where to save sheets data['save_dir'] = f'{self.sheet_location}/{obj_class}/{obj}/sheets_{num}_{finger_num}.npy' return data def collate(self, batch): data = {} data['names'] = [item['names'] for item in batch] data['class'] = [item['class'] for item in batch] data['samples'] = torch.cat([item['samples'].unsqueeze(0) for item in batch]) data['sim_touch'] = torch.cat([item['sim_touch'].unsqueeze(0) for item in batch]) data['empty'] = torch.cat([item['empty'].unsqueeze(0) for item in batch]) data['depth'] = torch.cat([item['depth'].unsqueeze(0) for item in batch]) data['ref'] = {} data['ref']['rot'] = torch.cat([item['rot'].unsqueeze(0) for item in batch]) data['ref']['rot_M'] = torch.cat([item['rot_M'].unsqueeze(0) for item in batch]) data['ref']['pos'] = torch.cat([item['pos'].unsqueeze(0) for item in batch]) data['good_touch'] = [item['good_touch'] for item in batch] data['save_dir'] = [item['save_dir'] for item in batch] data['num_samples'] = [item['num_samples'] for item in batch] return data
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import numpy as np import torch import time import sys sys.path.insert(0, "../") from pytorch3d.loss import chamfer_distance as cuda_cd # loads the initial mesh and stores vertex, face, and adjacency matrix information # input: # - args: arguments from the training file # - obj_name: name of the initial mesh object file fot eh vision charts # output: # - adj_info: the adjacency matrix, and faces for the combination of vision and touch charts # - verts: the set of vertices for the initial vision charts def load_mesh_vision(args, obj_name): # load obj file obj = import_obj(obj_name) verts = np.array(obj.vertices) verts = torch.FloatTensor(verts).cuda() faces = torch.LongTensor(np.array(obj.faces) - 1).cuda() # get adjacency matrix infomation adj_info = adj_init(verts, faces, args) return adj_info, verts # loads object file # involves identifying face and vertex infomation in .obj file # needs to be triangulated to work class import_obj(object): def __init__(self, file): self.vertices = [] self.faces = [] with open(file) as f : for line in f: line = line.replace('//', '/') line = line.replace('\n', '') if line[:2] == "v ": self.vertices.append([float(v) for v in line.split(" ")[1:]]) elif line[0] == "f": self.faces.append([int(s.split('/')[0]) for s in line.split(' ')[1:]]) # normalizes symetric, binary adj matrix such that sum of each row is 1 def normalize_adj(mx): rowsum = mx.sum(1) r_inv = (1. / rowsum).view(-1) r_inv[r_inv != r_inv] = 0. mx = torch.mm(torch.eye(r_inv.shape[0]).to(mx.device) * r_inv, mx) return mx # defines the adjacecny matrix for an object def adj_init(verts, faces, args): # get generic adjacency matrix for vision charts adj = calc_adj(faces) adj_info = {} if args.use_touch: # this combines the adjacency information of touch and vision charts # the output adj matrix has the first k rows corresponding to vision charts, and the last |V| - k # corresponding to touch charts. Similarly the first l faces are correspond to vision charts, and the # remaining correspond to touch charts adj, faces = adj_fuse_touch(verts, faces, adj, args) adj = normalize_adj(adj) adj_info['adj'] = adj adj_info['faces'] = faces return adj_info # combines graph for vision and touch charts to define a fused adjacency matrix # input: # - verts: vertices of the vision charts # - faces: faces of the vision charts # - adj: adjacency matric for the vision charts # - args: arguements from the training file # output: # - adj: adjacency matrix from the combination of touch and vision charts # - faces: combination of vision and touch chart faces def adj_fuse_touch(verts, faces, adj, args): verts = verts.data.cpu().numpy() hash = {} # find vertices which have the same 3D position for e, v in enumerate(verts): if v.tobytes() in hash: hash[v.tobytes()].append(e) else: hash[v.tobytes()] = [e] # load object information for generic touch chart sheet = import_obj('../data/initial_sheet.obj') sheet_verts = torch.FloatTensor(np.array(sheet.vertices)).cuda() sheet_faces = torch.LongTensor(np.array(sheet.faces) - 1).cuda() sheet_adj = calc_adj(sheet_faces) # central vertex for each touch chart that will communicate with all vision charts central_point = 4 central_points = [central_point + (i * sheet_adj.shape[0]) + adj.shape[0] for i in range(4 * args.num_grasps)] # define and fill new adjacency matrix with vision and touch charts new_dim = adj.shape[0] + (4 * args.num_grasps * sheet_adj.shape[0]) new_adj = torch.zeros((new_dim, new_dim)).cuda() new_adj[: adj.shape[0], :adj.shape[0]] = adj.clone() for i in range(4 * args.num_grasps): start = adj.shape[0] + (sheet_adj.shape[0] * i) end = adj.shape[0] + (sheet_adj.shape[0] * (i + 1)) new_adj[start: end, start:end] = sheet_adj.clone() adj = new_adj # define new faces with vision and touch charts all_faces = [faces] for i in range(4 * args.num_grasps): temp_sheet_faces = sheet_faces.clone() + verts.shape[0] temp_sheet_faces += i * sheet_verts.shape[0] all_faces.append(temp_sheet_faces) faces = torch.cat(all_faces) # update adjacency matrix to allow communication between vision and touch charts for key in hash.keys(): cur_verts = hash[key] if len(cur_verts) > 1: for v1 in cur_verts: for v2 in cur_verts: # vertices on the boundary of vision charts can communicate adj[v1, v2] = 1 if args.use_touch: for c in central_points: # touch and vision charts can communicate adj[v1, c] = 1 adj[c, v1] = 1 return adj, faces # computes adjacemcy matrix from face information def calc_adj(faces): v1 = faces[:, 0] v2 = faces[:, 1] v3 = faces[:, 2] num_verts = int(faces.max()) adj = torch.eye(num_verts + 1).to(faces.device) adj[(v1, v2)] = 1 adj[(v1, v3)] = 1 adj[(v2, v1)] = 1 adj[(v2, v3)] = 1 adj[(v3, v1)] = 1 adj[(v3, v2)] = 1 return adj # sample points from a batch of meshes # implemented from: # https://github.com/EdwardSmith1884/GEOMetrics/blob/master/utils.py # MIT License # input: # - verts: vertices of the mesh to sample from # - faces: faces of the mesh to sample from # - num: number of point to sample # output: # - points: points sampled on the surface of the mesh def batch_sample(verts, faces, num=10000): dist_uni = torch.distributions.Uniform(torch.tensor([0.0]).cuda(), torch.tensor([1.0]).cuda()) batch_size = verts.shape[0] # calculate area of each face x1, x2, x3 = torch.split(torch.index_select(verts, 1, faces[:, 0]) - torch.index_select(verts, 1, faces[:, 1]), 1, dim=-1) y1, y2, y3 = torch.split(torch.index_select(verts, 1, faces[:, 1]) - torch.index_select(verts, 1, faces[:, 2]), 1, dim=-1) a = (x2 * y3 - x3 * y2) ** 2 b = (x3 * y1 - x1 * y3) ** 2 c = (x1 * y2 - x2 * y1) ** 2 Areas = torch.sqrt(a + b + c) / 2 Areas = Areas.squeeze(-1) / torch.sum(Areas, dim=1) # percentage of each face w.r.t. full surface area # define distrubtions of relative face surface areas choices = None for A in Areas: if choices is None: choices = torch.multinomial(A, num, True) # list of faces to be sampled from else: choices = torch.cat((choices, torch.multinomial(A, num, True))) # select the faces to be used select_faces = faces[choices].view(verts.shape[0], 3, num) face_arange = verts.shape[1] * torch.arange(0, batch_size).cuda().unsqueeze(-1).expand(batch_size, num) select_faces = select_faces + face_arange.unsqueeze(1) select_faces = select_faces.view(-1, 3) flat_verts = verts.view(-1, 3) # sample one point from each xs = torch.index_select(flat_verts, 0, select_faces[:, 0]) ys = torch.index_select(flat_verts, 0, select_faces[:, 1]) zs = torch.index_select(flat_verts, 0, select_faces[:, 2]) u = torch.sqrt(dist_uni.sample_n(batch_size * num)) v = dist_uni.sample_n(batch_size * num) points = (1 - u) * xs + (u * (1 - v)) * ys + u * v * zs points = points.view(batch_size, num, 3) return points # compute the local chamfer distance metric on the ground truth mesh at different distances away from the touch sites # input: # - samples: point cloud from surface of predicted charts # - batch: current batch information # - losses: the current losses across the test set # output: # - losses: updates losses across the test set # - num_examples: the number of times the losses were updated def calc_local_chamfer(samples, batch, losses): batch_size = samples.shape[0] # a grid of point projected towards the surface of the object, starting from the same position and orientation # as the touch sensor when the touch occurred, but 5 times its size planes = batch['radius'].cuda().view(batch_size, 4, 100, 100, 3) # mask indicating which point hit the surface of the object, ie, tho ones we care about masks = batch['radius_masks'].cuda().view(batch_size, 4, 100, 100) successful = batch['successful'] num_examples = 0 # for every grasps for pred, gt, mask, success in zip(samples, planes, masks, successful): # for every ring size around each touch site for i in range(5): # for every touch for j in range(4): if not success[j]: continue # select the right ring of points, ie 1 x size of sensor ... 5 x size of sensor dim_mask = torch.zeros(mask[j].shape).clone() dim_mask[40 - i * 10: 60 + i * 10, 40 - i * 10: 60 + i * 10] = 1 dim_mask[50 - i * 10: 50 + i * 10, 50 - i * 10: 50 + i * 10] = 0 # select point which are on the objects surface dim_mask[mask[j] == 0] = 0 gt_masked = gt[j][dim_mask == 1] if (gt_masked.shape[0] == 0): continue # compute the local loss between the selected points and the predicted surface loss, _ = cuda_cd(pred_points, gt_points, batch_reduction=None) losses[i] += loss.mean() if i == 0: num_examples += 1. return losses, num_examples # sets up arugments for the pretrained models def pretrained_args(args): if args.pretrained == 'empty': args.use_occluded = False args.use_unoccluded = False args.use_touch = False elif args.pretrained == 'touch': args.num_gcn_layers = 25 args.hidden_gcn_layers = 250 args.use_occluded = False args.use_unoccluded = False args.use_touch = True elif args.pretrained == 'touch_unoccluded': args.num_img_blocks = 4 args.num_img_layers = 3 args.size_img_ker = 5 args.num_gcn_layers = 15 args.hidden_gcn_layers = 200 args.use_occluded = False args.use_unoccluded = True args.use_touch = True elif args.pretrained == 'touch_occluded': args.num_img_blocks = 4 args.num_img_layers = 3 args.size_img_ker = 5 args.num_gcn_layers = 20 args.hidden_gcn_layers = 200 args.use_occluded = True args.use_unoccluded = False args.use_touch = True elif args.pretrained == 'unoccluded': args.num_img_blocks = 5 args.num_img_layers = 3 args.size_img_ker = 5 args.num_gcn_layers = 15 args.hidden_gcn_layers = 150 args.use_occluded = False args.use_unoccluded = True args.use_touch = False elif args.pretrained == 'occluded': args.num_img_blocks = 4 args.num_img_layers = 3 args.size_img_ker = 5 args.num_gcn_layers = 25 args.hidden_gcn_layers = 250 args.use_occluded = True args.use_unoccluded = False args.use_touch = False return args # implemented from: # https://github.com/EdwardSmith1884/GEOMetrics/blob/master/utils.py # MIT License # loads the initial mesh and returns vertex, and face information def load_mesh_touch(obj='386.obj'): obj = import_obj(obj) verts = np.array(obj.vertices) verts = torch.FloatTensor(verts).cuda() faces = torch.LongTensor(np.array(obj.faces) - 1).cuda() return verts, faces # returns the chamfer distance between a mesh and a point cloud # input: # - verts: vertices of the mesh # - faces: faces of the mesh # - gt_points: point cloud to operate over # output: # - cd: computed chamfer distance def chamfer_distance(verts, faces, gt_points, num=1000): batch_size = verts.shape[0] # sample from faces and calculate pairs pred_points = batch_sample(verts, faces, num=num) cd, _ = cuda_cd(pred_points, gt_points, batch_reduction=None) return cd.mean() # implemented from: # https://github.com/EdwardSmith1884/GEOMetrics/blob/master/utils.py # MIT License # compute the edgle lengths of a batch of meshes def batch_calc_edge(verts, faces): # get vertex locations of faces p1 = torch.index_select(verts, 1, faces[:, 0]) p2 = torch.index_select(verts, 1, faces[:, 1]) p3 = torch.index_select(verts, 1, faces[:, 2]) # get edge lengths e1 = p2 - p1 e2 = p3 - p1 e3 = p2 - p3 edge_length = (torch.sum(e1 ** 2, -1).mean() + torch.sum(e2 ** 2, -1).mean() + torch.sum(e3 ** 2, -1).mean()) / 3. return edge_length # returns the chamfer distance between two point clouds # input: # - gt_points: point cloud 1 to operate over # - pred_points: point cloud 2 to operate over # output: # - cd: computed chamfer distance def point_loss(gt_points, pred_points): cd, _ = cuda_cd(pred_points, gt_points, batch_reduction=None) return cd.mean()
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import numpy as np import os from tqdm import tqdm interval = 1300 commands_to_run = [] for i in range(200): commands_to_run += [f'python runner.py --save_director experiments/checkpoint/pretrained/encoder_touch ' f'--start {interval*i } --end {interval*i + interval}'] def call(command): os.system(command) from multiprocessing import Pool pool = Pool(processes=10) pbar = tqdm(pool.imap_unordered(call, commands_to_run), total=len(commands_to_run)) pbar.set_description(f"calling submitit") for _ in pbar: pass
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import os import submitit import argparse import produce_sheets parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=0, help='Random seed.') parser.add_argument('--start', type=int, default=0, help='Random seed.') parser.add_argument('--end', type=int, default=10000000, help='Random seed.') parser.add_argument('--save_directory', type=str, default='experiments/checkpoint/pretrained/encoder_touch', help='Location of the model used to produce sheets') parser.add_argument('--num_samples', type=int, default=4000, help='Number of points in the predicted point cloud.') parser.add_argument('--model_location', type=str, default="../data/initial_sheet.obj") parser.add_argument('--surf_co', type=float, default=9000.) args = parser.parse_args() trainer = produce_sheets.Engine(args) submitit_logs_dir = os.path.join('experiments','sheet_logs_again',str(args.start)) executor = submitit.SlurmExecutor(submitit_logs_dir, max_num_timeout=3) time = 360 executor.update_parameters( num_gpus=1, partition='', cpus_per_task=16, mem=500000, time=time, job_name=str(args.start), signal_delay_s=300, ) executor.submit(trainer)
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import torch.nn as nn import torch import torch.nn.functional as F # implemented from: # https://github.com/MicrosoftLearning/dev290x-v2/blob/master/Mod04/02-Unet/unet_pytorch/model.py # MIT License class DoubleConv(nn.Module): def __init__(self, in_channels, out_channels, mid_channels=None): super().__init__() if not mid_channels: mid_channels = out_channels self.double_conv = nn.Sequential( nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1), nn.BatchNorm2d(mid_channels), nn.ReLU(inplace=True), nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True) ) def forward(self, x): return self.double_conv(x) # implemented from: # https://github.com/MicrosoftLearning/dev290x-v2/blob/master/Mod04/02-Unet/unet_pytorch/model.py # MIT License class Down(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.maxpool_conv = nn.Sequential( nn.MaxPool2d(2), DoubleConv(in_channels, out_channels) ) def forward(self, x): return self.maxpool_conv(x) # implemented from: # https://github.com/MicrosoftLearning/dev290x-v2/blob/master/Mod04/02-Unet/unet_pytorch/model.py # MIT License class Up(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.up = nn.ConvTranspose2d(in_channels , in_channels // 2, kernel_size=2, stride=2) self.conv = DoubleConv(in_channels, out_channels) def forward(self, x1, x2): x1 = self.up(x1) diffY = torch.tensor([x2.size()[2] - x1.size()[2]]) diffX = torch.tensor([x2.size()[3] - x1.size()[3]]) x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2, diffY // 2, diffY - diffY // 2]) x = torch.cat([x2, x1], dim=1) output = self.conv(x) return output # implemented from: # https://github.com/MicrosoftLearning/dev290x-v2/blob/master/Mod04/02-Unet/unet_pytorch/model.py # MIT License class OutConv(nn.Module): def __init__(self, in_channels, out_channels): super(OutConv, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1) def forward(self, x): return self.conv(x) class Encoder(nn.Module): def __init__(self, args, dim = 100): super(Encoder, self).__init__() self.args = args # settings n_channels = 3 n_classes = 1 # downscale the image self.inc = DoubleConv(n_channels, 64) self.down1 = Down(64, 128) self.down2 = Down(128, 256) self.down3 = Down(256, 512) # upscale the image self.down4 = Down(512, 1024) self.up1 = Up(1024, 512) self.up2 = Up(512, 256) self.up3 = Up(256, 128) self.up4 = Up(128, 64) self.outc = OutConv(64, n_classes) # define a plane of the same size, and shape at the touch sensor width = .0218 - 0.00539 y_z = torch.arange(dim).cuda().view(dim, 1).expand(dim, dim).float() y_z = torch.stack((y_z, y_z.permute(1, 0))).permute(1, 2, 0) plane = torch.cat((torch.zeros(dim, dim, 1).cuda(), y_z), dim=-1) self.orig_plane = (plane / float(dim) - .5) * width # update the plane with the predicted depth information def project_depth(self, depths, pos, rot, dim=100): # reshape the plane to have the same position and orientation as the touch sensor when the touch occurred batch_size = depths.shape[0] planes = self.orig_plane.view(1 , -1 , 3).expand(batch_size, -1, 3) planes = torch.bmm(rot, planes.permute(0, 2, 1)).permute(0, 2, 1) planes += pos.view(batch_size, 1, 3) # add the depth in the same direction as the normal of the sensor plane init_camera_vector = torch.FloatTensor((1, 0, 0)).cuda().view(1, 3, 1) .expand(batch_size, 3, 1 ) camera_vector = torch.bmm(rot, init_camera_vector).permute(0, 2, 1) camera_vector = F.normalize(camera_vector, p=2, dim=-1).view(batch_size, 1, 1, 3).expand(batch_size, dim, dim, 3) depth_update = depths.unsqueeze(-1) * camera_vector local_depth = (planes + depth_update.view(batch_size, -1, 3)).view(batch_size, -1, 3) return local_depth def forward(self, gel, depth, ref_frame, empty, producing_sheet = False): # get initial data batch_size = ref_frame['pos'].shape[0] pos = ref_frame['pos'].cuda().view(batch_size, -1) rot_m = ref_frame['rot_M'].cuda().view(-1, 3, 3) # U-Net prediction # downscale the image x1 = self.inc(gel) x2 = self.down1(x1) x3 = self.down2(x2) x4 = self.down3(x3) x5 = self.down4(x4) # upscale the image x = self.up1(x5, x4) x = self.up2(x, x3) x = self.up3(x, x2) x = self.up4(x, x1) pred_depth =(self.outc(x)) # scale the prediction pred_depth = F.sigmoid(pred_depth) * 0.1 # we only want to use the points in the predicted point cloud if they correspond to pixels in the touch signal # which are "different" enough from the an untouched touch signal, otherwise the do not correspond to any # geometry of the object which is deforming the touch sensor's surface. diff = torch.sqrt((((gel.permute(0, 2, 3, 1) - empty.permute(0, 2, 3, 1)).view(batch_size, -1, 3)) **2).sum(dim = -1)) useful_points = diff > 0.001 # project the depth values into 3D points projected_depths = self.project_depth(pred_depth.squeeze(1), pos, rot_m).view(batch_size, -1, 3) pred_points = [] for points, useful in zip(projected_depths, useful_points): # select only useful points orig_points = points.clone() points = points[useful] if points.shape[0] == 0: if producing_sheet: pred_points.append(torch.zeros((self.args.num_samples, 3)).cuda()) continue else: points = orig_points # make the number of points in each element of a batch consistent while points.shape[0] < self.args.num_samples: points = torch.cat((points, points, points, points)) perm = torch.randperm(points.shape[0]) idx = perm[:self.args.num_samples] points = points[idx] pred_points.append(points) pred_points = torch.stack(pred_points) return pred_depth, pred_points
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import models import os import torch import numpy as np import torch.optim as optim from torch.utils.data import DataLoader from tqdm import tqdm import argparse import sys sys.path.insert(0, "../") import utils import data_loaders class Engine(): def __init__(self, args): # set seeds np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) self.classes = ['0001', '0002'] self.args = args self.verts, self.faces = utils.load_mesh_touch(f'../data/initial_sheet.obj') def __call__(self) -> float: self.encoder = models.Encoder(self.args) self.encoder.load_state_dict(torch.load(self.args.save_directory)) self.encoder.cuda() self.encoder.eval() train_data = data_loaders.mesh_loader_touch(self.classes, self.args, produce_sheets=True) train_data.names = train_data.names[self.args.start:self.args.end] train_loader = DataLoader(train_data, batch_size=1, shuffle=False, num_workers=16, collate_fn=train_data.collate) for k, batch in enumerate(tqdm(train_loader, smoothing=0)): # initialize data sim_touch = batch['sim_touch'].cuda() depth = batch['depth'].cuda() ref_frame = batch['ref'] # predict point cloud with torch.no_grad(): pred_depth, sampled_points = self.encoder(sim_touch, depth, ref_frame, empty = batch['empty'].cuda()) # optimize touch chart for points, dir in zip(sampled_points, batch['save_dir']): if os.path.exists(dir): continue directory = dir[:-len(dir.split('/')[-1])] if not os.path.exists(directory): os.makedirs(directory) # if not a successful touch if torch.abs(points).sum() == 0 : np.save(dir, np.zeros(1)) continue # make initial mesh match touch sensor when touch occurred initial = self.verts.clone().unsqueeze(0) pos = ref_frame['pos'].cuda().view(1, -1) rot = ref_frame['rot_M'].cuda().view(1, 3, 3) initial = torch.bmm(rot, initial.permute(0, 2, 1)).permute(0, 2, 1) initial += pos.view(1, 1, 3) initial = initial[0] # set up optimization updates = torch.zeros(self.verts.shape, requires_grad=True, device="cuda") optimizer = optim.Adam([updates], lr=0.003, weight_decay=0) last_improvement = 0 best_loss = 10000 while True: # update optimizer.zero_grad() verts = initial + updates # losses surf_loss = utils.chamfer_distance(verts.unsqueeze(0), self.faces, points.unsqueeze(0), num =self.args.num_samples) edge_lengths = utils.batch_calc_edge(verts.unsqueeze(0), self.faces) loss = self.args.surf_co * surf_loss + 70 * edge_lengths # optimize loss.backward() optimizer.step() # check results if loss < 0.0006: break if best_loss > loss : best_loss = loss best_verts = verts.clone() last_improvement = 0 else: last_improvement += 1 if last_improvement > 50: break np.save(dir, best_verts.data.cpu().numpy()) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=0, help='Random seed.') parser.add_argument('--start', type=int, default=0, help='Random seed.') parser.add_argument('--end', type=int, default=10000000, help='Random seed.') parser.add_argument('--save_directory', type=str, default='experiments/checkpoint/pretrained/encoder_touch', help='Location of the model used to produce sheet') parser.add_argument('--num_samples', type=int, default=4000, help='Number of points in the predicted point cloud.') parser.add_argument('--model_location', type=str, default="../data/initial_sheet.obj", help='Location of inital mesh sheet whcih will be optimized') parser.add_argument('--surf_co', type=float, default=9000.) args = parser.parse_args() trainer = Engine(args) trainer()
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import models from torch.utils.tensorboard import SummaryWriter import torch import numpy as np import torch.optim as optim import os from torch.utils.data import DataLoader from tqdm import tqdm import argparse import sys sys.path.insert(0, "../") import utils import data_loaders class Engine(): def __init__(self, args): # set seeds np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) # set initial data values self.epoch = 0 self.best_loss = 10000 self.args = args self.last_improvement = 0 self.classes = ['0001', '0002'] self.checkpoint_dir = os.path.join('experiments/checkpoint/', args.exp_type, args.exp_id) self.log_dir = f'experiments/results/{self.args.exp_type}/{self.args.exp_id}/' if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) def __call__(self) -> float: self.encoder = models.Encoder(self.args) self.encoder.cuda() params = list(self.encoder.parameters()) self.optimizer = optim.Adam(params, lr=self.args.lr, weight_decay=0) writer = SummaryWriter(os.path.join('experiments/tensorboard/', args.exp_type )) train_loader, valid_loaders = self.get_loaders() if self.args.eval: self.load('') with torch.no_grad(): self.validate(valid_loaders, writer) exit() for epoch in range(self.args.epochs): self.epoch = epoch self.train(train_loader, writer) with torch.no_grad(): self.validate(valid_loaders, writer) self.check_values() def get_loaders(self): # training data train_data = data_loaders.mesh_loader_touch(self.classes, self.args, set_type='train') train_loader = DataLoader(train_data, batch_size=self.args.batch_size, shuffle=True, num_workers=16, collate_fn=train_data.collate) # validation data valid_loaders = [] set_type = 'test' if self.args.eval else 'valid' for c in self.classes: valid_data = data_loaders.mesh_loader_touch(c, self.args, set_type=set_type) valid_loaders.append( DataLoader(valid_data, batch_size=self.args.batch_size, shuffle=False, num_workers=16, collate_fn=valid_data.collate)) return train_loader, valid_loaders def train(self, data, writer): total_loss = 0 iterations = 0 self.encoder.train() for k, batch in enumerate(tqdm(data)): self.optimizer.zero_grad() # initialize data sim_touch = batch['sim_touch'].cuda() depth = batch['depth'].cuda() ref_frame = batch['ref'] gt_points = batch['samples'].cuda() # inference pred_depth, pred_points = self.encoder(sim_touch, depth, ref_frame, empty = batch['empty'].cuda()) # losses loss = point_loss = self.args.loss_coeff * utils.point_loss(pred_points, gt_points) total_loss += point_loss.item() # backprop loss.backward() self.optimizer.step() # log message = f'Train || Epoch: {self.epoch}, loss: {loss.item():.5f} ' message += f'|| best_loss: {self.best_loss :.5f}' tqdm.write(message) iterations += 1. writer.add_scalars('train', {self.args.exp_id: total_loss / iterations}, self.epoch) def validate(self, data, writer): total_loss = 0 self.encoder.eval() # loop through every class for v, valid_loader in enumerate(data): num_examples = 0 class_loss = 0 # loop through every batch for k, batch in enumerate(tqdm(valid_loader)): # initialize data sim_touch = batch['sim_touch'].cuda() depth = batch['depth'].cuda() ref_frame = batch['ref'] gt_points = batch['samples'].cuda() obj_class = batch['class'][0] batch_size = gt_points.shape[0] # inference pred_depth, pred_points = self.encoder( sim_touch, depth, ref_frame, empty = batch['empty'].cuda()) # losses point_loss = self.args.loss_coeff * utils.point_loss(pred_points, gt_points) # log num_examples += float(batch_size) class_loss += point_loss * float(batch_size) # log class_loss = (class_loss / num_examples) message = f'Valid || Epoch: {self.epoch}, class: {obj_class}, loss: {class_loss:.5f}' message += f' || best_loss: {self.best_loss:.5f}' tqdm.write(message) total_loss += (class_loss / float(len(self.classes))) # log print('*******************************************************') print(f'Total validation loss: {total_loss}') print('*******************************************************') if not self.args.eval: writer.add_scalars('valid', {self.args.exp_id: total_loss}, self.epoch) self.current_loss = total_loss def save(self, label): if not os.path.exists(self.checkpoint_dir): os.makedirs(self.checkpoint_dir) torch.save(self.encoder.state_dict(), self.checkpoint_dir + '/encoder_touch' + label) torch.save(self.optimizer.state_dict(), self.checkpoint_dir + '/optim_touch' + label) def check_values(self): if self.best_loss >= self.current_loss: improvement = self.best_loss - self.current_loss self.best_loss = self.current_loss print(f'Saving Model with a {improvement} improvement in point loss') self.save('') self.last_improvement = 0 else: self.last_improvement += 1 if self.last_improvement == self.args.patience: print(f'Over {self.args.patience} steps since last imporvement') print('Exiting now') exit() if self.epoch % 10 == 0: print(f'Saving Model at epoch {self.epoch}') self.save(f'_recent') print('*******************************************************') def load(self, label): self.encoder.load_state_dict(torch.load(self.checkpoint_dir + '/encoder_touch' + label)) self.optimizer.load_state_dict(torch.load(self.checkpoint_dir + '/optim_touch' + label)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=0, help='Setting for the random seed.') parser.add_argument('--epochs', type=int, default=300, help='Number of epochs to use.') parser.add_argument('--lr', type=float, default=0.001, help='Initial learning rate.') parser.add_argument('--eval', action='store_true', default=False, help='Evaluate the trained model on the test set.') parser.add_argument('--batch_size', type=int, default=128, help='Size of the batch.') parser.add_argument('--num_samples', type=int, default=4000, help='Number of points in the predicted point cloud.') parser.add_argument('--patience', type=int, default=70, help='How many epochs without imporvement before training stops.') parser.add_argument('--loss_coeff', type=float, default=9000., help='Coefficient for loss term.') parser.add_argument('--exp_id', type=str, default='test', help='The experiment name') parser.add_argument('--exp_type', type=str, default='test', help='The experiment group') args = parser.parse_args() trainer = Engine(args) trainer()
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. from .chamfer_distance import ChamferDistance
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import torch from torch.utils.cpp_extension import load cd = load(name="cd", sources=["../third_party_code/chamfer_distance.cpp", "../third_party_code/chamfer_distance.cu"]) class ChamferDistanceFunction(torch.autograd.Function): @staticmethod def forward(ctx, xyz1, xyz2): batchsize, n, _ = xyz1.size() _, m, _ = xyz2.size() xyz1 = xyz1.contiguous() xyz2 = xyz2.contiguous() dist1 = torch.zeros(batchsize, n) dist2 = torch.zeros(batchsize, m) idx1 = torch.zeros(batchsize, n, dtype=torch.int) idx2 = torch.zeros(batchsize, m, dtype=torch.int) dist1 = dist1.cuda() dist2 = dist2.cuda() idx1 = idx1.cuda() idx2 = idx2.cuda() cd.forward_cuda(xyz1, xyz2, dist1, dist2, idx1, idx2) return idx1, idx2 class ChamferDistance(torch.nn.Module): def forward(self, xyz1, xyz2): return ChamferDistanceFunction.apply(xyz1, xyz2)
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import numpy as np import os from tqdm import tqdm def call(command): os.system(command) param_namer = {'--seed': 'seed', '--num_gcn_layers': 'ngl', '--hidden_gcn_layers': 'hgl', '--num_img_blocks': 'nib', '--num_img_layers': 'nil', '--num_grasps': 'grasps', '--geo': 'geo'} commands = [] ex_type = 'Comparison' eval = False def add_commands(forced_params, string, params, exp_id_start): for f in forced_params: string += f' {f}' number = [] keys = list(params.keys()) for param_name in keys: number.append(len(params[param_name])) numbers = np.where(np.zeros(number) == 0 ) numbers = np.stack(numbers).transpose() commands = [] for n in numbers : exp_id = exp_id_start command = string for e, k in enumerate(n): param_name = keys[e] param_value = params[param_name][k] command += f' {param_name} {param_value}' exp_id += f'_{param_namer[param_name]}_{param_value}' if eval: command += ' --eval' command += f' --exp_id {exp_id}' commands.append(command) return commands ###################### ###### empty ######### ###################### params = {'--seed': [0,1,2,3,4,5]} exp_id_start = '@empty' string = f'CUDA_VISIBLE_DEVICES=0 python runner.py --exp_type {ex_type}' forced_params = [] commands += add_commands(forced_params, string, params, exp_id_start) ###################### ###### occluded ###### ###################### params = {'--num_gcn_layers': [15, 20, 25], '--hidden_gcn_layers': [150, 200, 250], '--num_img_blocks': [4,5], '--num_img_layers': [3, 5]} exp_id_start = '@occluded' string = f'CUDA_VISIBLE_DEVICES=0 python runner.py --exp_type {ex_type}' forced_params = ['--use_occluded'] commands += add_commands(forced_params, string, params, exp_id_start) ###################### ###### unoccluded #### ###################### params = {'--num_gcn_layers': [15, 20, 25], '--hidden_gcn_layers': [150, 200, 250], '--num_img_blocks': [4,5], '--num_img_layers': [3, 5]} exp_id_start = '@unoccluded' string = f'CUDA_VISIBLE_DEVICES=0 python runner.py --exp_type {ex_type}' forced_params = ['--use_unoccluded'] commands += add_commands(forced_params, string, params, exp_id_start) ######################## #### touch ###### ######################## params = {'--num_gcn_layers': [15, 20, 25], '--hidden_gcn_layers': [150, 200, 250], '--num_grasps': [1, 2, 3, 4, 5]} exp_id_start = '@touch' string = f'CUDA_VISIBLE_DEVICES=0 python runner.py --exp_type {ex_type}' forced_params = ['--use_touch', ] commands += add_commands(forced_params, string, params, exp_id_start) ############################## ##### occluded + touch ####### ############################## params = {'--num_gcn_layers': [15, 20, 25], '--hidden_gcn_layers': [150, 200, 250], '--num_img_blocks': [4,5], '--num_img_layers': [3, 5]} exp_id_start = '@occluded_touch' string = f'CUDA_VISIBLE_DEVICES=0 python runner.py --exp_type {ex_type}' forced_params = ['--use_occluded', '--use_touch'] commands += add_commands(forced_params, string, params, exp_id_start) ############################## ### touch + unoccluded ###### ############################## params = {'--num_gcn_layers': [15, 20, 25], '--hidden_gcn_layers': [150, 200, 250], '--num_img_blocks': [4,5], '--num_img_layers': [3, 5],'--num_grasps': [1, 2, 3, 4, 5] } exp_id_start = '@unoccluded_touch' string = f'CUDA_VISIBLE_DEVICES=0 python runner.py --exp_type {ex_type}' forced_params = ['--use_unoccluded', '--use_touch', ] commands += add_commands(forced_params, string, params, exp_id_start) for i in range(len(commands)): commands[i] += f'_command_{i}@' from multiprocessing import Pool pool = Pool(processes=10) pbar = tqdm(pool.imap_unordered(call, commands), total=len(commands)) pbar.set_description(f"calling submitit") for _ in pbar: pass
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import os import submitit import argparse import recon parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=0, help='Setting for the random seed.') parser.add_argument('--geo', type=int, default=0, help='use_geomtrics') parser.add_argument('--lr', type=float, default=0.0003, help='Initial learning rate.') parser.add_argument('--eval', action='store_true', default=False, help='Evaluate the trained model on the test set.') parser.add_argument('--batch_size', type=int, default=25, help='Size of the batch.') parser.add_argument('--exp_id', type=str, default='Eval', help='The experiment name') parser.add_argument('--exp_type', type=str, default='Test', help='The experiment group') parser.add_argument('--use_occluded', action='store_true', default=False, help='To use the occluded image.') parser.add_argument('--use_unoccluded', action='store_true', default=False, help='To use the unoccluded image.') parser.add_argument('--use_touch', action='store_true', default=False, help='To use the touch information.') parser.add_argument('--patience', type=int, default=70, help='How many epochs without imporvement before training stops.') parser.add_argument('--loss_coeff', type=float, default=9000., help='Coefficient for loss term.') parser.add_argument('--num_img_blocks', type=int, default=6, help='Number of image block in the image encoder.') parser.add_argument('--num_img_layers', type=int, default=3, help='Number of image layer in each blocl in the image encoder.') parser.add_argument('--size_img_ker', type=int, default=5, help='Size of the image kernel in each Image encoder layer') parser.add_argument('--num_gcn_layers', type=int, default=20, help='Number of GCN layer in the mesh deformation network.') parser.add_argument('--hidden_gcn_layers', type=int, default=300, help='Size of the feature vector for each GCN layer in the mesh deformation network.') parser.add_argument('--num_grasps', type=int, default=1, help='Number of grasps in each instance to train with') parser.add_argument('--pretrained', type=str, default='no', help='String indicating which pretrained model to use.', choices=['no', 'touch', 'touch_unoccluded', 'touch_occluded', 'unoccluded', 'occluded']) parser.add_argument('--visualize', action='store_true', default=False) args = parser.parse_args() trainer = recon.Engine(args) submitit_logs_dir = os.path.join('experiments','logs', args.exp_type, args.exp_id ) executor = submitit.SlurmExecutor(submitit_logs_dir, max_num_timeout=3) if args.eval: time = 30 else: time = 60*48 executor.update_parameters( num_gpus=1, partition='', cpus_per_task=16, mem=500000, time=time, job_name=args.exp_id, signal_delay_s=300, ) executor.submit(trainer)
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import torch.nn as nn import torch import numpy as np from torch.nn.parameter import Parameter import torch.nn.functional as F import math # network for making image features for vertex feature vectors class Image_Encoder(nn.Module): def __init__(self, args): super(Image_Encoder, self).__init__() layers = [] cur_size = 6 next_size = 16 for i in range(args.num_img_blocks): layers.append(CNN_layer(cur_size, next_size, args.size_img_ker, stride=2)) cur_size = next_size next_size = next_size * 2 for j in range(args.num_img_layers -1): layers.append(CNN_layer(cur_size, cur_size, args.size_img_ker)) self.args = args self.layers = nn.ModuleList(layers) f = 221.7025 RT = np.array([[-0.0000, -1.0000, 0.0000, -0.0000], [-0.7071, 0.0000, -0.7071, 0.4243], [0.7071, 0.0000, -0.7071, 1.1314]]) K = np.array([[f, 0, 128.], [0, f, 128.], [0, 0, 1]]) self.matrix = torch.FloatTensor(K.dot(RT)).cuda() # implemented from: # https://github.com/EdwardSmith1884/GEOMetrics/blob/master/utils.py # MIT License # defines image features over vertices from vertex positions, and feature mpas from vision def pooling(self, blocks, verts_pos, debug=False): # convert vertex positions to x,y coordinates in the image, scaled to fractions of image dimension ext_verts_pos = torch.cat( (verts_pos, torch.FloatTensor(np.ones([verts_pos.shape[0], verts_pos.shape[1], 1])).cuda()), dim=-1) ext_verts_pos = torch.matmul(ext_verts_pos, self.matrix.permute(1, 0)) xs = ext_verts_pos[:, :, 1] / ext_verts_pos[:, :, 2] / 256. ys = ext_verts_pos[:, :, 0] / ext_verts_pos[:, :, 2] / 256. full_features = None batch_size = verts_pos.shape[0] # check camera project covers the image if debug: dim = 256 xs = (torch.clamp(xs * dim, 0, dim - 1).data.cpu().numpy()).astype(np.uint8) ys = (torch.clamp(ys * dim, 0, dim - 1).data.cpu().numpy()).astype(np.uint8) for ex in range(blocks.shape[0]): img = blocks[ex].permute(1, 2, 0).data.cpu().numpy()[:, :, :3] for x, y in zip(xs[ex], ys[ex]): img[x, y, 0] = 1 img[x, y, 1] = 0 img[x, y, 2] = 0 from PIL import Image Image.fromarray((img * 255).astype(np.uint8)).save('results/temp.png') print('saved') input() for block in blocks: # scale projected vertex points to dimension of current feature map dim = block.shape[-1] cur_xs = torch.clamp(xs * dim, 0, dim - 1) cur_ys = torch.clamp(ys * dim, 0, dim - 1) # https://en.wikipedia.org/wiki/Bilinear_interpolation x1s, y1s, x2s, y2s = torch.floor(cur_xs), torch.floor(cur_ys), torch.ceil(cur_xs), torch.ceil(cur_ys) A = x2s - cur_xs B = cur_xs - x1s G = y2s - cur_ys H = cur_ys - y1s x1s = x1s.type(torch.cuda.LongTensor) y1s = y1s.type(torch.cuda.LongTensor) x2s = x2s.type(torch.cuda.LongTensor) y2s = y2s.type(torch.cuda.LongTensor) # flatten batch of feature maps to make vectorization easier flat_block = block.permute(1, 0, 2, 3).contiguous().view(block.shape[1], -1) block_idx = torch.arange(0, verts_pos.shape[0]).cuda().unsqueeze(-1).expand(batch_size, verts_pos.shape[1]) block_idx = block_idx * dim * dim selection = (block_idx + (x1s * dim) + y1s).view(-1) C = torch.index_select(flat_block, 1, selection) C = C.view(-1, batch_size, verts_pos.shape[1]).permute(1, 0, 2) selection = (block_idx + (x1s * dim) + y2s).view(-1) D = torch.index_select(flat_block, 1, selection) D = D.view(-1, batch_size, verts_pos.shape[1]).permute(1, 0, 2) selection = (block_idx + (x2s * dim) + y1s).view(-1) E = torch.index_select(flat_block, 1, selection) E = E.view(-1, batch_size, verts_pos.shape[1]).permute(1, 0, 2) selection = (block_idx + (x2s * dim) + y2s).view(-1) F = torch.index_select(flat_block, 1, selection) F = F.view(-1, batch_size, verts_pos.shape[1]).permute(1, 0, 2) section1 = A.unsqueeze(1) * C * G.unsqueeze(1) section2 = H.unsqueeze(1) * D * A.unsqueeze(1) section3 = G.unsqueeze(1) * E * B.unsqueeze(1) section4 = B.unsqueeze(1) * F * H.unsqueeze(1) features = (section1 + section2 + section3 + section4) features = features.permute(0, 2, 1) if full_features is None: full_features = features else: full_features = torch.cat((full_features, features), dim=2) return full_features def forward(self, img_occ, img_unocc, cur_vertices): # double size due to legacy decision if self.args.use_unoccluded: x = torch.cat((img_unocc, img_unocc), dim = 1) elif self.args.use_occluded: x = torch.cat((img_occ, img_occ), dim=1) else: x = torch.cat((img_occ, img_unocc), dim=1) features = [] layer_selections = [len(self.layers) - 1 - (i+1)*self.args.num_img_layers for i in range(3)] for e, layer in enumerate(self.layers): if x.shape[-1] < self.args.size_img_ker: break x = layer(x) # collect feature maps if e in layer_selections: features.append(x) features.append(x) # get vertex features from selected feature maps vert_image_features = self.pooling(features, cur_vertices) return vert_image_features # global chart deformation class class Encoder(nn.Module): def __init__(self, adj_info, inital_positions, args): super(Encoder, self).__init__() self.adj_info = adj_info self.initial_positions = inital_positions self.args = args input_size = 3 # used to determine the size of the vertex feature vector if args.use_occluded or args.use_unoccluded: self.img_encoder = Image_Encoder(args).cuda() with torch.no_grad(): input_size += self.img_encoder(torch.zeros(1, 3, 256, 256).cuda(), torch.zeros(1, 3, 256, 256).cuda(), torch.zeros(1, 1, 3).cuda()).shape[-1] if self.args.use_touch: input_size+=1 self.mesh_decoder = GCN(input_size, args).cuda() def forward(self, img_occ, img_unocc, batch): # initial data batch_size = img_occ.shape[0] cur_vertices = self.initial_positions.unsqueeze(0).expand(batch_size, -1, -1) size_vision_charts = cur_vertices.shape[1] # if using touch then append touch chart position to graph definition if self.args.use_touch: sheets = batch['sheets'].cuda().view(batch_size, -1, 3) cur_vertices = torch.cat((cur_vertices,sheets), dim = 1 ) # cycle thorugh deformation for _ in range(3): vertex_features = cur_vertices.clone() # add vision features if self.args.use_occluded or self.args.use_unoccluded: vert_img_features = self.img_encoder(img_occ, img_unocc, cur_vertices) vertex_features = torch.cat((vert_img_features, vertex_features), dim=-1) # add mask for touch charts if self.args.use_touch: vision_chart_mask = torch.ones(batch_size, size_vision_charts, 1).cuda() * 2 # flag corresponding to vision touch_chart_mask = torch.FloatTensor(batch['successful']).cuda().unsqueeze(-1).expand(batch_size, 4 * self.args.num_grasps, 25) touch_chart_mask = touch_chart_mask.contiguous().view(batch_size, -1, 1) mask = torch.cat((vision_chart_mask, touch_chart_mask), dim=1) vertex_features = torch.cat((vertex_features,mask), dim = -1) # deform the vertex positions vertex_positions = self.mesh_decoder(vertex_features, self.adj_info) # avoid deforming the touch chart positions vertex_positions[:, size_vision_charts:] = 0 cur_vertices = cur_vertices + vertex_positions return cur_vertices # implemented from: # https://github.com/tkipf/pygcn/tree/master/pygcn # MIT License # Graph convolutional network for chart deformation class GCN(nn.Module): def __init__(self, input_features, args): super(GCN, self).__init__() self.num_layers = args.num_gcn_layers # define output sizes for each GCN layer hidden_values = [input_features] + [ args.hidden_gcn_layers for k in range(self.num_layers -1)] + [3] # define layers layers = [] for i in range(self.num_layers): layers.append(GCN_layer(hidden_values[i], hidden_values[i+1])) self.layers = nn.ModuleList(layers) def forward(self, vertex_features, adj_info): adj = adj_info['adj'] # iterate through GCN layers x = self.layers[0](vertex_features, adj, F.relu) for i in range(1, self.num_layers-1): x = self.layers[i](x, adj, F.relu) coords = (self.layers[-1](x, adj, lambda x: x)) return coords # CNN layer definition def CNN_layer(f_in, f_out, k, stride = 1): layers = [] layers.append(nn.Conv2d(int(f_in), int(f_out), kernel_size=k, padding=1, stride=stride)) layers.append(nn.BatchNorm2d(int(f_out))) layers.append(nn.ReLU(inplace=True)) return nn.Sequential(*layers) # implemented from: # https://github.com/tkipf/pygcn/tree/master/pygcn # MIT License # Graph convolutional network layer definition class GCN_layer(nn.Module): def __init__(self, in_features, out_features, bias=True): super(GCN_layer, self).__init__() self.weight1 = Parameter(torch.Tensor(1, in_features, out_features)) self.bias = Parameter(torch.Tensor(out_features)) self.reset_parameters() def reset_parameters(self): stdv = 6. / math.sqrt((self.weight1.size(1) + self.weight1.size(0))) stdv *= .3 self.weight1.data.uniform_(-stdv, stdv) self.bias.data.uniform_(-.1, .1) def forward(self, features, adj, activation): # 0N-GCN definition, removes need for resnet layers features = torch.matmul(features, self.weight1) output = torch.matmul(adj, features[:, :, :features.shape[-1] // 3]) output = torch.cat((output, features[:, :, features.shape[-1] // 3:]), dim=-1) output = output + self.bias return activation(output)
#Copyright (c) Facebook, Inc. and its affiliates. #All rights reserved. #This source code is licensed under the license found in the #LICENSE file in the root directory of this source tree. import os import models import numpy as np import torch from torch.utils.data import DataLoader from torch.autograd import Variable import torch.optim as optim from torch.utils.tensorboard import SummaryWriter import tensorflow as tf import tensorboard as tb from tqdm import tqdm import sys sys.path.insert(0, "../") import utils import data_loaders class Engine(): def __init__(self, args): # set seeds np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) # set initial data values self.epoch = 0 self.best_loss = 10000 self.args = args self.last_improvement = 0 self.num_samples = 10000 self.classes = ['0001', '0002'] self.checkpoint_dir = os.path.join('experiments/checkpoint/', args.exp_type, args.exp_id) def __call__(self) -> float: # initial data if self.args.GEOmetrics: self.adj_info, initial_positions = utils.load_mesh_vision(self.args, f'../data/sphere.obj') else: self.adj_info, initial_positions = utils.load_mesh_vision(self.args, f'../data/vision_sheets.obj') self.encoder = models.Encoder(self.adj_info, Variable(initial_positions.cuda()), self.args) self.encoder.cuda() params = list(self.encoder.parameters()) self.optimizer = optim.Adam(params, lr=self.args.lr, weight_decay=0) writer = SummaryWriter(os.path.join('experiments/tensorboard/', self.args.exp_type )) train_loader, valid_loaders = self.get_loaders() if self.args.eval: if self.args.pretrained != 'no': self.load_pretrained() else: self.load('') with torch.no_grad(): self.validate(valid_loaders, writer) exit() # training loop for epoch in range(3000): self.epoch = epoch self.train(train_loader, writer) with torch.no_grad(): self.validate(valid_loaders, writer) self.check_values() def get_loaders(self): train_data = data_loaders.mesh_loader_vision(self.classes, self.args, set_type='train', sample_num=self.num_samples) train_loader = DataLoader(train_data, batch_size=self.args.batch_size, shuffle=True, num_workers=16, collate_fn=train_data.collate) valid_loaders = [] set_type = 'test' if self.args.eval else 'valid' for c in self.classes: valid_data = data_loaders.mesh_loader_vision(c, self.args, set_type=set_type, sample_num=self.num_samples) valid_loaders.append( DataLoader(valid_data, batch_size=self.args.batch_size, shuffle=False, num_workers=16, collate_fn=valid_data.collate)) return train_loader, valid_loaders def train(self, data, writer): total_loss = 0 iterations = 0 self.encoder.train() for k, batch in enumerate(tqdm(data)): self.optimizer.zero_grad() # initialize data img_occ = batch['img_occ'].cuda() img_unocc = batch['img_unocc'].cuda() gt_points = batch['gt_points'].cuda() # inference # self.encoder.img_encoder.pooling(img_unocc, gt_points, debug=True) verts = self.encoder(img_occ, img_unocc, batch) # losses loss = utils.chamfer_distance(verts, self.adj_info['faces'], gt_points, num=self.num_samples) loss = self.args.loss_coeff * loss.mean() # backprop loss.backward() self.optimizer.step() # log message = f'Train || Epoch: {self.epoch}, loss: {loss.item():.2f}, b_ptp: {self.best_loss:.2f}' tqdm.write(message) total_loss += loss.item() iterations += 1. writer.add_scalars('train_loss', {self.args.exp_id : total_loss / iterations}, self.epoch) def validate(self, data, writer): total_loss = 0 # local losses at different distances from the touch sites self.encoder.eval() for v, valid_loader in enumerate(data): num_examples = 0 class_loss = 0 for k, batch in enumerate(tqdm(valid_loader)): # initialize data img_occ = batch['img_occ'].cuda() img_unocc = batch['img_unocc'].cuda() gt_points = batch['gt_points'].cuda() batch_size = img_occ.shape[0] obj_class = batch['class'][0] # model prediction verts = self.encoder(img_occ, img_unocc, batch) # losses loss = utils.chamfer_distance(verts, self.adj_info['faces'], gt_points, num=self.num_samples) loss = self.args.loss_coeff * loss.mean() * batch_size # logs num_examples += float(batch_size) class_loss += loss print_loss = (class_loss / num_examples) message = f'Valid || Epoch: {self.epoch}, class: {obj_class}, f1: {print_loss:.2f}' tqdm.write(message) total_loss += (print_loss / float(len(self.classes))) print('*******************************************************') print(f'Validation Accuracy: {total_loss}') print('*******************************************************') writer.add_scalars('valid_ptp', {self.args.exp_id: total_loss}, self.epoch) self.current_loss = total_loss def save(self, label): if not os.path.exists(self.checkpoint_dir): os.makedirs(self.checkpoint_dir) torch.save(self.encoder.state_dict(), self.checkpoint_dir + '/encoder_vision' + label) torch.save(self.optimizer.state_dict(), self.checkpoint_dir + '/optim_vision' + label) def check_values(self): if self.best_loss >= self.current_loss: improvement = self.best_loss -self.current_loss self.best_loss = self.current_loss print(f'Saving Model with a {improvement} improvement') self.save('') self.last_improvement = 0 else: self.last_improvement += 1 if self.last_improvement == self.args.patience: print(f'Over {self.args.patience} steps since last imporvement') print('Exiting now') exit() if self.epoch % 10 == 0: print(f'Saving Model at epoch {self.epoch}') self.save(f'_recent') print('*******************************************************') def load(self, label): self.encoder.load_state_dict(torch.load(self.checkpoint_dir + '/encoder_vision' + label)) self.optimizer.load_state_dict(torch.load(self.checkpoint_dir + '/optim_vision' + label)) def load_pretrained(self): pretrained_location = 'experiments/checkpoint/pretrained/' + self.args.pretrained self.encoder.load_state_dict(torch.load(pretrained_location)) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=0, help='Setting for the random seed.') parser.add_argument('--GEOmetrics', type=int, default=0, help='use GEOMemtrics setup instead') parser.add_argument('--lr', type=float, default=0.0003, help='Initial learning rate.') parser.add_argument('--eval', action='store_true', default=False, help='Evaluate the trained model on the test set.') parser.add_argument('--batch_size', type=int, default=16, help='Size of the batch.') parser.add_argument('--exp_id', type=str, default='Eval', help='The experiment name') parser.add_argument('--exp_type', type=str, default='Test', help='The experiment group') parser.add_argument('--use_occluded', action='store_true', default=False, help='To use the occluded image.') parser.add_argument('--use_unoccluded', action='store_true', default=False, help='To use the unoccluded image.') parser.add_argument('--use_touch', action='store_true', default=False, help='To use the touch information.') parser.add_argument('--patience', type=int, default=30, help='How many epochs without imporvement before training stops.') parser.add_argument('--loss_coeff', type=float, default=9000., help='Coefficient for loss term.') parser.add_argument('--num_img_blocks', type=int, default=6, help='Number of image block in the image encoder.') parser.add_argument('--num_img_layers', type=int, default=3, help='Number of image layer in each blocl in the image encoder.') parser.add_argument('--size_img_ker', type=int, default=5, help='Size of the image kernel in each Image encoder layer') parser.add_argument('--num_gcn_layers', type=int, default=20, help='Number of GCN layer in the mesh deformation network.') parser.add_argument('--hidden_gcn_layers', type=int, default=300, help='Size of the feature vector for each GCN layer in the mesh deformation network.') parser.add_argument('--num_grasps', type=int, default=1, help='Number of grasps in each instance to train with') parser.add_argument('--pretrained', type=str, default='no', help='String indicating which pretrained model to use.', choices=['no', 'empty', 'touch', 'touch_unoccluded', 'touch_occluded', 'unoccluded', 'occluded']) args = parser.parse_args() # update args for pretrained models args = utils.pretrained_args(args) trainer = Engine(args) trainer()
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import distutils.command.clean import os import shutil import subprocess from pathlib import Path from setuptools import find_packages, setup cwd = os.path.dirname(os.path.abspath(__file__)) version_txt = os.path.join(cwd, "version.txt") with open(version_txt, "r") as f: version = f.readline().strip() ROOT_DIR = Path(__file__).parent.resolve() try: sha = ( subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=cwd) .decode("ascii") .strip() ) except Exception: sha = "Unknown" package_name = "rlhive" if os.getenv("BUILD_VERSION"): version = os.getenv("BUILD_VERSION") elif sha != "Unknown": version += "+" + sha[:7] def write_version_file(): version_path = os.path.join(cwd, "rlhive", "version.py") with open(version_path, "w") as f: f.write("__version__ = '{}'\n".format(version)) f.write("git_version = {}\n".format(repr(sha))) def _get_pytorch_version(): # if "PYTORCH_VERSION" in os.environ: # return f"torch=={os.environ['PYTORCH_VERSION']}" return "torch" def _get_packages(): exclude = [ "build*", "test*", # "rlhive.csrc*", # "third_party*", # "tools*", ] return find_packages(exclude=exclude) ROOT_DIR = Path(__file__).parent.resolve() class clean(distutils.command.clean.clean): def run(self): # Run default behavior first distutils.command.clean.clean.run(self) # Remove rlhive extension for path in (ROOT_DIR / "rlhive").glob("**/*.so"): print(f"removing '{path}'") path.unlink() # Remove build directory build_dirs = [ ROOT_DIR / "build", ] for path in build_dirs: if path.exists(): print(f"removing '{path}' (and everything under it)") shutil.rmtree(str(path), ignore_errors=True) def _check_robohive(): import importlib import sys name = "robohive" spam_loader = importlib.find_loader(name) found = spam_loader is not None if name in sys.modules: print(f"{name!r} already in sys.modules") # elif (spec := importlib.util.find_spec(name)) is not None: elif found: print(f"{name!r} is importable") else: raise ImportError( f"can't find {name!r}: check README.md for " f"install instructions" ) def _main(): pytorch_package_dep = _get_pytorch_version() print("-- PyTorch dependency:", pytorch_package_dep) # branch = _run_cmd(["git", "rev-parse", "--abbrev-ref", "HEAD"]) # tag = _run_cmd(["git", "describe", "--tags", "--exact-match", "@"]) this_directory = Path(__file__).parent long_description = (this_directory / "README.md").read_text() # install robohive locally # subprocess.run( # [ # "git", # "clone", # "-c", # "submodule.robohive/sims/neuromuscular_sim.update=none", # "--branch", # "non-local-install", # "--recursive", # "https://github.com/vikashplus/robohive.git", # "third_party/robohive", # ] # ) # subprocess.run( # [ # "git", # "clone", # "--branch", # "main", # "https://github.com/pytorch/rl.git", # "third_party/rl", # ] # ) # mj_env_path = os.path.join(os.getcwd(), "third_party", "robohive#egg=robohive") # rl_path = os.path.join(os.getcwd(), "third_party", "rl#egg=torchrl") setup( # Metadata name="rlhive", version=version, author="rlhive contributors", author_email="[email protected]", url="https://github.com/fairinternal/rlhive", long_description=long_description, long_description_content_type="text/markdown", license="BSD", # Package info packages=find_packages(exclude=("test", "tutorials", "third_party")), # ext_modules=get_extensions(), # cmdclass={ # "build_ext": BuildExtension.with_options(no_python_abi_suffix=True), # "clean": clean, # }, install_requires=[ pytorch_package_dep, # "torchrl @ git+ssh://[email protected]/pytorch/rl@main#egg=torchrl", # f"torchrl @ file://{rl_path}", "torchrl", "gym==0.13", # "robohive", # f"robohive @ file://{mj_env_path}", "numpy", "packaging", "cloudpickle", "hydra-core", "dm_control", ], zip_safe=False, dependency_links=[ # location to your egg file ], extra_requires={ "tests": ["pytest", "pyyaml", "pytest-instafail"], }, ) if __name__ == "__main__": write_version_file() print("Building wheel {}-{}".format(package_name, version)) print(f"BUILD_VERSION is {os.getenv('BUILD_VERSION')}") # _check_robohive() _main()
import robohive import torchrl from rlhive import RoboHiveEnv
import argparse import pytest import torch from rlhive.rl_envs import RoboHiveEnv from torchrl.envs import ( CatTensors, EnvCreator, ParallelEnv, R3MTransform, TransformedEnv, ) from torchrl.envs.utils import check_env_specs def test_state_env(): pass def test_pixel_env(): pass @pytest.mark.parametrize( "env_name", [ "visual_franka_slide_random-v3", "visual_franka_slide_close-v3", "visual_franka_slide_open-v3", "visual_franka_micro_random-v3", "visual_franka_micro_close-v3", "visual_franka_micro_open-v3", "visual_kitchen_knob1_off-v3", "visual_kitchen_knob1_on-v3", "visual_kitchen_knob2_off-v3", "visual_kitchen_knob2_on-v3", "visual_kitchen_knob3_off-v3", "visual_kitchen_knob3_on-v3", "visual_kitchen_knob4_off-v3", "visual_kitchen_knob4_on-v3", "visual_kitchen_light_off-v3", "visual_kitchen_light_on-v3", "visual_kitchen_sdoor_close-v3", "visual_kitchen_sdoor_open-v3", "visual_kitchen_ldoor_close-v3", "visual_kitchen_ldoor_open-v3", "visual_kitchen_rdoor_close-v3", "visual_kitchen_rdoor_open-v3", "visual_kitchen_micro_close-v3", "visual_kitchen_micro_open-v3", "visual_kitchen_close-v3", ], ) def test_mixed_env(env_name): base_env = RoboHiveEnv( env_name, ) assert base_env.from_pixels env = TransformedEnv( base_env, CatTensors( [key for key in base_env.observation_spec.keys() if "pixels" not in key], "observation", ), ) # reset tensordict = env.reset() assert {"done", "observation", "pixels"} == set(tensordict.keys()) assert tensordict["pixels"].shape[0] == 2 # step env.rand_step(tensordict) assert { "reward", "done", "observation", "pixels", "action", ("next", "observation"), ("next", "pixels"), "next", } == set(tensordict.keys(True)) # rollout tensordict = env.rollout(10) assert { "reward", "done", "observation", "pixels", "action", ("next", "observation"), ("next", "pixels"), "next", } == set(tensordict.keys(True)) assert tensordict.shape == torch.Size([10]) env.close() @pytest.mark.parametrize( "env_name", [ "visual_franka_slide_random-v3", "visual_franka_slide_close-v3", "visual_franka_slide_open-v3", "visual_franka_micro_random-v3", "visual_franka_micro_close-v3", "visual_franka_micro_open-v3", "visual_kitchen_knob1_off-v3", "visual_kitchen_knob1_on-v3", "visual_kitchen_knob2_off-v3", "visual_kitchen_knob2_on-v3", "visual_kitchen_knob3_off-v3", "visual_kitchen_knob3_on-v3", "visual_kitchen_knob4_off-v3", "visual_kitchen_knob4_on-v3", "visual_kitchen_light_off-v3", "visual_kitchen_light_on-v3", "visual_kitchen_sdoor_close-v3", "visual_kitchen_sdoor_open-v3", "visual_kitchen_ldoor_close-v3", "visual_kitchen_ldoor_open-v3", "visual_kitchen_rdoor_close-v3", "visual_kitchen_rdoor_open-v3", "visual_kitchen_micro_close-v3", "visual_kitchen_micro_open-v3", "visual_kitchen_close-v3", ], ) def test_specs(env_name): base_env = RoboHiveEnv( env_name, ) check_env_specs(base_env) env = TransformedEnv( base_env, CatTensors( [key for key in base_env.observation_spec.keys() if "pixels" not in key], "observation", ), ) check_env_specs(env) @pytest.mark.parametrize( "env_name", [ "visual_franka_slide_random-v3", "visual_franka_slide_close-v3", "visual_franka_slide_open-v3", "visual_franka_micro_random-v3", "visual_franka_micro_close-v3", "visual_franka_micro_open-v3", "visual_kitchen_knob1_off-v3", "visual_kitchen_knob1_on-v3", "visual_kitchen_knob2_off-v3", "visual_kitchen_knob2_on-v3", "visual_kitchen_knob3_off-v3", "visual_kitchen_knob3_on-v3", "visual_kitchen_knob4_off-v3", "visual_kitchen_knob4_on-v3", "visual_kitchen_light_off-v3", "visual_kitchen_light_on-v3", "visual_kitchen_sdoor_close-v3", "visual_kitchen_sdoor_open-v3", "visual_kitchen_ldoor_close-v3", "visual_kitchen_ldoor_open-v3", "visual_kitchen_rdoor_close-v3", "visual_kitchen_rdoor_open-v3", "visual_kitchen_micro_close-v3", "visual_kitchen_micro_open-v3", "visual_kitchen_close-v3", ], ) def test_parallel(env_name): def make_env(): base_env = RoboHiveEnv( env_name, ) check_env_specs(base_env) env = TransformedEnv( base_env, CatTensors( [ key for key in base_env.observation_spec.keys() if "pixels" not in key ], "observation", ), ) return env env = ParallelEnv(3, make_env) env.reset() env.rollout(3) @pytest.mark.parametrize("parallel", [False, True]) def test_env_render_native(parallel): if not parallel: env = RoboHiveEnv(env_name="FrankaReachRandom_v2d-v0") else: env = ParallelEnv(3, lambda: RoboHiveEnv(env_name="FrankaReachRandom_v2d-v0")) td = env.reset() assert set(td.keys(True)) == { "done", "observation", "pixels", } td = env.rand_step(td) assert set(td.keys(True)) == { "done", "next", ("next", "pixels"), "pixels", "observation", ("next", "observation"), "reward", "action", } td = env.rollout(50) if not parallel: assert td.shape == torch.Size([50]) else: assert td.shape == torch.Size([3, 50]) assert set(td.keys(True)) == { "done", "next", ("next", "pixels"), "pixels", "observation", ("next", "observation"), "reward", "action", } env.close() @pytest.mark.parametrize( "parallel,env_creator", [[True, True], [True, False], [False, True]] ) def test_env_r3m_native(parallel, env_creator): if not parallel: base_env = RoboHiveEnv(env_name="FrankaReachRandom_v2d-v0") else: if env_creator: env_creator = EnvCreator( lambda: RoboHiveEnv(env_name="FrankaReachRandom_v2d-v0") ) else: env_creator = lambda: RoboHiveEnv(env_name="FrankaReachRandom_v2d-v0") base_env = ParallelEnv(3, env_creator) env = TransformedEnv( base_env, R3MTransform( "resnet18", ["pixels"], ["pixels_embed"], ), ) td = env.reset() _ = env.rand_step(td) td = env.rollout(50) if parallel: assert td.shape == torch.Size([3, 50]) else: assert td.shape == torch.Size([50]) env.close() if __name__ == "__main__": args, unknown = argparse.ArgumentParser().parse_known_args() pytest.main([__file__, "--capture", "no", "--exitfirst"] + unknown)
import torch def get_available_devices(): devices = [torch.device("cpu")] n_cuda = torch.cuda.device_count() if n_cuda > 0: for i in range(n_cuda): devices += [torch.device(f"cuda:{i}")] return devices
import argparse import pytest import torch from omegaconf import OmegaConf from rlhive.sim_algos.helpers import EnvConfig from rlhive.sim_algos.run import make_env_constructor from utils import get_available_devices @pytest.mark.parametrize("device", get_available_devices()) def test_make_r3menv(device): cfg = EnvConfig # hacky way of create a config that can be shared across processes cfg = OmegaConf.create(OmegaConf.to_yaml(cfg)) cfg.env_name = "FrankaReachRandom_v2d-v0" cfg.r3m = "resnet50" cfg.collector_devices = str(device) cfg.norm_stats = False cfg.env_per_collector = 2 cfg.pin_memory = False cfg.batch_transform = True single_env_constructor, multi_env_constructor = make_env_constructor(cfg) env = single_env_constructor() print(env) td = env.reset() assert {"done", "observation_vector"} == set(td.keys()) td = env.rollout(10) assert { "action", "done", ( "next", "observation_vector", ), "next", "observation_vector", "reward", } == set(td.keys()) assert td.shape == torch.Size([10]) env = multi_env_constructor print(env) td = env.reset() assert {"done", "observation_vector"} == set(td.keys()) td = env.rollout(10) assert { "action", "done", ( "next", "observation_vector", ), "next", "observation_vector", "reward", } == set(td.keys()) assert td.shape == torch.Size([2, 10]) env.close() if __name__ == "__main__": args, unknown = argparse.ArgumentParser().parse_known_args() pytest.main([__file__, "--capture", "no", "--exitfirst"] + unknown)
''' Use this script to comapare multiple results \n Usage: python viz_resulyts.py -j expdir1_group0 expdir2_group0 -j expdir3_group1 expdir4_group1 -k "key1" "key2"... ''' from vtils.plotting import simple_plot import argparse from scipy import signal import pandas import glob def get_files(search_path, file_name): search_path = search_path[:-1] if search_path.endswith('/') else search_path search_path = search_path+"*/**/"+file_name filenames = glob.glob(search_path, recursive=True) assert (len(filenames) > 0), "No file found at: {}".format(search_path) return filenames # Another example, Python 3.5+ def get_files_p35(search_path, file_name): from pathlib import Path filenames = [] for path in Path(search_path).rglob(file_name): filenames.append(path) return filenames def get_log(filename, format="csv"): try: if format=="csv": data = pandas.read_csv(filename) elif format=="json": data = pandas.read_json(filename) except Exception as e: print("WARNING: Can't read %s." % filename) quit() return data def smooth_data(y, window_length=101, polyorder=3): window_length = min(int(len(y) / 2), window_length) # set maximum valid window length # if window not off if window_length % 2 == 0: window_length = window_length + 1 try: return signal.savgol_filter(y, window_length, polyorder) except Exception as e: return y # nans # MAIN ========================================================= def main(): # Parse arguments parser = argparse.ArgumentParser() parser.add_argument( '-j', '--job', required=True, action='append', nargs='?', help='job group') parser.add_argument( '-lf', '--log_file', type=str, default="log.csv", help='name of log file (with extension)') parser.add_argument( '-cf', '--config_file', type=str, default="job_config.json", help='name of config file (with extension)') parser.add_argument( '-t', '--title', type=str, default=None, help='Title of the plot') parser.add_argument( '-l', '--label', action='append', nargs='?', help='job group label') parser.add_argument( '-s', '--smooth', type=int, default=21, help='window for smoothing') parser.add_argument( '-y', '--ykeys', nargs='+', default=["eval_score", 'norm_score'], help='yKeys to plot') parser.add_argument( '-x', '--xkey', default="total_num_samples", help='xKey to plot') parser.add_argument( '-i', '--index', type=int, default=-4, help='index in log filename to use as labels') args = parser.parse_args() # scan labels if args.label is not None: assert (len(args.job) == len(args.label)), "The number of labels has to be same as the number of jobs" else: args.label = [''] * len(args.job) # for all the algo jobs for ialgo, algo_dir in enumerate(args.job): print("algo> "+algo_dir) envs_dirs = glob.glob(algo_dir+"/*/") # for all envs inside the algo nenv = len(envs_dirs) for ienv, env_dir in enumerate(sorted(envs_dirs)): print("env>> "+env_dir) run_dirs = glob.glob(env_dir+"/*/") # all the seeds/ variations within the env for irun, run_dir in enumerate(sorted(run_dirs)): print("run> "+run_dir) title = run_dir.split('/')[3] title = title[:title.find('-v')] # for log_file in get_files(env_dir, args.file): log_file = get_files(run_dir, args.log_file) log = get_log(filename=log_file[0], format="csv") # validate keys for key in [args.xkey]+args.ykeys: assert key in log.keys(), "{} not present in available keys {}".format(key, log.keys()) nykeys = len(args.ykeys) for iykey, ykey in enumerate(sorted(args.ykeys)): simple_plot.plot(xdata=log[args.xkey]/1e6, ydata=smooth_data(log[ykey], args.smooth), legend='job_name', subplot_id=(nenv, nykeys, nykeys*ienv+iykey+1), xaxislabel=args.xkey+'(M)', plot_name=title, yaxislabel=ykey, fig_size=(4*nykeys, 4*nenv), fig_name='SAC performance' ) # simple_plot.show_plot() simple_plot.save_plot(args.job[0]+'RS-SAC.pdf') if __name__ == '__main__': main()
''' Use this script to comapare multiple results \n Usage: python agents/NPG/plot_all_npg.py -j agents/v0.1/kitchen/NPG/outputs_kitchenJ5c_3.8/ -j agents/v0.1/kitchen/NPG/outputs_kitchenJ5d_3.9/ -j /Users/vikashplus/Projects/mj_envs/kitchen/outputs_kitchenJ8a/ -l 'v0.1(fixed_init)' -l 'v0.1(random_init)' -l 'v0.2(random_init)' -pt True ''' from vtils.plotting import simple_plot import argparse from scipy import signal import pandas import glob import numpy as np import os def get_files(search_path, file_name): search_path = search_path[:-1] if search_path.endswith('/') else search_path search_path = search_path+"*/**/"+file_name filenames = glob.glob(search_path, recursive=True) assert (len(filenames) > 0), "No file found at: {}".format(search_path) return filenames # Another example, Python 3.5+ def get_files_p35(search_path, file_name): from pathlib import Path filenames = [] for path in Path(search_path).rglob(file_name): filenames.append(path) return filenames def get_log(filename, format="csv"): try: if format=="csv": data = pandas.read_csv(filename) elif format=="json": data = pandas.read_json(filename) except Exception as e: print("WARNING: Can't read %s." % filename) quit() return data def smooth_data(y, window_length=101, polyorder=3): window_length = min(int(len(y) / 2), window_length) # set maximum valid window length # if window not off if window_length % 2 == 0: window_length = window_length + 1 try: return signal.savgol_filter(y, window_length, polyorder) except Exception as e: return y # nans # MAIN ========================================================= def main(): # Parse arguments parser = argparse.ArgumentParser() parser.add_argument( '-j', '--job', required=True, action='append', nargs='?', help='job group') parser.add_argument( '-lf', '--run_log', type=str, default="log.csv", help='name of log file (with extension)') parser.add_argument( '-cf', '--config_file', type=str, default="job_config.json", help='name of config file (with extension)') parser.add_argument( '-t', '--title', type=str, default=None, help='Title of the plot') parser.add_argument( '-l', '--label', action='append', nargs='?', help='job group label') parser.add_argument( '-s', '--smooth', type=int, default=21, help='window for smoothing') parser.add_argument( '-y', '--ykeys', nargs='+', default=['success_percentage', 'rwd_sparse', 'rwd_dense'], help='yKeys to plot') parser.add_argument( '-x', '--xkey', default="num_samples", help='xKey to plot') parser.add_argument( '-ei', '--env_index', type=int, default=-2, help='index in log filename to use as labels') parser.add_argument( '-pt', '--plot_train', type=bool, default=False, help='plot train perf') parser.add_argument( '-od', '--output_dir', type=str, default=None, help='Save outputs here') args = parser.parse_args() # init nykeys = len(args.ykeys) njob = len(args.job) nenv = -1 env_labels = [] # scan labels if args.label is not None: assert (njob == len(args.label)), "The number of labels has to be same as the number of jobs" else: args.label = [''] * njob # for all the jobs for ijob, job_dir in enumerate(args.job): print("Job> "+job_dir) envs_dirs = glob.glob(job_dir+"/*/") if nenv ==-1: nenv = len(envs_dirs) else: assert nenv == len(envs_dirs), f"Number of envs changed {envs_dirs}" for env_dir in sorted(envs_dirs): env_labels.append(env_dir.split('/')[args.env_index]) # for all envs inside the exp env_means = [] env_stds = [] for ienv, env_dir in enumerate(sorted(envs_dirs)): print(" env> "+env_dir) # all the seeds/ variations runs within the env yruns = [] xruns = [] # known bug: Logs will different lengths will cause a bug. Its hacked via using [:len(xdata)] for irun, run_log in enumerate(sorted(get_files(env_dir, args.run_log))): print(" run> "+run_log, flush=True) log = get_log(filename=run_log, format="csv") # validate keys for key in [args.xkey]+args.ykeys: assert key in log.keys(), "{} not present in available keys {}".format(key, log.keys()) if 'sample' in args.xkey: #special keys xdata = np.cumsum(log[args.xkey])/1e6 plot_xkey = args.xkey+"(M)" else: xdata = log[args.xkey] plot_xkey = args.xkey yruns.append(log[args.ykeys]) # print(xdata.shape, log[args.ykeys].shape) del log # stats over keys yruns = pandas.concat(yruns) yruns_stacked = yruns.groupby(yruns.index) yruns_mean = yruns_stacked.mean() yruns_min = yruns_stacked.min() yruns_max = yruns_stacked.max() yruns_std = yruns_stacked.std() # stats over jobs env_means.append(yruns_mean.tail(1)) env_stds.append(yruns_std.tail(1)) if args.plot_train: for iykey, ykey in enumerate(sorted(args.ykeys)): h_figp,_,_= simple_plot.plot(xdata=xdata, ydata=smooth_data(yruns_mean[ykey][:len(xdata)], args.smooth), errmin=yruns_min[ykey][:len(xdata)], errmax=yruns_max[ykey][:len(xdata)], legend=args.label[ijob], subplot_id=(nenv, nykeys, nykeys*ienv+iykey+1), xaxislabel=plot_xkey, plot_name=env_labels[ienv], yaxislabel=ykey, fig_size=(4*nykeys, 3*nenv), fig_name='NPG performance', ) env_means = pandas.concat(env_means) env_stds = pandas.concat(env_stds) width = 1/(njob+1) for iykey, ykey in enumerate(sorted(args.ykeys)): h_figb, h_axisb, h_bar = simple_plot.bar( xdata=np.arange(nenv)+width*ijob, ydata=env_means[ykey], errdata=env_stds[ykey], width=width, subplot_id=(nykeys, 1, iykey+1), fig_size=(2+0.2*nenv, 4*nykeys), fig_name="Env perfs", yaxislabel=ykey, legend=args.label[ijob], xticklabels=env_labels[:nenv], # plot_name="Performance using 5M samples" ) args.output_dir = args.job[-1] if args.output_dir == None else args.output_dir if args.plot_train: simple_plot.save_plot(os.path.join(args.output_dir, 'TrainPerf-NPG.pdf'), h_figp) simple_plot.save_plot(os.path.join(args.output_dir,'FinalPerf-NPG.pdf'), h_figb) if __name__ == '__main__': main()
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from tensordict.tensordict import make_tensordict, TensorDictBase from torchrl.data import BoundedTensorSpec, CompositeSpec, UnboundedContinuousTensorSpec from torchrl.envs.libs.gym import _gym_to_torchrl_spec_transform, _has_gym, GymEnv from torchrl.envs.transforms import CatTensors, Compose, R3MTransform, TransformedEnv from torchrl.envs.utils import make_composite_from_td from torchrl.trainers.helpers.envs import LIBS if _has_gym: import gym class RoboHiveEnv(GymEnv): # info_keys = ["time", "rwd_dense", "rwd_sparse", "solved"] def _build_env( self, env_name: str, from_pixels: bool = False, pixels_only: bool = False, **kwargs, ) -> "gym.core.Env": self.pixels_only = pixels_only try: render_device = int(str(self.device)[-1]) except ValueError: render_device = 0 print(f"rendering device: {render_device}, device is {self.device}") if not _has_gym: raise RuntimeError( f"gym not found, unable to create {env_name}. " f"Consider downloading and installing dm_control from" f" {self.git_url}" ) try: env = self.lib.make( env_name, frameskip=self.frame_skip, device_id=render_device, return_dict=True, **kwargs, ) self.wrapper_frame_skip = 1 from_pixels = bool(len(env.visual_keys)) except TypeError as err: if "unexpected keyword argument 'frameskip" not in str(err): raise TypeError(err) kwargs.pop("framek_skip") env = self.lib.make( env_name, return_dict=True, device_id=render_device, **kwargs ) self.wrapper_frame_skip = self.frame_skip self.from_pixels = from_pixels self.render_device = render_device self.info_dict_reader = self.read_info return env def _make_specs(self, env: "gym.Env") -> None: if self.from_pixels: num_cams = len(env.visual_keys) # n_pix = 224 * 224 * 3 * num_cams # env.observation_space = gym.spaces.Box( # -8 * np.ones(env.obs_dim - n_pix), # 8 * np.ones(env.obs_dim - n_pix), # dtype=np.float32, # ) self.action_spec = _gym_to_torchrl_spec_transform( env.action_space, device=self.device ) observation_spec = _gym_to_torchrl_spec_transform( env.observation_space, device=self.device, ) if not isinstance(observation_spec, CompositeSpec): observation_spec = CompositeSpec(observation=observation_spec) self.observation_spec = observation_spec if self.from_pixels: self.observation_spec["pixels"] = BoundedTensorSpec( torch.zeros( num_cams, 224, # working with 640 224, # working with 480 3, device=self.device, dtype=torch.uint8, ), 255 * torch.ones( num_cams, 224, 224, 3, device=self.device, dtype=torch.uint8, ), torch.Size(torch.Size([num_cams, 224, 224, 3])), dtype=torch.uint8, device=self.device, ) self.reward_spec = UnboundedContinuousTensorSpec( device=self.device, ) # default rollout = self.rollout(2).get("next").exclude("done", "reward")[0] self.observation_spec.update(make_composite_from_td(rollout)) def set_from_pixels(self, from_pixels: bool) -> None: """Sets the from_pixels attribute to an existing environment. Args: from_pixels (bool): new value for the from_pixels attribute """ if from_pixels is self.from_pixels: return self.from_pixels = from_pixels self._make_specs(self.env) def read_obs(self, observation): # the info is missing from the reset observations = self.env.obs_dict visual = self.env.get_exteroception() try: del observations["t"] except KeyError: pass # recover vec obsvec = [] pixel_list = [] observations.update(visual) for key in observations: if key.startswith("rgb"): pix = observations[key] if not pix.shape[0] == 1: pix = pix[None] pixel_list.append(pix) elif key in self._env.obs_keys: value = observations[key] if not value.shape: value = value[None] obsvec.append(value) # ravel helps with images if obsvec: obsvec = np.concatenate(obsvec, 0) if self.from_pixels: out = {"observation": obsvec, "pixels": np.concatenate(pixel_list, 0)} else: out = {"observation": obsvec} return super().read_obs(out) def read_info(self, info, tensordict_out): out = {} for key, value in info.items(): if key in ("obs_dict", "done", "reward"): continue if isinstance(value, dict): value = {key: _val for key, _val in value.items() if _val is not None} value = make_tensordict(value, batch_size=[]) out[key] = value tensordict_out.update(out) return tensordict_out def to(self, *args, **kwargs): out = super().to(*args, **kwargs) try: render_device = int(str(out.device)[-1]) except ValueError: render_device = 0 if render_device != self.render_device: out._build_env(**self._constructor_kwargs) return out def make_r3m_env(env_name, model_name="resnet50", download=True, **kwargs): base_env = RoboHiveEnv(env_name, from_pixels=True, pixels_only=False) vec_keys = [k for k in base_env.observation_spec.keys() if k not in "pixels"] env = TransformedEnv( base_env, Compose( R3MTransform( model_name, keys_in=["pixels"], keys_out=["pixel_r3m"], download=download, **kwargs, ), CatTensors(keys_in=["pixel_r3m", *vec_keys], out_key="observation_vector"), ), ) return env LIBS["robohive"] = RoboHiveEnv
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Custom env reg for RoboHive usage in TorchRL # Pixel rendering will be queried by torchrl, so we don't include those keys in visual_obs_keys_wt import os import warnings from pathlib import Path import robohive.envs.multi_task.substeps1 from robohive.envs.env_variants import register_env_variant visual_obs_keys_wt = robohive.envs.multi_task.substeps1.visual_obs_keys_wt class set_directory(object): """Sets the cwd within the context Args: path (Path): The path to the cwd """ def __init__(self, path: Path): self.path = path self.origin = Path().absolute() def __enter__(self): os.chdir(self.path) def __exit__(self, *args, **kwargs): os.chdir(self.origin) def __call__(self, fun): def new_fun(*args, **kwargs): with set_directory(Path(self.path)): return fun(*args, **kwargs) return new_fun CURR_DIR = robohive.envs.multi_task.substeps1.CURR_DIR MODEL_PATH = robohive.envs.multi_task.substeps1.MODEL_PATH CONFIG_PATH = robohive.envs.multi_task.substeps1.CONFIG_PATH RANDOM_ENTRY_POINT = robohive.envs.multi_task.substeps1.RANDOM_ENTRY_POINT FIXED_ENTRY_POINT = robohive.envs.multi_task.substeps1.FIXED_ENTRY_POINT ENTRY_POINT = RANDOM_ENTRY_POINT override_keys = [ "objs_jnt", "end_effector", "knob1_site_err", "knob2_site_err", "knob3_site_err", "knob4_site_err", "light_site_err", "slide_site_err", "leftdoor_site_err", "rightdoor_site_err", "microhandle_site_err", "kettle_site0_err", "rgb:right_cam:224x224:2d", "rgb:left_cam:224x224:2d", ] @set_directory(CURR_DIR) def register_kitchen_envs(): print("RLHive:> Registering Kitchen Envs") env_list = [ "kitchen_knob1_off-v3", "kitchen_knob1_on-v3", "kitchen_knob2_off-v3", "kitchen_knob2_on-v3", "kitchen_knob3_off-v3", "kitchen_knob3_on-v3", "kitchen_knob4_off-v3", "kitchen_knob4_on-v3", "kitchen_light_off-v3", "kitchen_light_on-v3", "kitchen_sdoor_close-v3", "kitchen_sdoor_open-v3", "kitchen_ldoor_close-v3", "kitchen_ldoor_open-v3", "kitchen_rdoor_close-v3", "kitchen_rdoor_open-v3", "kitchen_micro_close-v3", "kitchen_micro_open-v3", "FK1_RelaxFixed-v4", # "kitchen_close-v3", ] obs_keys_wt = { "robot_jnt": 1.0, "end_effector": 1.0, } visual_obs_keys = { "rgb:right_cam:224x224:2d": 1.0, "rgb:left_cam:224x224:2d": 1.0, } for env in env_list: try: new_env_name = "visual_" + env register_env_variant( env, variants={"obs_keys_wt": obs_keys_wt, "visual_keys": list(visual_obs_keys.keys())}, variant_id=new_env_name, override_keys=override_keys, ) except AssertionError as err: warnings.warn( f"Could not register {new_env_name}, the following error was raised: {err}" ) @set_directory(CURR_DIR) def register_franka_envs(): print("RLHive:> Registering Franka Envs") env_list = [ "franka_slide_random-v3", "franka_slide_close-v3", "franka_slide_open-v3", "franka_micro_random-v3", "franka_micro_close-v3", "franka_micro_open-v3", ] # Franka Appliance ====================================================================== obs_keys_wt = { "robot_jnt": 1.0, "end_effector": 1.0, } visual_obs_keys = { "rgb:right_cam:224x224:2d": 1.0, "rgb:left_cam:224x224:2d": 1.0, } for env in env_list: try: new_env_name = "visual_" + env register_env_variant( env, variants={"obs_keys_wt": obs_keys_wt, "visual_keys": visual_obs_keys}, variant_id=new_env_name, override_keys=override_keys, ) except AssertionError as err: warnings.warn( f"Could not register {new_env_name}, the following error was raised: {err}" ) @set_directory(CURR_DIR) def register_hand_envs(): print("RLHive:> Registering Arm Envs") env_list = ["door-v1", "hammer-v1", "pen-v1", "relocate-v1"] visual_obs_keys = [ "rgb:vil_camera:224x224:2d", "rgb:fixed:224x224:2d", ] # Hand Manipulation Suite ====================================================================== for env in env_list: try: new_env_name = "visual_" + env register_env_variant( env, variants={ "obs_keys": [ "hand_jnt", ], "visual_keys": visual_obs_keys, }, variant_id=new_env_name, ) except AssertionError as err: warnings.warn( f"Could not register {new_env_name}, the following error was raised: {err}" ) @set_directory(CURR_DIR) def register_myo_envs(): print("RLHive:> Registering Myo Envs") env_list = ["motorFingerReachFixed-v0"] visual_keys = [ "rgb:vil_camera:224x224:2d", "rgb:fixed:224x224:2d", ] # Hand Manipulation Suite ====================================================================== for env in env_list: try: new_env_name = "visual_" + env register_env_variant( env, variants={ "obs_keys": [ "hand_jnt", ], "visual_keys": visual_keys, }, variant_id=new_env_name, ) except AssertionError as err: warnings.warn( f"Could not register {new_env_name}, the following error was raised: {err}" )
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from .envs import ( register_franka_envs, register_hand_envs, register_kitchen_envs, register_myo_envs, ) register_franka_envs() register_kitchen_envs() register_hand_envs() register_myo_envs() from .rl_envs import RoboHiveEnv
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import List, Optional, Union import torch from torch.nn import Identity from torchrl.data.tensor_specs import ( CompositeSpec, TensorSpec, UnboundedContinuousTensorSpec, ) from torchrl.data.utils import DEVICE_TYPING from torchrl.envs.transforms.transforms import ( CatTensors, Compose, FlattenObservation, ObservationNorm, Resize, ToTensorImage, Transform, UnsqueezeTransform, ) try: from torchvision import models _has_tv = True except ImportError: _has_tv = False class _RRLNet(Transform): inplace = False def __init__(self, in_keys, out_keys, model_name, del_keys: bool = True): if not _has_tv: raise ImportError( "Tried to instantiate RRL without torchvision. Make sure you have " "torchvision installed in your environment." ) if model_name == "resnet18": self.model_name = "rrl_18" self.outdim = 512 convnet = models.resnet18(pretrained=True) elif model_name == "resnet34": self.model_name = "rrl_34" self.outdim = 512 convnet = models.resnet34(pretrained=True) elif model_name == "resnet50": self.model_name = "rrl_50" self.outdim = 2048 convnet = models.resnet50(pretrained=True) else: raise NotImplementedError( f"model {model_name} is currently not supported by RRL" ) convnet.fc = Identity() super().__init__(in_keys=in_keys, out_keys=out_keys) self.convnet = convnet self.del_keys = del_keys def _call(self, tensordict): tensordict_view = tensordict.view(-1) super()._call(tensordict_view) if self.del_keys: tensordict.exclude(*self.in_keys, inplace=True) return tensordict @torch.no_grad() def _apply_transform(self, obs: torch.Tensor) -> None: shape = None if obs.ndimension() > 4: shape = obs.shape[:-3] obs = obs.flatten(0, -4) out = self.convnet(obs) if shape is not None: out = out.view(*shape, *out.shape[1:]) return out def transform_observation_spec(self, observation_spec: TensorSpec) -> TensorSpec: if not isinstance(observation_spec, CompositeSpec): raise ValueError("_RRLNet can only infer CompositeSpec") keys = [key for key in observation_spec._specs.keys() if key in self.in_keys] device = observation_spec[keys[0]].device dim = observation_spec[keys[0]].shape[:-3] observation_spec = CompositeSpec(observation_spec) if self.del_keys: for in_key in keys: del observation_spec[in_key] for out_key in self.out_keys: observation_spec[out_key] = UnboundedContinuousTensorSpec( shape=torch.Size([*dim, self.outdim]), device=device ) return observation_spec # @staticmethod # def _load_weights(model_name, r3m_instance, dir_prefix): # if model_name not in ("r3m_50", "r3m_34", "r3m_18"): # raise ValueError( # "model_name should be one of 'r3m_50', 'r3m_34' or 'r3m_18'" # ) # # url = "https://download.pytorch.org/models/rl/r3m/" + model_name # url = "https://pytorch.s3.amazonaws.com/models/rl/r3m/" + model_name + ".pt" # d = load_state_dict_from_url( # url, # progress=True, # map_location=next(r3m_instance.parameters()).device, # model_dir=dir_prefix, # ) # td = TensorDict(d["r3m"], []).unflatten_keys(".") # td_flatten = td["module"]["convnet"].flatten_keys(".") # state_dict = td_flatten.to_dict() # r3m_instance.convnet.load_state_dict(state_dict) # def load_weights(self, dir_prefix=None): # self._load_weights(self.model_name, self, dir_prefix) def _init_first(fun): def new_fun(self, *args, **kwargs): if not self.initialized: self._init() return fun(self, *args, **kwargs) return new_fun class RRLTransform(Compose): """RRL Transform class. RRL provides pre-trained ResNet weights aimed at facilitating visual embedding for robotic tasks. The models are trained using Ego4d. See the paper: Shah, Rutav, and Vikash Kumar. "RRl: Resnet as representation for reinforcement learning." arXiv preprint arXiv:2107.03380 (2021). The RRLTransform is created in a lazy manner: the object will be initialized only when an attribute (a spec or the forward method) will be queried. The reason for this is that the :obj:`_init()` method requires some attributes of the parent environment (if any) to be accessed: by making the class lazy we can ensure that the following code snippet works as expected: Examples: >>> transform = RRLTransform("resnet50", in_keys=["pixels"]) >>> env.append_transform(transform) >>> # the forward method will first call _init which will look at env.observation_spec >>> env.reset() Args: model_name (str): one of resnet50, resnet34 or resnet18 in_keys (list of str): list of input keys. If left empty, the "pixels" key is assumed. out_keys (list of str, optional): list of output keys. If left empty, "rrl_vec" is assumed. size (int, optional): Size of the image to feed to resnet. Defaults to 244. stack_images (bool, optional): if False, the images given in the :obj:`in_keys` argument will be treaded separetely and each will be given a single, separated entry in the output tensordict. Defaults to :obj:`True`. download (bool, optional): if True, the weights will be downloaded using the torch.hub download API (i.e. weights will be cached for future use). Defaults to False. download_path (str, optional): path where to download the models. Default is None (cache path determined by torch.hub utils). tensor_pixels_keys (list of str, optional): Optionally, one can keep the original images (as collected from the env) in the output tensordict. If no value is provided, this won't be collected. """ @classmethod def __new__(cls, *args, **kwargs): cls.initialized = False cls._device = None cls._dtype = None return super().__new__(cls) def __init__( self, model_name: str, in_keys: List[str], out_keys: List[str] = None, size: int = 244, stack_images: bool = True, download: bool = False, download_path: Optional[str] = None, tensor_pixels_keys: List[str] = None, ): super().__init__() self.in_keys = in_keys if in_keys is not None else ["pixels"] self.download = download self.download_path = download_path self.model_name = model_name self.out_keys = out_keys self.size = size self.stack_images = stack_images self.tensor_pixels_keys = tensor_pixels_keys self._init() def _init(self): """Initializer for RRL.""" self.initialized = True in_keys = self.in_keys model_name = self.model_name out_keys = self.out_keys size = self.size stack_images = self.stack_images tensor_pixels_keys = self.tensor_pixels_keys # ToTensor transforms = [] if tensor_pixels_keys: for i in range(len(in_keys)): transforms.append( CatTensors( in_keys=[in_keys[i]], out_key=tensor_pixels_keys[i], del_keys=False, ) ) totensor = ToTensorImage( unsqueeze=False, in_keys=in_keys, ) transforms.append(totensor) # Normalize mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize = ObservationNorm( in_keys=in_keys, loc=torch.tensor(mean).view(3, 1, 1), scale=torch.tensor(std).view(3, 1, 1), standard_normal=True, ) transforms.append(normalize) # Resize: note that resize is a no-op if the tensor has the desired size already resize = Resize(size, size, in_keys=in_keys) transforms.append(resize) # RRL if out_keys is None: if stack_images: out_keys = ["rrl_vec"] else: out_keys = [f"rrl_vec_{i}" for i in range(len(in_keys))] self.out_keys = out_keys elif stack_images and len(out_keys) != 1: raise ValueError( f"out_key must be of length 1 if stack_images is True. Got out_keys={out_keys}" ) elif not stack_images and len(out_keys) != len(in_keys): raise ValueError( "out_key must be of length equal to in_keys if stack_images is False." ) if stack_images and len(in_keys) > 1: unsqueeze = UnsqueezeTransform( in_keys=in_keys, out_keys=in_keys, unsqueeze_dim=-4, ) transforms.append(unsqueeze) cattensors = CatTensors( in_keys, out_keys[0], dim=-4, ) network = _RRLNet( in_keys=out_keys, out_keys=out_keys, model_name=model_name, del_keys=False, ) flatten = FlattenObservation(-2, -1, out_keys) transforms = [*transforms, cattensors, network, flatten] else: network = _RRLNet( in_keys=in_keys, out_keys=out_keys, model_name=model_name, del_keys=True, ) transforms = [*transforms, network] for transform in transforms: self.append(transform) # if self.download: # self[-1].load_weights(dir_prefix=self.download_path) if self._device is not None: self.to(self._device) if self._dtype is not None: self.to(self._dtype) def to(self, dest: Union[DEVICE_TYPING, torch.dtype]): if isinstance(dest, torch.dtype): self._dtype = dest else: self._device = dest return super().to(dest) @property def device(self): return self._device @property def dtype(self): return self._dtype
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """Multi-node distributed data collection with submitit in contexts where jobs can't launch other jobs. The default configuration will ask for 8 nodes with 1 GPU each and 32 procs / node. It should reach a collection speed of roughly 15-25K fps, or better depending on the cluster specs. The logic of the script is the following: we create a `main()` function that executes or code (in this case just a data collection but in practice a training loop should be present). Since this `main()` function cannot launch sub-jobs by design, we launch the script from the jump host and pass the slurm specs to submitit. *Note*: Although we don't go in much details into this in this script, the specs of the training node and the specs of the inference nodes can differ (look at the DEFAULT_SLURM_CONF and DEFAULT_SLURM_CONF_MAIN dictionaries below). """ import time from argparse import ArgumentParser import torch from torchrl.collectors.distributed import submitit_delayed_launcher from torchrl.collectors.distributed.default_configs import ( DEFAULT_SLURM_CONF, DEFAULT_SLURM_CONF_MAIN, ) parser = ArgumentParser() parser.add_argument("--partition", "-p", help="slurm partition to use") parser.add_argument("--num_jobs", type=int, default=8, help="Number of jobs") parser.add_argument("--tcp_port", type=int, default=1234, help="TCP port") parser.add_argument( "--num_workers", type=int, default=8, help="Number of workers per node" ) parser.add_argument( "--gpus_per_node", "--gpus-per-node", "-G", type=int, default=1, help="Number of GPUs per node. If greater than 0, the backend used will be NCCL.", ) parser.add_argument( "--cpus_per_task", "--cpus-per-task", "-c", type=int, default=32, help="Number of CPUs per node.", ) parser.add_argument( "--sync", action="store_true", help="Use --sync to collect data synchronously." ) parser.add_argument( "--frames_per_batch", "--frames-per-batch", default=4000, type=int, help="Number of frames in each batch of data. Must be " "divisible by the product of nodes and workers if sync, by the number of " "workers otherwise.", ) parser.add_argument( "--total_frames", "--total-frames", default=10_000_000, type=int, help="Total number of frames collected by the collector.", ) parser.add_argument( "--time", "-t", default="1:00:00", help="Timeout for the nodes", ) parser.add_argument( "--backend", "-b", default="gloo", help="Backend for the collector", ) parser.add_argument("--env_name", default="franka_micro_random-v3") parser.add_argument("--r3m", action="store_true") args = parser.parse_args() slurm_gpus_per_node = args.gpus_per_node slurm_time = args.time backend = args.backend DEFAULT_SLURM_CONF["slurm_gpus_per_node"] = slurm_gpus_per_node DEFAULT_SLURM_CONF["slurm_time"] = slurm_time DEFAULT_SLURM_CONF["slurm_cpus_per_task"] = args.cpus_per_task DEFAULT_SLURM_CONF["slurm_partition"] = args.partition DEFAULT_SLURM_CONF_MAIN["slurm_partition"] = args.partition DEFAULT_SLURM_CONF_MAIN["slurm_time"] = slurm_time num_jobs = args.num_jobs tcp_port = args.tcp_port num_workers = args.num_workers sync = args.sync total_frames = args.total_frames frames_per_batch = args.frames_per_batch device = "cpu" if backend == "gloo" else "cuda:0" def make_env(args): def constructor(): from rlhive import RoboHiveEnv from torchrl.envs import EnvCreator, ParallelEnv, R3MTransform, TransformedEnv from torchrl.envs.libs.gym import GymEnv if args.num_workers > 1: penv = ParallelEnv( args.num_workers, # EnvCreator(lambda: RoboHiveEnv(args.env_name, device="cuda:0")), EnvCreator(lambda: GymEnv("Pendulum-v0", device="cuda:0")), ) else: # penv = RoboHiveEnv(args.env_name, device="cuda:0") penv = GymEnv("Pendulum-v0", device="cuda:0") if "visual" in args.env_name: if args.r3m: tenv = TransformedEnv( penv, R3MTransform( in_keys=["pixels"], download=True, model_name="resnet50" ), ) else: tenv = penv else: tenv = penv return tenv return constructor @submitit_delayed_launcher( num_jobs=num_jobs, backend=backend, tcpport=tcp_port, ) def main(): assert torch.cuda.device_count() import tqdm from torchrl.collectors import SyncDataCollector from torchrl.collectors.collectors import RandomPolicy from torchrl.collectors.distributed.generic import DistributedDataCollector from torchrl.envs import EnvCreator collector_class = SyncDataCollector collector = DistributedDataCollector( [EnvCreator(make_env(args))] * num_jobs, policy=RandomPolicy(make_env(args)().action_spec), launcher="submitit_delayed", frames_per_batch=frames_per_batch, total_frames=total_frames, tcp_port=tcp_port, collector_class=collector_class, num_workers_per_collector=args.num_workers, collector_kwargs={ "device": "cuda:0" if slurm_gpus_per_node else "cpu", "storing_device": device, }, storing_device="cpu", backend=backend, sync=sync, ) counter = 0 pbar = tqdm.tqdm(total=collector.total_frames) for i, data in enumerate(collector): pbar.update(data.numel()) pbar.set_description(f"data shape: {data.shape}, data device: {data.device}") if i >= 10: counter += data.numel() if i == 10: t0 = time.time() t1 = time.time() print(f"time elapsed: {t1-t0}s, rate: {counter/(t1-t0)} fps") collector.shutdown() exit() if __name__ == "__main__": main()
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os from omegaconf import DictConfig os.environ["sim_backend"] = "MUJOCO" def main(args: DictConfig): import numpy as np import torch.cuda import tqdm from rlhive.rl_envs import RoboHiveEnv from tensordict import TensorDict from torch import nn, optim from torchrl.collectors import MultiaSyncDataCollector from torchrl.data import TensorDictPrioritizedReplayBuffer, TensorDictReplayBuffer from torchrl.data.replay_buffers.storages import LazyMemmapStorage # from torchrl.envs import SerialEnv as ParallelEnv, R3MTransform, SelectTransform, TransformedEnv from torchrl.envs import ( CatTensors, EnvCreator, ParallelEnv, R3MTransform, SelectTransform, TransformedEnv, ) from torchrl.envs.transforms import Compose, FlattenObservation, RewardScaling from torchrl.envs.utils import set_exploration_mode, step_mdp from torchrl.modules import MLP, NormalParamWrapper, SafeModule from torchrl.modules.distributions import TanhNormal from torchrl.modules.tensordict_module.actors import ( ProbabilisticActor, ValueOperator, ) from torchrl.objectives import SoftUpdate from torchrl.objectives.deprecated import REDQLoss_deprecated as REDQLoss from torchrl.record import VideoRecorder from torchrl.record.loggers.wandb import WandbLogger from torchrl.trainers import Recorder # =========================================================================================== # Env constructor # --------------- # - Use the RoboHiveEnv class to wrap robohive envs in torchrl's GymWrapper # - Add transforms immediately after that: # - SelectTransform: selects the relevant kesy from our output # - R3MTransform # - FlattenObservation: The images delivered by robohive have a singleton dim to start with, we need to flatten that # - RewardScaling # # One can also possibly use ObservationNorm. # # TIPS: # - For faster execution, you should follow this abstract scheme, where we reduce the data # to be passed from worker to worker to a minimum, we apply R3M to a batch and append the # rest of the transforms afterward: # # >>> env = TransformedEnv( # ... ParallelEnv(N, lambda: TransformedEnv(RoboHiveEnv(...), SelectTransform(...))), # ... Compose( # ... R3MTransform(...), # ... FlattenObservation(...), # ... *other_transforms, # ... )) # def traj_is_solved(done, solved): solved = solved.view_as(done) done_cumsum = done.cumsum(-2) count = 0 _i = 0 for _i, u in enumerate(done_cumsum.unique()): is_solved = solved[done_cumsum == u].any() count += is_solved return count / (_i + 1) def traj_total_reward(done, reward): reward = reward.view_as(done) done_cumsum = done.cumsum(-2) count = 0 _i = 0 for _i, u in enumerate(done_cumsum.unique()): count += reward[done_cumsum == u].sum() return count / (_i + 1) def make_env(num_envs, task, visual_transform, reward_scaling, device): if num_envs > 1: base_env = ParallelEnv( num_envs, EnvCreator(lambda: RoboHiveEnv(task, device=device)) ) else: base_env = RoboHiveEnv(task, device=device) env = make_transformed_env( env=base_env, reward_scaling=reward_scaling, visual_transform=visual_transform, ) return env def make_transformed_env( env, reward_scaling=5.0, visual_transform="r3m", ): """ Apply transforms to the env (such as reward scaling and state normalization) """ env = TransformedEnv( env, SelectTransform( "solved", "pixels", "observation", "rwd_dense", "rwd_sparse" ), ) if visual_transform == "r3m": vec_keys = ["r3m_vec"] selected_keys = ["observation", "r3m_vec"] env.append_transform( Compose( R3MTransform("resnet50", in_keys=["pixels"], download=True).eval(), FlattenObservation(-2, -1, in_keys=vec_keys), ) ) # Necessary to Compose R3MTransform with FlattenObservation; Track bug: https://github.com/pytorch/rl/issues/802 elif visual_transform == "rrl": vec_keys = ["r3m_vec"] selected_keys = ["observation", "r3m_vec"] env.append_transform( Compose( R3MTransform( "resnet50", in_keys=["pixels"], download="IMAGENET1K_V2" ).eval(), FlattenObservation(-2, -1, in_keys=vec_keys), ) ) # Necessary to Compose R3MTransform with FlattenObservation; Track bug: https://github.com/pytorch/rl/issues/802 elif not visual_transform: selected_keys = ["observation"] else: raise NotImplementedError(visual_transform) env.append_transform(RewardScaling(loc=0.0, scale=reward_scaling)) out_key = "observation_vector" env.append_transform(CatTensors(in_keys=selected_keys, out_key=out_key)) return env # =========================================================================================== # Making a recorder # ----------------- # # A `Recorder` is a dedicated torchrl class that will run the policy in the test env # once every X steps (eg X=1M). # def make_recorder( task: str, frame_skip: int, record_interval: int, actor_model_explore: object, eval_traj: int, env_configs: dict, wandb_logger: WandbLogger, num_envs: int, ): test_env = make_env(num_envs=num_envs, task=task, **env_configs) if "visual" in task: test_env.insert_transform( 0, VideoRecorder(wandb_logger, "test", in_keys=["pixels"]) ) test_env.reset() recorder_obj = Recorder( record_frames=eval_traj * test_env.horizon, frame_skip=frame_skip, policy_exploration=actor_model_explore, recorder=test_env, exploration_mode="mean", record_interval=record_interval, log_keys=["reward", "solved", "done", "rwd_sparse"], out_keys={ "reward": "r_evaluation", "solved": "success", "done": "done", "rwd_sparse": "rwd_sparse", }, ) return recorder_obj # =========================================================================================== # Relplay buffers # --------------- # # TorchRL also provides prioritized RBs if needed. # def make_replay_buffer( prb: bool, buffer_size: int, buffer_scratch_dir: str, device: torch.device, prefetch: int = 10, ): if prb: replay_buffer = TensorDictPrioritizedReplayBuffer( alpha=0.7, beta=0.5, pin_memory=False, prefetch=prefetch, storage=LazyMemmapStorage( buffer_size, scratch_dir=buffer_scratch_dir, device=device, ), ) else: replay_buffer = TensorDictReplayBuffer( pin_memory=False, prefetch=prefetch, storage=LazyMemmapStorage( buffer_size, scratch_dir=buffer_scratch_dir, device=device, ), ) return replay_buffer # =========================================================================================== # Dataloader # ---------- # # This is a simplified version of the dataloder # @torch.no_grad() @set_exploration_mode("random") def dataloader( total_frames, fpb, train_env, actor, actor_collection, device_collection ): params = TensorDict( {k: v for k, v in actor.named_parameters()}, batch_size=[] ).unflatten_keys(".") params_collection = TensorDict( {k: v for k, v in actor_collection.named_parameters()}, batch_size=[] ).unflatten_keys(".") _prev = None collected_frames = 0 while collected_frames < total_frames: params_collection.update_(params) batch = TensorDict( {}, batch_size=[fpb, *train_env.batch_size], device=device_collection ) for t in range(fpb): if _prev is None: _prev = train_env.reset() _reset = _prev["_reset"] = _prev["done"].clone().squeeze(-1) if _reset.any(): _prev = train_env.reset(_prev) _new = train_env.step(actor_collection(_prev)) batch[t] = _new _prev = step_mdp(_new, exclude_done=False) collected_frames += batch.numel() yield batch # customize device at will device = args.device torch.manual_seed(args.seed) np.random.seed(args.seed) # Create Environment env_configs = { "reward_scaling": args.reward_scaling, "visual_transform": args.visual_transform, "device": "cpu", } train_env = make_env(num_envs=args.env_per_collector, task=args.task, **env_configs) # add forward pass for initialization with proof env proof_env = make_env(num_envs=1, task=args.task, **env_configs) # Create Agent # Define Actor Network in_keys = ["observation_vector"] action_spec = proof_env.action_spec actor_net_kwargs = { "num_cells": [256, 256], "out_features": 2 * action_spec.shape[-1], "activation_class": nn.ReLU, } actor_net = MLP(**actor_net_kwargs) dist_class = TanhNormal dist_kwargs = { "min": action_spec.space.minimum, "max": action_spec.space.maximum, "tanh_loc": True, } actor_net = NormalParamWrapper( actor_net, scale_mapping=f"biased_softplus_{1.0}", scale_lb=0.1, ) in_keys_actor = in_keys actor_module = SafeModule( actor_net, in_keys=in_keys_actor, out_keys=[ "loc", "scale", ], ) actor = ProbabilisticActor( spec=action_spec, in_keys=["loc", "scale"], module=actor_module, distribution_class=dist_class, distribution_kwargs=dist_kwargs, default_interaction_mode="random", return_log_prob=True, ) # Define Critic Network qvalue_net_kwargs = { "num_cells": [256, 256], "out_features": 1, "activation_class": nn.ReLU, } qvalue_net = MLP( **qvalue_net_kwargs, ) qvalue = ValueOperator( in_keys=["action"] + in_keys, module=qvalue_net, ) model = actor, qvalue = nn.ModuleList([actor, qvalue]).to(device) # init nets with torch.no_grad(), set_exploration_mode("random"): td = proof_env.reset() td = td.to(device) for net in model: net(td) del td proof_env.close() actor_model_explore = model[0] # Create REDQ loss loss_module = REDQLoss( actor_network=model[0], qvalue_network=model[1], gamma=args.gamma, loss_function="smooth_l1", ) # Define Target Network Updater target_net_updater = SoftUpdate(loss_module, args.target_update_polyak) # Make Replay Buffer replay_buffer = make_replay_buffer( prb=args.prb, buffer_size=args.buffer_size, buffer_scratch_dir=args.buffer_scratch_dir, device="cpu", ) # Optimizers params = list(loss_module.parameters()) optimizer = optim.Adam(params, lr=args.lr, weight_decay=args.weight_decay) rewards = [] rewards_eval = [] # Main loop target_net_updater.init_() collected_frames = 0 episodes = 0 optim_steps = 0 pbar = tqdm.tqdm(total=args.total_frames) r0 = None loss = None logger = WandbLogger( exp_name=args.task, project=args.wandb_project, name=args.exp_name, config=args, entity=args.wandb_entity, mode=args.wandb_mode, ) # Trajectory recorder for evaluation recorder = make_recorder( task=args.task, frame_skip=args.frame_skip, record_interval=args.record_interval, actor_model_explore=actor_model_explore, eval_traj=args.eval_traj, env_configs=env_configs, wandb_logger=logger, num_envs=args.num_record_envs, ) collector_device = args.device_collection if isinstance(collector_device, str): collector_device = [collector_device] collector = MultiaSyncDataCollector( create_env_fn=[train_env for _ in collector_device], policy=actor_model_explore, total_frames=args.total_frames, max_frames_per_traj=args.frames_per_batch, frames_per_batch=args.frames_per_batch, init_random_frames=args.init_random_frames, reset_at_each_iter=False, postproc=None, split_trajs=False, devices=collector_device, # device for execution passing_devices=collector_device, # device where data will be stored and passed seed=args.seed, pin_memory=False, update_at_each_batch=False, exploration_mode="random", ) for i, batch in enumerate(collector): collector.update_policy_weights_() if r0 is None: r0 = batch["reward"].sum(-1).mean().item() pbar.update(batch.numel()) # extend the replay buffer with the new data batch = batch.cpu().view(-1) current_frames = batch.numel() collected_frames += current_frames episodes += batch["done"].sum() replay_buffer.extend(batch) # optimization steps if collected_frames >= args.init_random_frames: ( total_losses, actor_losses, q_losses, alpha_losses, alphas, entropies, ) = ([], [], [], [], [], []) for _ in range( max(1, args.frames_per_batch * args.utd_ratio // args.batch_size) ): optim_steps += 1 # sample from replay buffer sampled_tensordict = ( replay_buffer.sample(args.batch_size).clone().to(device) ) loss_td = loss_module(sampled_tensordict) actor_loss = loss_td["loss_actor"] q_loss = loss_td["loss_qvalue"] alpha_loss = loss_td["loss_alpha"] loss = actor_loss + q_loss + alpha_loss optimizer.zero_grad() loss.backward() gn = torch.nn.utils.clip_grad_norm_(params, args.clip_norm) optimizer.step() # update qnet_target params target_net_updater.step() # update priority if args.prb: replay_buffer.update_tensordict_priority(sampled_tensordict) total_losses.append(loss.item()) actor_losses.append(actor_loss.item()) q_losses.append(q_loss.item()) alpha_losses.append(alpha_loss.item()) alphas.append(loss_td["alpha"].item()) entropies.append(loss_td["entropy"].item()) rewards.append((i, batch["reward"].mean().item())) logger.log_scalar("train_reward", rewards[-1][1], step=collected_frames) logger.log_scalar("optim_steps", optim_steps, step=collected_frames) logger.log_scalar("episodes", episodes, step=collected_frames) if loss is not None: logger.log_scalar( "total_loss", np.mean(total_losses), step=collected_frames ) logger.log_scalar( "actor_loss", np.mean(actor_losses), step=collected_frames ) logger.log_scalar("q_loss", np.mean(q_losses), step=collected_frames) logger.log_scalar( "alpha_loss", np.mean(alpha_losses), step=collected_frames ) logger.log_scalar("alpha", np.mean(alphas), step=collected_frames) logger.log_scalar("entropy", np.mean(entropies), step=collected_frames) logger.log_scalar("grad_norm", gn, step=collected_frames) td_record = recorder(None) if td_record is not None: rewards_eval.append( ( i, td_record["r_evaluation"] / recorder.recorder.batch_size.numel(), # divide by number of eval worker ) ) logger.log_scalar("test_reward", rewards_eval[-1][1], step=collected_frames) solved = traj_is_solved(td_record["done"], td_record["success"]) logger.log_scalar("success", solved, step=collected_frames) rwd_sparse = traj_total_reward(td_record["done"], td_record["rwd_sparse"]) logger.log_scalar("rwd_sparse", rwd_sparse, step=collected_frames) if len(rewards_eval): pbar.set_description( f"reward: {rewards[-1][1]: 4.4f} (r0 = {r0: 4.4f}), test reward: {rewards_eval[-1][1]: 4.4f}, solved: {solved}" ) del batch # gc.collect() if __name__ == "__main__": main()
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os from omegaconf import DictConfig os.environ["sim_backend"] = "MUJOCO" os.environ["MUJOCO_GL"] = "egl" def main(args: DictConfig): import numpy as np import torch.cuda import tqdm from rlhive.rl_envs import RoboHiveEnv from sac_loss import SACLoss from tensordict import TensorDict from torch import nn, optim from torchrl.collectors import MultiaSyncDataCollector from torchrl.data import TensorDictPrioritizedReplayBuffer, TensorDictReplayBuffer from torchrl.data.replay_buffers.storages import LazyMemmapStorage # from torchrl.envs import SerialEnv as ParallelEnv, R3MTransform, SelectTransform, TransformedEnv from torchrl.envs import ( CatTensors, EnvCreator, ParallelEnv, R3MTransform, SelectTransform, TransformedEnv, ) from torchrl.envs.transforms import Compose, FlattenObservation, RewardScaling from torchrl.envs.utils import set_exploration_mode, step_mdp from torchrl.modules import MLP, NormalParamWrapper, SafeModule from torchrl.modules.distributions import TanhNormal from torchrl.modules.tensordict_module.actors import ( ProbabilisticActor, ValueOperator, ) from torchrl.objectives import SoftUpdate from torchrl.record import VideoRecorder from torchrl.record.loggers.wandb import WandbLogger from torchrl.trainers import Recorder # =========================================================================================== # Env constructor # --------------- # - Use the RoboHiveEnv class to wrap robohive envs in torchrl's GymWrapper # - Add transforms immediately after that: # - SelectTransform: selects the relevant kesy from our output # - R3MTransform # - FlattenObservation: The images delivered by robohive have a singleton dim to start with, we need to flatten that # - RewardScaling # # One can also possibly use ObservationNorm. # # TIPS: # - For faster execution, you should follow this abstract scheme, where we reduce the data # to be passed from worker to worker to a minimum, we apply R3M to a batch and append the # rest of the transforms afterward: # # >>> env = TransformedEnv( # ... ParallelEnv(N, lambda: TransformedEnv(RoboHiveEnv(...), SelectTransform(...))), # ... Compose( # ... R3MTransform(...), # ... FlattenObservation(...), # ... *other_transforms, # ... )) # def traj_is_solved(done, solved): solved = solved.view_as(done) done_cumsum = done.cumsum(-2) count = 0 _i = 0 for _i, u in enumerate(done_cumsum.unique()): is_solved = solved[done_cumsum == u].any() count += is_solved return count / (_i + 1) def traj_total_reward(done, reward): reward = reward.view_as(done) done_cumsum = done.cumsum(-2) count = 0 _i = 0 for _i, u in enumerate(done_cumsum.unique()): count += reward[done_cumsum == u].sum() return count / (_i + 1) def make_env(num_envs, task, visual_transform, reward_scaling, device): if num_envs > 1: base_env = ParallelEnv( num_envs, EnvCreator(lambda: RoboHiveEnv(task, device=device)) ) else: base_env = RoboHiveEnv(task, device=device) env = make_transformed_env( env=base_env, reward_scaling=reward_scaling, visual_transform=visual_transform, ) return env def make_transformed_env( env, reward_scaling=5.0, visual_transform="r3m", ): """ Apply transforms to the env (such as reward scaling and state normalization) """ env = TransformedEnv( env, SelectTransform( "solved", "pixels", "observation", "rwd_dense", "rwd_sparse" ), ) if visual_transform == "r3m": vec_keys = ["r3m_vec"] selected_keys = ["observation", "r3m_vec"] env.append_transform( Compose( R3MTransform("resnet50", in_keys=["pixels"], download=True).eval(), FlattenObservation(-2, -1, in_keys=vec_keys), ) ) # Necessary to Compose R3MTransform with FlattenObservation; Track bug: https://github.com/pytorch/rl/issues/802 elif visual_transform == "rrl": vec_keys = ["r3m_vec"] selected_keys = ["observation", "r3m_vec"] env.append_transform( Compose( R3MTransform( "resnet50", in_keys=["pixels"], download="IMAGENET1K_V2" ).eval(), FlattenObservation(-2, -1, in_keys=vec_keys), ) ) # Necessary to Compose R3MTransform with FlattenObservation; Track bug: https://github.com/pytorch/rl/issues/802 elif not visual_transform: selected_keys = ["observation"] else: raise NotImplementedError(visual_transform) env.append_transform(RewardScaling(loc=0.0, scale=reward_scaling)) out_key = "observation_vector" env.append_transform(CatTensors(in_keys=selected_keys, out_key=out_key)) return env # =========================================================================================== # Making a recorder # ----------------- # # A `Recorder` is a dedicated torchrl class that will run the policy in the test env # once every X steps (eg X=1M). # def make_recorder( task: str, frame_skip: int, record_interval: int, actor_model_explore: object, eval_traj: int, env_configs: dict, wandb_logger: WandbLogger, num_envs: int, ): test_env = make_env(num_envs=num_envs, task=task, **env_configs) if "visual" in task: test_env.insert_transform( 0, VideoRecorder(wandb_logger, "test", in_keys=["pixels"]) ) test_env.reset() recorder_obj = Recorder( record_frames=eval_traj * test_env.horizon, frame_skip=frame_skip, policy_exploration=actor_model_explore, recorder=test_env, exploration_mode="mean", record_interval=record_interval, log_keys=["reward", "solved", "done", "rwd_sparse"], out_keys={ "reward": "r_evaluation", "solved": "success", "done": "done", "rwd_sparse": "rwd_sparse", }, ) return recorder_obj # =========================================================================================== # Relplay buffers # --------------- # # TorchRL also provides prioritized RBs if needed. # def make_replay_buffer( prb: bool, buffer_size: int, buffer_scratch_dir: str, device: torch.device, prefetch: int = 10, ): if prb: replay_buffer = TensorDictPrioritizedReplayBuffer( alpha=0.7, beta=0.5, pin_memory=False, prefetch=prefetch, storage=LazyMemmapStorage( buffer_size, scratch_dir=buffer_scratch_dir, device=device, ), ) else: replay_buffer = TensorDictReplayBuffer( pin_memory=False, prefetch=prefetch, storage=LazyMemmapStorage( buffer_size, scratch_dir=buffer_scratch_dir, device=device, ), ) return replay_buffer # =========================================================================================== # Dataloader # ---------- # # This is a simplified version of the dataloder # @torch.no_grad() @set_exploration_mode("random") def dataloader( total_frames, fpb, train_env, actor, actor_collection, device_collection ): params = TensorDict( {k: v for k, v in actor.named_parameters()}, batch_size=[] ).unflatten_keys(".") params_collection = TensorDict( {k: v for k, v in actor_collection.named_parameters()}, batch_size=[] ).unflatten_keys(".") _prev = None collected_frames = 0 while collected_frames < total_frames: params_collection.update_(params) batch = TensorDict( {}, batch_size=[fpb, *train_env.batch_size], device=device_collection ) for t in range(fpb): if _prev is None: _prev = train_env.reset() _reset = _prev["_reset"] = _prev["done"].clone().squeeze(-1) if _reset.any(): _prev = train_env.reset(_prev) _new = train_env.step(actor_collection(_prev)) batch[t] = _new _prev = step_mdp(_new, exclude_done=False) collected_frames += batch.numel() yield batch # customize device at will device = args.device torch.manual_seed(args.seed) np.random.seed(args.seed) # Create Environment env_configs = { "reward_scaling": args.reward_scaling, "visual_transform": args.visual_transform, "device": device, } train_env = make_env(num_envs=args.env_per_collector, task=args.task, **env_configs) # add forward pass for initialization with proof env proof_env = make_env(num_envs=1, task=args.task, **env_configs) # Create Agent # Define Actor Network in_keys = ["observation_vector"] action_spec = proof_env.action_spec actor_net_kwargs = { "num_cells": [256, 256], "out_features": 2 * action_spec.shape[-1], "activation_class": nn.ReLU, } actor_net = MLP(**actor_net_kwargs) dist_class = TanhNormal dist_kwargs = { "min": action_spec.space.minimum, "max": action_spec.space.maximum, "tanh_loc": True, } actor_net = NormalParamWrapper( actor_net, scale_mapping=f"biased_softplus_{1.0}", scale_lb=0.1, ) in_keys_actor = in_keys actor_module = SafeModule( actor_net, in_keys=in_keys_actor, out_keys=[ "loc", "scale", ], ) actor = ProbabilisticActor( spec=action_spec, in_keys=["loc", "scale"], module=actor_module, distribution_class=dist_class, distribution_kwargs=dist_kwargs, default_interaction_mode="random", return_log_prob=True, ) # Define Critic Network qvalue_net_kwargs = { "num_cells": [256, 256], "out_features": 1, "activation_class": nn.ReLU, } qvalue_net = MLP( **qvalue_net_kwargs, ) qvalue = ValueOperator( in_keys=["action"] + in_keys, module=qvalue_net, ) model = actor, qvalue = nn.ModuleList([actor, qvalue]).to(device) # init nets with torch.no_grad(), set_exploration_mode("random"): td = proof_env.reset() td = td.to(device) for net in model: net(td) del td proof_env.close() actor_model_explore = model[0] # Create SAC loss loss_module = SACLoss( actor_network=model[0], qvalue_network=model[1], num_qvalue_nets=2, gamma=args.gamma, loss_function="smooth_l1", ) # Define Target Network Updater target_net_updater = SoftUpdate(loss_module, args.target_update_polyak) # Make Replay Buffer replay_buffer = make_replay_buffer( prb=args.prb, buffer_size=args.buffer_size, buffer_scratch_dir=args.buffer_scratch_dir, device=args.device, ) # Optimizers params = list(loss_module.parameters()) optimizer = optim.Adam(params, lr=args.lr, weight_decay=args.weight_decay) rewards = [] rewards_eval = [] # Main loop target_net_updater.init_() collected_frames = 0 episodes = 0 optim_steps = 0 pbar = tqdm.tqdm(total=args.total_frames) r0 = None loss = None logger = WandbLogger( exp_name=args.task, project=args.wandb_project, name=args.exp_name, config=args, entity=args.wandb_entity, mode=args.wandb_mode, ) # Trajectory recorder for evaluation recorder = make_recorder( task=args.task, frame_skip=args.frame_skip, record_interval=args.record_interval, actor_model_explore=actor_model_explore, eval_traj=args.eval_traj, env_configs=env_configs, wandb_logger=logger, num_envs=args.num_record_envs, ) collector_device = args.device_collection if isinstance(collector_device, str): collector_device = [collector_device] collector = MultiaSyncDataCollector( create_env_fn=[train_env for _ in collector_device], policy=actor_model_explore, total_frames=args.total_frames, max_frames_per_traj=args.frames_per_batch, frames_per_batch=args.frames_per_batch, init_random_frames=args.init_random_frames, reset_at_each_iter=False, postproc=None, split_trajs=False, devices=collector_device, # device for execution storing_devices=collector_device, # device where data will be stored and passed seed=args.seed, pin_memory=False, update_at_each_batch=False, exploration_mode="random", ) for i, batch in enumerate(collector): collector.update_policy_weights_() if r0 is None: r0 = batch["reward"].sum(-1).mean().item() pbar.update(batch.numel()) # extend the replay buffer with the new data batch = batch.cpu().view(-1) current_frames = batch.numel() collected_frames += current_frames episodes += batch["done"].sum() replay_buffer.extend(batch) # optimization steps if collected_frames >= args.init_random_frames: ( total_losses, actor_losses, q_losses, alpha_losses, alphas, entropies, ) = ([], [], [], [], [], []) for _ in range( max(1, args.frames_per_batch * args.utd_ratio // args.batch_size) ): optim_steps += 1 # sample from replay buffer sampled_tensordict = ( replay_buffer.sample(args.batch_size).clone().to(device) ) loss_td = loss_module(sampled_tensordict) actor_loss = loss_td["loss_actor"] q_loss = loss_td["loss_qvalue"] alpha_loss = loss_td["loss_alpha"] loss = actor_loss + q_loss + alpha_loss optimizer.zero_grad() loss.backward() gn = torch.nn.utils.clip_grad_norm_(params, args.clip_norm) optimizer.step() # update qnet_target params target_net_updater.step() # update priority if args.prb: replay_buffer.update_tensordict_priority(sampled_tensordict) total_losses.append(loss.item()) actor_losses.append(actor_loss.item()) q_losses.append(q_loss.item()) alpha_losses.append(alpha_loss.item()) alphas.append(loss_td["alpha"].item()) entropies.append(loss_td["entropy"].item()) rewards.append((i, batch["reward"].mean().item())) logger.log_scalar("train_reward", rewards[-1][1], step=collected_frames) logger.log_scalar("optim_steps", optim_steps, step=collected_frames) logger.log_scalar("episodes", episodes, step=collected_frames) if loss is not None: logger.log_scalar( "total_loss", np.mean(total_losses), step=collected_frames ) logger.log_scalar( "actor_loss", np.mean(actor_losses), step=collected_frames ) logger.log_scalar("q_loss", np.mean(q_losses), step=collected_frames) logger.log_scalar( "alpha_loss", np.mean(alpha_losses), step=collected_frames ) logger.log_scalar("alpha", np.mean(alphas), step=collected_frames) logger.log_scalar("entropy", np.mean(entropies), step=collected_frames) logger.log_scalar("grad_norm", gn, step=collected_frames) td_record = recorder(None) if td_record is not None: rewards_eval.append( ( i, td_record["r_evaluation"] / recorder.recorder.batch_size.numel(), # divide by number of eval worker ) ) logger.log_scalar("test_reward", rewards_eval[-1][1], step=collected_frames) solved = traj_is_solved(td_record["done"], td_record["success"]) logger.log_scalar("success", solved, step=collected_frames) rwd_sparse = traj_total_reward(td_record["done"], td_record["rwd_sparse"]) logger.log_scalar("rwd_sparse", rwd_sparse, step=collected_frames) if len(rewards_eval): pbar.set_description( f"reward: {rewards[-1][1]: 4.4f} (r0 = {r0: 4.4f}), test reward: {rewards_eval[-1][1]: 4.4f}, solved: {solved}" ) del batch # gc.collect()
"""Entry point for RLHive""" import hydra from omegaconf import DictConfig from redq import main as train_redq from sac import main as train_sac @hydra.main(config_name="sac_mixed.yaml", config_path="config") def main(args: DictConfig): if args.algo == "sac": train_sac(args) if args.algo == "redq": train_redq(args) else: raise NotImplementedError if __name__ == "__main__": main()
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os os.environ["sim_backend"] = "MUJOCO" import argparse import time import tqdm from rlhive.rl_envs import RoboHiveEnv from torchrl.collectors.collectors import MultiaSyncDataCollector, RandomPolicy from torchrl.collectors.distributed import DistributedDataCollector, RPCDataCollector from torchrl.envs import EnvCreator, ParallelEnv, R3MTransform, TransformedEnv parser = argparse.ArgumentParser() parser.add_argument("--num_workers", default=2, type=int) parser.add_argument("--num_collectors", default=4, type=int) parser.add_argument("--frames_per_batch", default=200, type=int) parser.add_argument("--total_frames", default=20_000, type=int) parser.add_argument("--r3m", action="store_true") parser.add_argument("--env_name", default="franka_micro_random-v3") if __name__ == "__main__": args = parser.parse_args() if args.num_workers > 1: penv = ParallelEnv( args.num_workers, EnvCreator(lambda: RoboHiveEnv(args.env_name, device="cpu")), ) else: penv = RoboHiveEnv(args.env_name, device="cpu") if "visual" in args.env_name: if args.r3m: tenv = TransformedEnv( penv, R3MTransform(in_keys=["pixels"], download=True, model_name="resnet50"), ) else: tenv = penv else: tenv = penv # tenv.transform[-1].init_stats(reduce_dim=(0, 1), cat_dim=1, # num_iter=1000) policy = RandomPolicy(tenv.action_spec) # some random policy device = "cpu" slurm_conf = { "timeout_min": 100, "slurm_partition": "train", "slurm_cpus_per_gpu": 12, "slurm_gpus_per_task": 1, } collector = DistributedDataCollector( [tenv] * args.num_collectors, policy=policy, frames_per_batch=args.frames_per_batch, total_frames=args.total_frames, storing_device=device, split_trajs=False, sync=True, launcher="mp", slurm_kwargs=slurm_conf, backend="gloo", ) pbar = tqdm.tqdm(total=args.total_frames) for i, data in enumerate(collector): if i == 3: t0 = time.time() total = 0 if i >= 3: total += data.numel() pbar.update(data.numel()) t = time.time() - t0 print(f"{args.env_name}, Time: {t:4.4f}, Rate: {args.total_frames / t: 4.4f} fps") del collector del tenv
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from numbers import Number from typing import Union import numpy as np import torch from tensordict.nn import TensorDictSequential from tensordict.tensordict import TensorDict, TensorDictBase from torch import Tensor from torchrl.envs.utils import set_exploration_mode, step_mdp from torchrl.modules import SafeModule from torchrl.objectives.common import LossModule from torchrl.objectives.utils import ( distance_loss, next_state_value as get_next_state_value, ) try: from functorch import vmap FUNCTORCH_ERR = "" _has_functorch = True except ImportError as err: FUNCTORCH_ERR = str(err) _has_functorch = False class SACLoss(LossModule): """SAC Loss module. Args: actor_network (SafeModule): the actor to be trained qvalue_network (SafeModule): a single Q-value network that will be multiplicated as many times as needed. num_qvalue_nets (int, optional): Number of Q-value networks to be trained. Default is 10. gamma (Number, optional): gamma decay factor. Default is 0.99. priotity_key (str, optional): Key where to write the priority value for prioritized replay buffers. Default is `"td_error"`. loss_function (str, optional): loss function to be used for the Q-value. Can be one of `"smooth_l1"`, "l2", "l1", Default is "smooth_l1". alpha_init (float, optional): initial entropy multiplier. Default is 1.0. min_alpha (float, optional): min value of alpha. Default is 0.1. max_alpha (float, optional): max value of alpha. Default is 10.0. fixed_alpha (bool, optional): whether alpha should be trained to match a target entropy. Default is :obj:`False`. target_entropy (Union[str, Number], optional): Target entropy for the stochastic policy. Default is "auto". delay_qvalue (bool, optional): Whether to separate the target Q value networks from the Q value networks used for data collection. Default is :obj:`False`. gSDE (bool, optional): Knowing if gSDE is used is necessary to create random noise variables. Default is False """ delay_actor: bool = False _explicit: bool = False def __init__( self, actor_network: SafeModule, qvalue_network: SafeModule, num_qvalue_nets: int = 2, gamma: Number = 0.99, priotity_key: str = "td_error", loss_function: str = "smooth_l1", alpha_init: float = 1.0, min_alpha: float = 0.1, max_alpha: float = 10.0, fixed_alpha: bool = False, target_entropy: Union[str, Number] = "auto", delay_qvalue: bool = True, gSDE: bool = False, ): if not _has_functorch: raise ImportError( f"Failed to import functorch with error message:\n{FUNCTORCH_ERR}" ) super().__init__() self.convert_to_functional( actor_network, "actor_network", create_target_params=self.delay_actor, funs_to_decorate=["forward", "get_dist_params"], ) # let's make sure that actor_network has `return_log_prob` set to True self.actor_network.return_log_prob = True self.delay_qvalue = delay_qvalue self.convert_to_functional( qvalue_network, "qvalue_network", num_qvalue_nets, create_target_params=self.delay_qvalue, compare_against=list(actor_network.parameters()), ) self.num_qvalue_nets = num_qvalue_nets self.register_buffer("gamma", torch.tensor(gamma)) self.priority_key = priotity_key self.loss_function = loss_function try: device = next(self.parameters()).device except AttributeError: device = torch.device("cpu") self.register_buffer("alpha_init", torch.tensor(alpha_init, device=device)) self.register_buffer( "min_log_alpha", torch.tensor(min_alpha, device=device).log() ) self.register_buffer( "max_log_alpha", torch.tensor(max_alpha, device=device).log() ) self.fixed_alpha = fixed_alpha if fixed_alpha: self.register_buffer( "log_alpha", torch.tensor(math.log(alpha_init), device=device) ) else: self.register_parameter( "log_alpha", torch.nn.Parameter(torch.tensor(math.log(alpha_init), device=device)), ) if target_entropy == "auto": if actor_network.spec["action"] is None: raise RuntimeError( "Cannot infer the dimensionality of the action. Consider providing " "the target entropy explicitely or provide the spec of the " "action tensor in the actor network." ) target_entropy = -float(np.prod(actor_network.spec["action"].shape)) self.register_buffer( "target_entropy", torch.tensor(target_entropy, device=device) ) self.gSDE = gSDE @property def alpha(self): self.log_alpha.data.clamp_(self.min_log_alpha, self.max_log_alpha) with torch.no_grad(): alpha = self.log_alpha.exp() return alpha def forward(self, tensordict: TensorDictBase) -> TensorDictBase: if self._explicit: # slow but explicit version return self._forward_explicit(tensordict) else: return self._forward_vectorized(tensordict) def _loss_alpha(self, log_pi: Tensor) -> Tensor: if torch.is_grad_enabled() and not log_pi.requires_grad: raise RuntimeError( "expected log_pi to require gradient for the alpha loss)" ) if self.target_entropy is not None: # we can compute this loss even if log_alpha is not a parameter alpha_loss = -self.log_alpha.exp() * (log_pi.detach() + self.target_entropy) else: # placeholder alpha_loss = torch.zeros_like(log_pi) return alpha_loss def _forward_vectorized(self, tensordict: TensorDictBase) -> TensorDictBase: obs_keys = self.actor_network.in_keys tensordict_select = tensordict.select( "reward", "done", "next", *obs_keys, "action" ) actor_params = torch.stack( [self.actor_network_params, self.target_actor_network_params], 0 ) tensordict_actor_grad = tensordict_select.select( *obs_keys ) # to avoid overwriting keys next_td_actor = step_mdp(tensordict_select).select( *self.actor_network.in_keys ) # next_observation -> tensordict_actor = torch.stack([tensordict_actor_grad, next_td_actor], 0) tensordict_actor = tensordict_actor.contiguous() with set_exploration_mode("random"): if self.gSDE: tensordict_actor.set( "_eps_gSDE", torch.zeros(tensordict_actor.shape, device=tensordict_actor.device), ) # vmap doesn't support sampling, so we take it out from the vmap td_params = vmap(self.actor_network.get_dist_params)( tensordict_actor, actor_params, ) if isinstance(self.actor_network, TensorDictSequential): sample_key = self.actor_network[-1].out_keys[0] tensordict_actor_dist = self.actor_network.build_dist_from_params( td_params ) else: sample_key = self.actor_network.out_keys[0] tensordict_actor_dist = self.actor_network.build_dist_from_params( td_params ) tensordict_actor[sample_key] = self._rsample(tensordict_actor_dist) tensordict_actor["sample_log_prob"] = tensordict_actor_dist.log_prob( tensordict_actor[sample_key] ) # repeat tensordict_actor to match the qvalue size _actor_loss_td = ( tensordict_actor[0] .select(*self.qvalue_network.in_keys) .expand(self.num_qvalue_nets, *tensordict_actor[0].batch_size) ) # for actor loss _qval_td = tensordict_select.select(*self.qvalue_network.in_keys).expand( self.num_qvalue_nets, *tensordict_select.select(*self.qvalue_network.in_keys).batch_size, ) # for qvalue loss _next_val_td = ( tensordict_actor[1] .select(*self.qvalue_network.in_keys) .expand(self.num_qvalue_nets, *tensordict_actor[1].batch_size) ) # for next value estimation tensordict_qval = torch.cat( [ _actor_loss_td, _next_val_td, _qval_td, ], 0, ) # cat params q_params_detach = self.qvalue_network_params.detach() qvalue_params = torch.cat( [ q_params_detach, self.target_qvalue_network_params, self.qvalue_network_params, ], 0, ) tensordict_qval = vmap(self.qvalue_network)( tensordict_qval, qvalue_params, ) state_action_value = tensordict_qval.get("state_action_value").squeeze(-1) ( state_action_value_actor, next_state_action_value_qvalue, state_action_value_qvalue, ) = state_action_value.split( [self.num_qvalue_nets, self.num_qvalue_nets, self.num_qvalue_nets], dim=0, ) sample_log_prob = tensordict_actor.get("sample_log_prob").squeeze(-1) ( action_log_prob_actor, next_action_log_prob_qvalue, ) = sample_log_prob.unbind(0) # E[alpha * log_pi(a) - Q(s, a)] where a is reparameterized loss_actor = -( state_action_value_actor.min(0)[0] - self.alpha * action_log_prob_actor ).mean() next_state_value = ( next_state_action_value_qvalue.min(0)[0] - self.alpha * next_action_log_prob_qvalue ) target_value = get_next_state_value( tensordict, gamma=self.gamma, pred_next_val=next_state_value, ) pred_val = state_action_value_qvalue td_error = (pred_val - target_value).pow(2) loss_qval = ( distance_loss( pred_val, target_value.expand_as(pred_val), loss_function=self.loss_function, ) .mean(-1) .sum() * 0.5 ) tensordict.set("td_error", td_error.detach().max(0)[0]) loss_alpha = self._loss_alpha(sample_log_prob) if not loss_qval.shape == loss_actor.shape: raise RuntimeError( f"QVal and actor loss have different shape: {loss_qval.shape} and {loss_actor.shape}" ) td_out = TensorDict( { "loss_actor": loss_actor.mean(), "loss_qvalue": loss_qval.mean(), "loss_alpha": loss_alpha.mean(), "alpha": self.alpha.detach(), "entropy": -sample_log_prob.mean().detach(), "state_action_value_actor": state_action_value_actor.mean().detach(), "action_log_prob_actor": action_log_prob_actor.mean().detach(), "next.state_value": next_state_value.mean().detach(), "target_value": target_value.mean().detach(), }, [], ) return td_out def _forward_explicit(self, tensordict: TensorDictBase) -> TensorDictBase: loss_actor, sample_log_prob = self._loss_actor_explicit(tensordict.clone(False)) loss_qval, td_error = self._loss_qval_explicit(tensordict.clone(False)) tensordict.set("td_error", td_error.detach().max(0)[0]) loss_alpha = self._loss_alpha(sample_log_prob) td_out = TensorDict( { "loss_actor": loss_actor.mean(), "loss_qvalue": loss_qval.mean(), "loss_alpha": loss_alpha.mean(), "alpha": self.alpha.detach(), "entropy": -sample_log_prob.mean().detach(), # "state_action_value_actor": state_action_value_actor.mean().detach(), # "action_log_prob_actor": action_log_prob_actor.mean().detach(), # "next.state_value": next_state_value.mean().detach(), # "target_value": target_value.mean().detach(), }, [], ) return td_out def _rsample( self, dist, ): # separated only for the purpose of making the sampling # deterministic to compare methods return dist.rsample() def _sample_reparam(self, tensordict, params): """Given a policy param batch and input data in a tensordict, writes a reparam sample and log-prob key.""" with set_exploration_mode("random"): if self.gSDE: raise NotImplementedError # vmap doesn't support sampling, so we take it out from the vmap td_params = self.actor_network.get_dist_params( tensordict, params, ) if isinstance(self.actor_network, TensorDictSequential): sample_key = self.actor_network[-1].out_keys[0] tensordict_actor_dist = self.actor_network.build_dist_from_params( td_params ) else: sample_key = self.actor_network.out_keys[0] tensordict_actor_dist = self.actor_network.build_dist_from_params( td_params ) tensordict[sample_key] = self._rsample(tensordict_actor_dist) tensordict["sample_log_prob"] = tensordict_actor_dist.log_prob( tensordict[sample_key] ) return tensordict def _loss_actor_explicit(self, tensordict): tensordict_actor = tensordict.clone(False) actor_params = self.actor_network_params tensordict_actor = self._sample_reparam(tensordict_actor, actor_params) action_log_prob_actor = tensordict_actor["sample_log_prob"] tensordict_qval = tensordict_actor.select(*self.qvalue_network.in_keys).expand( self.num_qvalue_nets, *tensordict_actor.batch_size ) # for actor loss qvalue_params = self.qvalue_network_params.detach() tensordict_qval = vmap(self.qvalue_network)( tensordict_qval, qvalue_params, ) state_action_value_actor = tensordict_qval.get("state_action_value").squeeze(-1) state_action_value_actor = state_action_value_actor.min(0)[0] # E[alpha * log_pi(a) - Q(s, a)] where a is reparameterized loss_actor = ( self.alpha * action_log_prob_actor - state_action_value_actor ).mean() return loss_actor, action_log_prob_actor def _loss_qval_explicit(self, tensordict): next_tensordict = step_mdp(tensordict) next_tensordict = self._sample_reparam( next_tensordict, self.target_actor_network_params ) next_action_log_prob_qvalue = next_tensordict["sample_log_prob"] next_state_action_value_qvalue = vmap(self.qvalue_network, (None, 0))( next_tensordict, self.target_qvalue_network_params, )["state_action_value"].squeeze(-1) next_state_value = ( next_state_action_value_qvalue.min(0)[0] - self.alpha * next_action_log_prob_qvalue ) pred_val = vmap(self.qvalue_network, (None, 0))( tensordict, self.qvalue_network_params, )["state_action_value"].squeeze(-1) target_value = get_next_state_value( tensordict, gamma=self.gamma, pred_next_val=next_state_value, ) # 1/2 * E[Q(s,a) - (r + gamma * (Q(s,a)-alpha log pi(s, a))) loss_qval = ( distance_loss( pred_val, target_value.expand_as(pred_val), loss_function=self.loss_function, ) .mean(-1) .sum() * 0.5 ) td_error = (pred_val - target_value).pow(2) return loss_qval, td_error if __name__ == "__main__": from tensordict.nn import TensorDictModule from torch import nn from torchrl.data import BoundedTensorSpec # Tests the vectorized version of SAC-v2 against plain implementation from torchrl.modules import ProbabilisticActor, ValueOperator from torchrl.modules.distributions import TanhNormal torch.manual_seed(0) action_spec = BoundedTensorSpec(-1, 1, shape=(3,)) class Splitter(nn.Linear): def forward(self, x): loc, scale = super().forward(x).chunk(2, -1) return loc, scale.exp() actor_module = TensorDictModule( Splitter(6, 6), in_keys=["obs"], out_keys=["loc", "scale"] ) actor = ProbabilisticActor( spec=action_spec, in_keys=["loc", "scale"], module=actor_module, distribution_class=TanhNormal, default_interaction_mode="random", return_log_prob=False, ) class QVal(nn.Linear): def forward(self, s: Tensor, a: Tensor) -> Tensor: return super().forward(torch.cat([s, a], -1)) qvalue = ValueOperator(QVal(9, 1), in_keys=["obs", "action"]) _rsample_old = SACLoss._rsample def _rsample_new(self, dist): return torch.ones_like(_rsample_old(self, dist)) SACLoss._rsample = _rsample_new loss = SACLoss(actor, qvalue) for batch in ((), (2, 3)): td_input = TensorDict( { "obs": torch.rand(*batch, 6), "action": torch.rand(*batch, 3).clamp(-1, 1), "next": {"obs": torch.rand(*batch, 6)}, "reward": torch.rand(*batch, 1), "done": torch.zeros(*batch, 1, dtype=torch.bool), }, batch, ) loss._explicit = True loss0 = loss(td_input) loss._explicit = False loss1 = loss(td_input) print("a", loss0["loss_actor"] - loss1["loss_actor"]) print("q", loss0["loss_qvalue"] - loss1["loss_qvalue"])
import json import random import torch import numpy as np class NpEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() else: return super(NpEncoder, self).default(obj) class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def control_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True def stack_tensor_list(tensor_list): return np.array(tensor_list) def stack_tensor_dict_list(tensor_dict_list): """ Stack a list of dictionaries of {tensors or dictionary of tensors}. :param tensor_dict_list: a list of dictionaries of {tensors or dictionary of tensors}. :return: a dictionary of {stacked tensors or dictionary of stacked tensors} """ keys = list(tensor_dict_list[0].keys()) ret = dict() for k in keys: example = tensor_dict_list[0][k] if isinstance(example, dict): v = stack_tensor_dict_list([x[k] for x in tensor_dict_list]) else: v = stack_tensor_list([x[k] for x in tensor_dict_list]) ret[k] = v return ret def tensorize(var, device='cpu'): """ Convert input to torch.Tensor on desired device :param var: type either torch.Tensor or np.ndarray :param device: desired device for output (e.g. cpu, cuda) :return: torch.Tensor mapped to the device """ if type(var) == torch.Tensor: return var.to(device) elif type(var) == np.ndarray: return torch.from_numpy(var).float().to(device) elif type(var) == float: return torch.tensor(var).float() else: print("Variable type not compatible with function.") return None
""" Minimize bc loss (MLE, MSE, RWR etc.) with pytorch optimizers """ import logging logging.disable(logging.CRITICAL) import numpy as np import torch import time as timer from tqdm import tqdm from misc import tensorize class BC: def __init__(self, expert_paths, policy, epochs = 5, batch_size = 64, lr = 1e-3, optimizer = None, loss_type = 'MSE', # can be 'MLE' or 'MSE' save_logs = True, logger = None, set_transforms = False, *args, **kwargs, ): self.policy = policy self.expert_paths = expert_paths self.epochs = epochs self.mb_size = batch_size self.logger = logger self.loss_type = loss_type self.save_logs = save_logs self.device = self.policy.device assert (self.loss_type == 'MSE' or self.loss_type == 'MLE') if self.save_logs: assert not self.logger is None if set_transforms: in_shift, in_scale, out_shift, out_scale = self.compute_transformations() self.set_transformations(in_shift, in_scale, out_shift, out_scale) #self.set_variance_with_data(out_scale) # construct optimizer self.optimizer = torch.optim.Adam(self.policy.trainable_params, lr=lr) if optimizer is None else optimizer # Loss criterion if required if loss_type == 'MSE': self.loss_criterion = torch.nn.MSELoss() def compute_transformations(self): # get transformations if self.expert_paths == [] or self.expert_paths is None: in_shift, in_scale, out_shift, out_scale = None, None, None, None else: print(type(self.expert_paths)) if type(self.expert_paths) is list: observations = np.concatenate([path["observations"] for path in self.expert_paths]) actions = np.concatenate([path["actions"] for path in self.expert_paths]) else: # 'h5py._hl.files.File' observations = np.concatenate([self.expert_paths[k]['observations'] for k in self.expert_paths.keys()]) actions = np.concatenate([self.expert_paths[k]['actions'] for k in self.expert_paths.keys()]) in_shift, in_scale = np.mean(observations, axis=0), np.std(observations, axis=0) out_shift, out_scale = np.mean(actions, axis=0), np.std(actions, axis=0) return in_shift, in_scale, out_shift, out_scale def set_transformations(self, in_shift=None, in_scale=None, out_shift=None, out_scale=None): # set scalings in the target policy self.policy.set_transformations(in_shift, in_scale, out_shift, out_scale) def set_variance_with_data(self, out_scale): # set the variance of gaussian policy based on out_scale out_scale = tensorize(out_scale, device=self.policy.device) data_log_std = torch.log(out_scale + 1e-3) self.policy.set_log_std(data_log_std) def loss(self, data, idx=None): if self.loss_type == 'MLE': return self.mle_loss(data, idx) elif self.loss_type == 'MSE': return self.mse_loss(data, idx) else: print("Please use valid loss type") return None def mle_loss(self, data, idx): # use indices if provided (e.g. for mini-batching) # otherwise, use all the data idx = range(data['observations'].shape[0]) if idx is None else idx if type(data['observations']) == torch.Tensor: idx = torch.LongTensor(idx) obs = data['observations'][idx] act = data['expert_actions'][idx] mu, LL = self.policy.mean_LL(obs, act) # minimize negative log likelihood return -torch.mean(LL) def mse_loss(self, data, idx=None): idx = range(data['observations'].shape[0]) if idx is None else idx if type(data['observations']) is torch.Tensor: idx = torch.LongTensor(idx) obs = data['observations'][idx] act_expert = data['expert_actions'][idx] act_expert = tensorize(act_expert, device=self.policy.device) act_pi = self.policy.forward(obs) return self.loss_criterion(act_pi, act_expert.detach()) def fit(self, data, suppress_fit_tqdm=False, **kwargs): # data is a dict # keys should have "observations" and "expert_actions" validate_keys = all([k in data.keys() for k in ["observations", "expert_actions"]]) assert validate_keys is True ts = timer.time() num_samples = data["observations"].shape[0] # log stats before if self.save_logs: loss_val = self.loss(data, idx=range(num_samples)).to('cpu').data.numpy().ravel()[0] self.logger.log_scalar("train/loss_before", loss_val, step=0) print('BC loss before', loss_val) # train loop for ep in config_tqdm(range(self.epochs), suppress_fit_tqdm): avg_loss = 0.0 step = 0 for mb in range(int(num_samples / self.mb_size)): rand_idx = np.random.choice(num_samples, size=self.mb_size) self.optimizer.zero_grad() loss = self.loss(data, idx=rand_idx) loss.backward() self.optimizer.step() avg_loss = (avg_loss*step + loss.item())/(step+1) step += 1 if self.save_logs: self.logger.log_scalar("train/bc_loss", avg_loss, step=ep+1) # log stats after if self.save_logs: loss_val = self.loss(data, idx=range(num_samples)).to('cpu').data.numpy().ravel()[0] self.logger.log_scalar("train/loss_after", loss_val, step=self.epochs) print('BC val loss', loss_val) def train(self, **kwargs): if not hasattr(self, 'data'): observations = np.concatenate([path["observations"] for path in self.expert_paths]) expert_actions = np.concatenate([path["actions"] for path in self.expert_paths]) observations = tensorize(observations, device=self.policy.device) expert_actions = tensorize(expert_actions, self.policy.device) self.data = dict(observations=observations, expert_actions=expert_actions) self.fit(self.data, **kwargs) def train_h5(self, **kwargs): if not hasattr(self, 'data'): observations = np.concatenate([self.expert_paths[k]['observations'] for k in self.expert_paths.keys()]) expert_actions = np.concatenate([self.expert_paths[k]['actions'] for k in self.expert_paths.keys()]) observations = tensorize(observations, device=self.policy.device) expert_actions = tensorize(expert_actions, self.policy.device) self.data = dict(observations=observations, expert_actions=expert_actions) self.fit(self.data, **kwargs) def config_tqdm(range_inp, suppress_tqdm=False): if suppress_tqdm: return range_inp else: return tqdm(range_inp)
""" Job script to learn policy using BC """ import os import time from os import environ environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID' environ['MKL_THREADING_LAYER']='GNU' import pickle import yaml import hydra import gym import wandb import numpy as np from omegaconf import DictConfig, OmegaConf, ListConfig from batch_norm_mlp import BatchNormMLP from gmm_policy import GMMPolicy from behavior_cloning import BC from misc import control_seed, \ bcolors, stack_tensor_dict_list from torchrl.record.loggers.wandb import WandbLogger from robohive.logger.grouped_datasets import Trace as Trace def evaluate_policy( policy, env, num_episodes, epoch, horizon=None, gamma=1, percentile=[], get_full_dist=False, eval_logger=None, device='cpu', seed=123, verbose=True, ): env.seed(seed) horizon = env.horizon if horizon is None else horizon mean_eval, std, min_eval, max_eval = 0.0, 0.0, -1e8, -1e8 ep_returns = np.zeros(num_episodes) policy.eval() paths = [] for ep in range(num_episodes): observations=[] actions=[] rewards=[] agent_infos = [] env_infos = [] o = env.reset() t, done = 0, False while t < horizon and (done == False): a = policy.get_action(o)[1]['evaluation'] next_o, r, done, env_info = env.step(a) ep_returns[ep] += (gamma ** t) * r observations.append(o) actions.append(a) rewards.append(r) agent_infos.append(None) env_infos.append(env_info) o = next_o t += 1 if verbose: print("Episode: {}; Reward: {}".format(ep, ep_returns[ep])) path = dict( observations=np.array(observations), actions=np.array(actions), rewards=np.array(rewards), #agent_infos=stack_tensor_dict_list(agent_infos), env_infos=stack_tensor_dict_list(env_infos), terminated=done ) paths.append(path) mean_eval, std = np.mean(ep_returns), np.std(ep_returns) min_eval, max_eval = np.amin(ep_returns), np.amax(ep_returns) base_stats = [mean_eval, std, min_eval, max_eval] percentile_stats = [] for p in percentile: percentile_stats.append(np.percentile(ep_returns, p)) full_dist = ep_returns if get_full_dist is True else None success = env.evaluate_success(paths, logger=None) ## Don't use the mj_envs logging function if not eval_logger is None: rwd_sparse = np.mean([np.mean(p['env_infos']['rwd_sparse']) for p in paths]) # return rwd/step rwd_dense = np.mean([np.sum(p['env_infos']['rwd_dense'])/env.horizon for p in paths]) # return rwd/step eval_logger.log_scalar('eval/rwd_sparse', rwd_sparse, step=epoch) eval_logger.log_scalar('eval/rwd_dense', rwd_dense, step=epoch) eval_logger.log_scalar('eval/success', success, step=epoch) return [base_stats, percentile_stats, full_dist], success class ObservationWrapper: def __init__(self, env_name, visual_keys, encoder): self.env = gym.make(env_name, visual_keys=visual_keys) self.horizon = self.env.horizon self.encoder = encoder def reset(self, **kwargs): obs = self.env.reset(**kwargs) return self.get_obs(obs) def step(self, action): observation, reward, terminated, info = self.env.step(action) return self.get_obs(observation), reward, terminated, info def get_obs(self, observation=None): if self.encoder == 'proprio': proprio_vec = self.env.get_proprioception()[1] return proprio_vec if len(self.env.visual_keys) > 0: visual_obs = self.env.get_exteroception() final_visual_obs = None for key in self.env.visual_keys: if final_visual_obs is None: final_visual_obs = visual_obs[key] else: final_visual_obs = np.concatenate((final_visual_obs, visual_obs[key]), axis=-1) _, proprio_vec, _ = self.env.get_proprioception() observation = np.concatenate((final_visual_obs, proprio_vec)) else: observation = self.env.get_obs() if observation is None else observation return observation def seed(self, seed): return self.env.seed(seed) def set_env_state(self, state_dict): return self.env.set_env_state(state_dict) def evaluate_success(self, paths, logger=None): return self.env.evaluate_success(paths, logger=logger) def make_env(env_name, cam_name, encoder, from_pixels): if from_pixels: visual_keys = [] assert encoder in ["vc1s", "vc1l", "r3m18", "rrl18", "rrl50", "r3m50", "2d", "1d", "proprio"] if encoder == "1d" or encoder == "2d": visual_keys = [f'rgb:{cam_name}:84x84:{encoder}'] elif encoder == 'proprio': visual_keys = [] else: # cam_name is a list of cameras if type(cam_name) == ListConfig: visual_keys = [] for cam in cam_name: visual_keys.append(f'rgb:{cam}:224x224:{encoder}') else: visual_keys = [f'rgb:{cam_name}:224x224:{encoder}'] print(f"Using visual keys {visual_keys}") env = ObservationWrapper(env_name, visual_keys=visual_keys, encoder=encoder) else: env = gym.make(env_name) return env @hydra.main(config_name="bc.yaml", config_path="config") def main(job_data: DictConfig): OmegaConf.resolve(job_data) job_data['policy_size'] = tuple(job_data['policy_size']) exp_start = time.time() OUT_DIR = os.getcwd() if not os.path.exists(OUT_DIR): os.mkdir(OUT_DIR) if not os.path.exists(OUT_DIR+'/iterations'): os.mkdir(OUT_DIR+'/iterations') if not os.path.exists(OUT_DIR+'/logs'): os.mkdir(OUT_DIR+'/logs') if job_data['from_pixels'] == False: job_data['env_name'] = job_data['env_name'].replace('_v2d', '') #exp_name = OUT_DIR.split('/')[-1] ## TODO: Customizer for logging # Unpack args and make files for easy access #logger = DataLog() exp_name = job_data['env_name'] + '_pixels' + str(job_data['from_pixels']) + '_' + job_data['encoder'] logger = WandbLogger( exp_name=exp_name, config=job_data, name=exp_name, project=job_data['wandb_project'], entity=job_data['wandb_entity'], mode=job_data['wandb_mode'], ) ENV_NAME = job_data['env_name'] EXP_FILE = OUT_DIR + '/job_data.yaml' SEED = job_data['seed'] # base cases if 'device' not in job_data.keys(): job_data['device'] = 'cpu' assert 'data_file' in job_data.keys() yaml_config = OmegaConf.to_yaml(job_data) with open(EXP_FILE, 'w') as file: yaml.dump(yaml_config, file) env = make_env( env_name=job_data["env_name"], cam_name=job_data["cam_name"], encoder=job_data["encoder"], from_pixels=job_data["from_pixels"] ) # =============================================================================== # Setup functions and environment # =============================================================================== control_seed(SEED) env.seed(SEED) paths_trace = Trace.load(job_data['data_file']) bc_paths = [] for key, path in paths_trace.items(): path_dict = {} traj_len = path['observations'].shape[0] obs_list = [] ep_reward = 0.0 env.reset() init_state_dict = {} t0 = time.time() for key, value in path['env_infos']['state'].items(): init_state_dict[key] = value[0] env.set_env_state(init_state_dict) obs = env.get_obs() for step in range(traj_len-1): next_obs, reward, done, env_info = env.step(path["actions"][step]) ep_reward += reward obs_list.append(obs) obs = next_obs t1 = time.time() obs_np = np.stack(obs_list, axis=0) path_dict['observations'] = obs_np # [:-1] path_dict['actions'] = path['actions'][()][:-1] path_dict['env_infos'] = {'solved': path['env_infos']['solved'][()]} print(f"Time to convert one trajectory: {(t1-t0)/60:4.2f}") print("Converted episode reward:", ep_reward) print("Original episode reward:", np.sum(path["rewards"])) print(key, path_dict['observations'].shape, path_dict['actions'].shape) bc_paths.append(path_dict) expert_success = env.evaluate_success(bc_paths) print(f"{bcolors.BOLD}{bcolors.OKGREEN}{exp_name} {bcolors.ENDC}") print(f"{bcolors.BOLD}{bcolors.OKGREEN}Expert Success Rate: {expert_success}. {bcolors.ENDC}") observation_dim = bc_paths[0]['observations'].shape[-1] action_dim = bc_paths[0]['actions'].shape[-1] print(f'Policy obs dim {observation_dim} act dim {action_dim}') policy = GMMPolicy( # network_kwargs input_size=observation_dim, output_size=action_dim, hidden_size=job_data['policy_size'][0], num_layers=len(job_data['policy_size']), min_std=0.0001, num_modes=5, activation="softplus", low_eval_noise=False, # loss_kwargs ) set_transforms = False # =============================================================================== # Model training # =============================================================================== print(f"{bcolors.OKBLUE}Training BC{bcolors.ENDC}") policy.to(job_data['device']) bc_agent = BC( bc_paths, policy, epochs=job_data['eval_every_n'], batch_size=job_data['bc_batch_size'], lr=job_data['bc_lr'], loss_type='MLE', save_logs=True, logger=logger, set_transforms=set_transforms, ) for ind in range(0, job_data['bc_epochs'], job_data['eval_every_n']): policy.train() bc_agent.train() # bc_agent.train_h5() policy.eval() _, success_rate = evaluate_policy( env=env, policy=policy, eval_logger=logger, epoch=ind+job_data['eval_every_n'], num_episodes=job_data['eval_traj'], seed=job_data['seed'] + 123, verbose=True, device='cpu', ) policy.to(job_data['device']) exp_end = time.time() print(f"{bcolors.BOLD}{bcolors.OKGREEN}Success Rate: {success_rate}. Time: {(exp_end - exp_start)/60:4.2f} minutes.{bcolors.ENDC}") exp_end = time.time() print(f"{bcolors.BOLD}{bcolors.OKGREEN}Success Rate: {success_rate}. Time: {(exp_end - exp_start)/60:4.2f} minutes.{bcolors.ENDC}") # pickle.dump(bc_agent, open(OUT_DIR + '/iterations/agent_final.pickle', 'wb')) pickle.dump(policy, open(OUT_DIR + '/iterations/policy_final.pickle', 'wb')) wandb.finish() if __name__ == '__main__': main()
import torch import numpy as np import torch.nn as nn from torch.autograd import Variable class FCNetworkWithBatchNorm(nn.Module): def __init__(self, obs_dim, act_dim, hidden_sizes=(64,64), nonlinearity='relu', # either 'tanh' or 'relu' dropout=0, # probability to dropout activations (0 means no dropout) *args, **kwargs, ): super(FCNetworkWithBatchNorm, self).__init__() self.obs_dim = obs_dim self.act_dim = act_dim assert type(hidden_sizes) == tuple self.layer_sizes = (obs_dim, ) + hidden_sizes + (act_dim, ) self.device = 'cpu' # hidden layers self.fc_layers = nn.ModuleList([nn.Linear(self.layer_sizes[i], self.layer_sizes[i+1]) \ for i in range(len(self.layer_sizes) -1)]) self.nonlinearity = torch.relu if nonlinearity == 'relu' else torch.tanh self.input_batchnorm = nn.BatchNorm1d(num_features=obs_dim) self.dropout = nn.Dropout(dropout) def forward(self, x): out = x.to(self.device) out = self.input_batchnorm(out) for i in range(len(self.fc_layers)-1): out = self.fc_layers[i](out) out = self.dropout(out) out = self.nonlinearity(out) out = self.fc_layers[-1](out) return out def to(self, device): self.device = device return super().to(device) def set_transformations(self, *args, **kwargs): pass class BatchNormMLP(nn.Module): def __init__(self, env_spec=None, action_dim=None, observation_dim=None, hidden_sizes=(64,64), min_log_std=-3, init_log_std=0, seed=None, nonlinearity='relu', dropout=0, device='cpu', *args, **kwargs, ): """ :param env_spec: specifications of the env (see utils/gym_env.py) :param hidden_sizes: network hidden layer sizes (currently 2 layers only) :param min_log_std: log_std is clamped at this value and can't go below :param init_log_std: initial log standard deviation :param seed: random seed """ super(BatchNormMLP, self).__init__() self.device = device self.n = env_spec.observation_dim if observation_dim is None else observation_dim # number of states self.m = env_spec.action_dim if action_dim is None else action_dim # number of actions self.min_log_std = min_log_std # Set seed # ------------------------ if seed is not None: torch.manual_seed(seed) np.random.seed(seed) # Policy network # ------------------------ self.model = FCNetworkWithBatchNorm(self.n, self.m, hidden_sizes, nonlinearity, dropout) # make weights small for param in list(self.model.parameters())[-2:]: # only last layer param.data = 1e-2 * param.data self.log_std = Variable(torch.ones(self.m) * init_log_std, requires_grad=True) self.trainable_params = list(self.model.parameters()) + [self.log_std] self.model.eval() # Easy access variables # ------------------------- self.log_std_val = np.float64(self.log_std.data.numpy().ravel()) self.param_shapes = [p.data.numpy().shape for p in self.trainable_params] self.param_sizes = [p.data.numpy().size for p in self.trainable_params] self.d = np.sum(self.param_sizes) # total number of params # Placeholders # ------------------------ self.obs_var = Variable(torch.randn(self.n), requires_grad=False) # Utility functions # ============================================ def to(self, device): super().to(device) self.model = self.model.to(device) print(self.model) self.device = device return self # Main functions # ============================================ def get_action(self, observation): o = np.float32(observation.reshape(1, -1)) self.obs_var.data = torch.from_numpy(o) mean = self.model(self.obs_var).to('cpu').data.numpy().ravel() noise = np.exp(self.log_std_val) * np.random.randn(self.m) action = mean + noise return [action, {'mean': mean, 'log_std': self.log_std_val, 'evaluation': mean}] # ============================================ def forward(self, observations): if type(observations) == np.ndarray: observations = torch.from_numpy(observations).float() assert type(observations) == torch.Tensor observations = observations.to(self.device) out = self.model(observations) return out
import torch import numpy as np import torch.nn as nn import torch.distributions as D import torch.nn.functional as F class GMMPolicy(nn.Module): def __init__(self, # network_kwargs input_size, output_size, hidden_size=1024, num_layers=2, min_std=0.0001, num_modes=5, activation="softplus", low_eval_noise=False, # loss_kwargs loss_coef=1.0): super().__init__() self.num_modes = num_modes self.output_size = output_size self.min_std = min_std if num_layers > 0: sizes = [input_size] + [hidden_size] * num_layers layers = [nn.BatchNorm1d(num_features=input_size)] for i in range(num_layers): layers += [nn.Linear(sizes[i], sizes[i+1]), nn.ReLU()] layers += [nn.Linear(sizes[-2], sizes[-1])] self.share = nn.Sequential(*layers) else: self.share = nn.Identity() self.mean_layer = nn.Linear(hidden_size, output_size * num_modes) self.logstd_layer = nn.Linear(hidden_size, output_size * num_modes) self.logits_layer = nn.Linear(hidden_size, num_modes) self.low_eval_noise = low_eval_noise self.loss_coef = loss_coef if activation == "softplus": self.actv = F.softplus else: self.actv = torch.exp self.trainable_params = list(self.share.parameters()) + \ list(self.mean_layer.parameters()) + \ list(self.logstd_layer.parameters()) + \ list(self.logits_layer.parameters()) def to(self, device): super().to(device) self.device = device return self def forward_fn(self, x): # x: (B, input_size) share = self.share(x) means = self.mean_layer(share).view(-1, self.num_modes, self.output_size) means = torch.tanh(means) logits = self.logits_layer(share) if self.training or not self.low_eval_noise: logstds = self.logstd_layer(share).view(-1, self.num_modes, self.output_size) stds = self.actv(logstds) + self.min_std else: stds = torch.ones_like(means) * 1e-4 return means, stds, logits def get_action(self, observation): o = np.float32(observation.reshape(1, -1)) o = torch.from_numpy(o).to(self.device) means, stds, logits = self.forward_fn(o) compo = D.Normal(loc=means, scale=stds) compo = D.Independent(compo, 1) mix = D.Categorical(logits=logits) gmm = D.MixtureSameFamily(mixture_distribution=mix, component_distribution=compo) action = gmm.sample() mean = gmm.mean mean = mean.detach().cpu().numpy().ravel() return [action, {'mean': mean, 'std': stds, 'evaluation': mean}] def forward(self, x): means, scales, logits = self.forward_fn(x) compo = D.Normal(loc=means, scale=scales) compo = D.Independent(compo, 1) mix = D.Categorical(logits=logits) gmm = D.MixtureSameFamily(mixture_distribution=mix, component_distribution=compo) return gmm def mean_LL(self, x, target): gmm_dist = self.forward(x) # return mean, log_prob of the gmm return gmm_dist.mean, gmm_dist.log_prob(target) def loss_fn(self, gmm, target, reduction='mean'): log_probs = gmm.log_prob(target) loss = -log_probs if reduction == 'mean': return loss.mean() * self.loss_coef elif reduction == 'none': return loss * self.loss_coef elif reduction == 'sum': return loss.sum() * self.loss_coef else: raise NotImplementedError
import torch from rlhive.rl_envs import RoboHiveEnv from rlhive.sim_algos.helpers.rrl_transform import RRLTransform from torchrl.envs import ( CatTensors, DoubleToFloat, ObservationNorm, R3MTransform, SelectTransform, TransformedEnv, ) from torchrl.envs.transforms import Compose, FlattenObservation, RewardScaling from torchrl.envs.utils import set_exploration_mode def make_env(task, visual_transform, reward_scaling, device): assert visual_transform in ("rrl", "r3m") base_env = RoboHiveEnv(task, device=device) env = make_transformed_env( env=base_env, reward_scaling=reward_scaling, visual_transform=visual_transform ) print(env) # exit() return env def make_transformed_env( env, reward_scaling=5.0, visual_transform="r3m", stats=None, ): """ Apply transforms to the env (such as reward scaling and state normalization) """ env = TransformedEnv(env, SelectTransform("solved", "pixels", "observation")) if visual_transform == "rrl": vec_keys = ["rrl_vec"] selected_keys = ["observation", "rrl_vec"] env.append_transform( Compose( RRLTransform("resnet50", in_keys=["pixels"], download=True), FlattenObservation(-2, -1, in_keys=vec_keys), ) ) # Necessary to Compose R3MTransform with FlattenObservation; Track bug: https://github.com/pytorch/rl/issues/802 elif visual_transform == "r3m": vec_keys = ["r3m_vec"] selected_keys = ["observation", "r3m_vec"] env.append_transform( Compose( R3MTransform("resnet50", in_keys=["pixels"], download=True), FlattenObservation(-2, -1, in_keys=vec_keys), ) ) # Necessary to Compose R3MTransform with FlattenObservation; Track bug: https://github.com/pytorch/rl/issues/802 else: raise NotImplementedError env.append_transform(RewardScaling(loc=0.0, scale=reward_scaling)) out_key = "observation_vector" env.append_transform(CatTensors(in_keys=selected_keys, out_key=out_key)) # we normalize the states if stats is None: _stats = {"loc": 0.0, "scale": 1.0} else: _stats = stats env.append_transform( ObservationNorm(**_stats, in_keys=[out_key], standard_normal=True) ) env.append_transform(DoubleToFloat(in_keys=[out_key], in_keys_inv=[])) return env env = make_env( task="visual_franka_slide_random-v3", reward_scaling=5.0, device=torch.device("cuda:0"), visual_transform="rrl", ) with torch.no_grad(), set_exploration_mode("random"): td = env.reset() td = env.rand_step() print(td)
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import gc import os import hydra import numpy as np import torch import torch.cuda import tqdm import wandb from omegaconf import DictConfig from rlhive.rl_envs import RoboHiveEnv from rlhive.sim_algos.helpers.rrl_transform import RRLTransform # from torchrl.objectives import SACLoss from sac_loss import SACLoss from torch import nn, optim from torchrl.collectors import MultiaSyncDataCollector from torchrl.data import TensorDictPrioritizedReplayBuffer, TensorDictReplayBuffer from torchrl.data.replay_buffers.storages import LazyMemmapStorage from torchrl.envs import ( CatTensors, DoubleToFloat, ObservationNorm, R3MTransform, SelectTransform, TransformedEnv, ) from torchrl.envs.transforms import Compose, FlattenObservation, RewardScaling from torchrl.envs.utils import set_exploration_mode from torchrl.modules import MLP, NormalParamWrapper, SafeModule from torchrl.modules.distributions import TanhNormal from torchrl.modules.tensordict_module.actors import ProbabilisticActor, ValueOperator from torchrl.objectives import SoftUpdate from torchrl.trainers import Recorder os.environ["WANDB_MODE"] = "offline" # offline sync. TODO: Remove this behavior def make_env(task, visual_transform, reward_scaling, device, from_pixels): assert visual_transform in ("rrl", "r3m") base_env = RoboHiveEnv(task, device=device) env = make_transformed_env( env=base_env, reward_scaling=reward_scaling, visual_transform=visual_transform, from_pixels=from_pixels, ) print(env) return env def make_transformed_env( env, from_pixels, reward_scaling=5.0, visual_transform="r3m", stats=None, ): """ Apply transforms to the env (such as reward scaling and state normalization) """ if from_pixels: env = TransformedEnv(env, SelectTransform("solved", "pixels", "observation")) if visual_transform == "rrl": vec_keys = ["rrl_vec"] selected_keys = ["observation", "rrl_vec"] env.append_transform( Compose( RRLTransform("resnet50", in_keys=["pixels"], download=True), FlattenObservation(-2, -1, in_keys=vec_keys), ) ) # Necessary to Compose R3MTransform with FlattenObservation; Track bug: https://github.com/pytorch/rl/issues/802 elif visual_transform == "r3m": vec_keys = ["r3m_vec"] selected_keys = ["observation", "r3m_vec"] env.append_transform( Compose( R3MTransform("resnet50", in_keys=["pixels"], download=True), FlattenObservation(-2, -1, in_keys=vec_keys), ) ) # Necessary to Compose R3MTransform with FlattenObservation; Track bug: https://github.com/pytorch/rl/issues/802 else: raise NotImplementedError else: env = TransformedEnv(env, SelectTransform("solved", "observation")) selected_keys = ["observation"] env.append_transform(RewardScaling(loc=0.0, scale=reward_scaling)) out_key = "observation_vector" env.append_transform(CatTensors(in_keys=selected_keys, out_key=out_key)) # we normalize the states if stats is None: _stats = {"loc": 0.0, "scale": 1.0} else: _stats = stats env.append_transform( ObservationNorm(**_stats, in_keys=[out_key], standard_normal=True) ) env.append_transform(DoubleToFloat(in_keys=[out_key], in_keys_inv=[])) return env def make_recorder( task: str, frame_skip: int, record_interval: int, actor_model_explore: object, eval_traj: int, env_configs: dict, ): test_env = make_env(task=task, **env_configs) recorder_obj = Recorder( record_frames=eval_traj * test_env.horizon, frame_skip=frame_skip, policy_exploration=actor_model_explore, recorder=test_env, exploration_mode="mean", record_interval=record_interval, log_keys=["reward", "solved"], out_keys={"reward": "r_evaluation", "solved": "success"}, ) return recorder_obj def make_replay_buffer( prb: bool, buffer_size: int, buffer_scratch_dir: str, device: torch.device, make_replay_buffer: int = 3, ): if prb: replay_buffer = TensorDictPrioritizedReplayBuffer( alpha=0.7, beta=0.5, pin_memory=False, prefetch=make_replay_buffer, storage=LazyMemmapStorage( buffer_size, scratch_dir=buffer_scratch_dir, device=device, ), ) else: replay_buffer = TensorDictReplayBuffer( pin_memory=False, prefetch=make_replay_buffer, storage=LazyMemmapStorage( buffer_size, scratch_dir=buffer_scratch_dir, device=device, ), ) return replay_buffer def evaluate_success(env_success_fn, td_record: dict, eval_traj: int): td_record["success"] = td_record["success"].reshape((eval_traj, -1)) paths = [] for solved_traj in td_record["success"]: path = {"env_infos": {"solved": solved_traj.data.cpu().numpy()}} paths.append(path) success_percentage = env_success_fn(paths) return success_percentage @hydra.main(config_name="sac.yaml", config_path="config") def main(args: DictConfig): device = ( torch.device("cuda:0") if torch.cuda.is_available() and torch.cuda.device_count() > 0 and args.device == "cuda:0" else torch.device("cpu") ) torch.manual_seed(args.seed) np.random.seed(args.seed) # Create Environment env_configs = { "reward_scaling": args.reward_scaling, "visual_transform": args.visual_transform, "device": args.device, "from_pixels": args.from_pixels, } train_env = make_env(task=args.task, **env_configs) # Create Agent # Define Actor Network in_keys = ["observation_vector"] action_spec = train_env.action_spec actor_net_kwargs = { "num_cells": [256, 256], "out_features": 2 * action_spec.shape[-1], "activation_class": nn.ReLU, } actor_net = MLP(**actor_net_kwargs) dist_class = TanhNormal dist_kwargs = { "min": action_spec.space.minimum, "max": action_spec.space.maximum, "tanh_loc": False, } actor_net = NormalParamWrapper( actor_net, scale_mapping=f"biased_softplus_{1.0}", scale_lb=0.1, ) in_keys_actor = in_keys actor_module = SafeModule( actor_net, in_keys=in_keys_actor, out_keys=[ "loc", "scale", ], ) actor = ProbabilisticActor( spec=action_spec, in_keys=["loc", "scale"], module=actor_module, distribution_class=dist_class, distribution_kwargs=dist_kwargs, default_interaction_mode="random", return_log_prob=False, ) # Define Critic Network qvalue_net_kwargs = { "num_cells": [256, 256], "out_features": 1, "activation_class": nn.ReLU, } qvalue_net = MLP( **qvalue_net_kwargs, ) qvalue = ValueOperator( in_keys=["action"] + in_keys, module=qvalue_net, ) model = nn.ModuleList([actor, qvalue]).to(device) # add forward pass for initialization with proof env proof_env = make_env(task=args.task, **env_configs) # init nets with torch.no_grad(), set_exploration_mode("random"): td = proof_env.reset() td = td.to(device) for net in model: net(td) del td proof_env.close() actor_model_explore = model[0] # Create SAC loss loss_module = SACLoss( actor_network=model[0], qvalue_network=model[1], num_qvalue_nets=2, gamma=args.gamma, loss_function="smooth_l1", ) # Define Target Network Updater target_net_updater = SoftUpdate(loss_module, args.target_update_polyak) # Make Off-Policy Collector collector = MultiaSyncDataCollector( create_env_fn=[train_env], policy=actor_model_explore, total_frames=args.total_frames, max_frames_per_traj=args.frames_per_batch, frames_per_batch=args.env_per_collector * args.frames_per_batch, init_random_frames=args.init_random_frames, reset_at_each_iter=False, postproc=None, split_trajs=True, devices=[device], # device for execution passing_devices=[device], # device where data will be stored and passed seed=None, pin_memory=False, update_at_each_batch=False, exploration_mode="random", ) collector.set_seed(args.seed) # Make Replay Buffer replay_buffer = make_replay_buffer( prb=args.prb, buffer_size=args.buffer_size, buffer_scratch_dir=args.buffer_scratch_dir, device=device, ) # Trajectory recorder for evaluation recorder = make_recorder( task=args.task, frame_skip=args.frame_skip, record_interval=args.record_interval, actor_model_explore=actor_model_explore, eval_traj=args.eval_traj, env_configs=env_configs, ) # Optimizers params = list(loss_module.parameters()) + [loss_module.log_alpha] optimizer_actor = optim.Adam(params, lr=args.lr, weight_decay=args.weight_decay) rewards = [] rewards_eval = [] # Main loop target_net_updater.init_() collected_frames = 0 episodes = 0 pbar = tqdm.tqdm(total=args.total_frames) r0 = None loss = None with wandb.init(project="SAC_TorchRL", name=args.exp_name, config=args): for i, tensordict in enumerate(collector): # update weights of the inference policy collector.update_policy_weights_() if r0 is None: r0 = tensordict["reward"].sum(-1).mean().item() pbar.update(tensordict.numel()) # extend the replay buffer with the new data if "mask" in tensordict.keys(): # if multi-step, a mask is present to help filter padded values current_frames = tensordict["mask"].sum() tensordict = tensordict[tensordict.get("mask").squeeze(-1)] else: tensordict = tensordict.view(-1) current_frames = tensordict.numel() collected_frames += current_frames episodes += args.env_per_collector replay_buffer.extend(tensordict.cpu()) # optimization steps if collected_frames >= args.init_random_frames: ( total_losses, actor_losses, q_losses, alpha_losses, alphas, entropies, ) = ([], [], [], [], [], []) for _ in range( args.env_per_collector * args.frames_per_batch * args.utd_ratio ): # sample from replay buffer sampled_tensordict = replay_buffer.sample(args.batch_size).clone() loss_td = loss_module(sampled_tensordict) actor_loss = loss_td["loss_actor"] q_loss = loss_td["loss_qvalue"] alpha_loss = loss_td["loss_alpha"] loss = actor_loss + q_loss + alpha_loss optimizer_actor.zero_grad() loss.backward() optimizer_actor.step() # update qnet_target params target_net_updater.step() # update priority if args.prb: replay_buffer.update_priority(sampled_tensordict) total_losses.append(loss.item()) actor_losses.append(actor_loss.item()) q_losses.append(q_loss.item()) alpha_losses.append(alpha_loss.item()) alphas.append(loss_td["alpha"].item()) entropies.append(loss_td["entropy"].item()) rewards.append( (i, tensordict["reward"].sum().item() / args.env_per_collector) ) wandb.log( { "train_reward": rewards[-1][1], "collected_frames": collected_frames, "episodes": episodes, } ) if loss is not None: wandb.log( { "total_loss": np.mean(total_losses), "actor_loss": np.mean(actor_losses), "q_loss": np.mean(q_losses), "alpha_loss": np.mean(alpha_losses), "alpha": np.mean(alphas), "entropy": np.mean(entropies), } ) td_record = recorder(None) success_percentage = evaluate_success( env_success_fn=train_env.evaluate_success, td_record=td_record, eval_traj=args.eval_traj, ) if td_record is not None: rewards_eval.append( ( i, td_record["total_r_evaluation"] / 1, # divide by number of eval worker ) ) wandb.log({"test_reward": rewards_eval[-1][1]}) wandb.log({"success": success_percentage}) if len(rewards_eval): pbar.set_description( f"reward: {rewards[-1][1]: 4.4f} (r0 = {r0: 4.4f}), test reward: {rewards_eval[-1][1]: 4.4f}" ) del tensordict gc.collect() collector.shutdown() if __name__ == "__main__": main()
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from numbers import Number from typing import Union import numpy as np import torch from tensordict.nn import TensorDictSequential from tensordict.tensordict import TensorDict, TensorDictBase from torch import Tensor from torchrl.envs.utils import set_exploration_mode, step_mdp from torchrl.modules import SafeModule from torchrl.objectives.common import LossModule from torchrl.objectives.utils import ( distance_loss, next_state_value as get_next_state_value, ) try: from functorch import vmap FUNCTORCH_ERR = "" _has_functorch = True except ImportError as err: FUNCTORCH_ERR = str(err) _has_functorch = False class SACLoss(LossModule): """SAC Loss module. Args: actor_network (SafeModule): the actor to be trained qvalue_network (SafeModule): a single Q-value network that will be multiplicated as many times as needed. num_qvalue_nets (int, optional): Number of Q-value networks to be trained. Default is 10. gamma (Number, optional): gamma decay factor. Default is 0.99. priotity_key (str, optional): Key where to write the priority value for prioritized replay buffers. Default is `"td_error"`. loss_function (str, optional): loss function to be used for the Q-value. Can be one of `"smooth_l1"`, "l2", "l1", Default is "smooth_l1". alpha_init (float, optional): initial entropy multiplier. Default is 1.0. min_alpha (float, optional): min value of alpha. Default is 0.1. max_alpha (float, optional): max value of alpha. Default is 10.0. fixed_alpha (bool, optional): whether alpha should be trained to match a target entropy. Default is :obj:`False`. target_entropy (Union[str, Number], optional): Target entropy for the stochastic policy. Default is "auto". delay_qvalue (bool, optional): Whether to separate the target Q value networks from the Q value networks used for data collection. Default is :obj:`False`. gSDE (bool, optional): Knowing if gSDE is used is necessary to create random noise variables. Default is False """ delay_actor: bool = False _explicit: bool = True def __init__( self, actor_network: SafeModule, qvalue_network: SafeModule, num_qvalue_nets: int = 2, gamma: Number = 0.99, priotity_key: str = "td_error", loss_function: str = "smooth_l1", alpha_init: float = 1.0, min_alpha: float = 0.1, max_alpha: float = 10.0, fixed_alpha: bool = False, target_entropy: Union[str, Number] = "auto", delay_qvalue: bool = True, gSDE: bool = False, ): if not _has_functorch: raise ImportError( f"Failed to import functorch with error message:\n{FUNCTORCH_ERR}" ) super().__init__() self.convert_to_functional( actor_network, "actor_network", create_target_params=self.delay_actor, funs_to_decorate=["forward", "get_dist_params"], ) # let's make sure that actor_network has `return_log_prob` set to True self.actor_network.return_log_prob = True self.delay_qvalue = delay_qvalue self.convert_to_functional( qvalue_network, "qvalue_network", num_qvalue_nets, create_target_params=self.delay_qvalue, compare_against=list(actor_network.parameters()), ) self.num_qvalue_nets = num_qvalue_nets self.register_buffer("gamma", torch.tensor(gamma)) self.priority_key = priotity_key self.loss_function = loss_function try: device = next(self.parameters()).device except AttributeError: device = torch.device("cpu") self.register_buffer("alpha_init", torch.tensor(alpha_init, device=device)) self.register_buffer( "min_log_alpha", torch.tensor(min_alpha, device=device).log() ) self.register_buffer( "max_log_alpha", torch.tensor(max_alpha, device=device).log() ) self.fixed_alpha = fixed_alpha if fixed_alpha: self.register_buffer( "log_alpha", torch.tensor(math.log(alpha_init), device=device) ) else: self.register_parameter( "log_alpha", torch.nn.Parameter(torch.tensor(math.log(alpha_init), device=device)), ) if target_entropy == "auto": if actor_network.spec["action"] is None: raise RuntimeError( "Cannot infer the dimensionality of the action. Consider providing " "the target entropy explicitely or provide the spec of the " "action tensor in the actor network." ) target_entropy = -float(np.prod(actor_network.spec["action"].shape)) self.register_buffer( "target_entropy", torch.tensor(target_entropy, device=device) ) self.gSDE = gSDE @property def alpha(self): self.log_alpha.data.clamp_(self.min_log_alpha, self.max_log_alpha) with torch.no_grad(): alpha = self.log_alpha.exp() return alpha def forward(self, tensordict: TensorDictBase) -> TensorDictBase: if self._explicit: # slow but explicit version return self._forward_explicit(tensordict) else: return self._forward_vectorized(tensordict) def _loss_alpha(self, log_pi: Tensor) -> Tensor: if torch.is_grad_enabled() and not log_pi.requires_grad: raise RuntimeError( "expected log_pi to require gradient for the alpha loss)" ) if self.target_entropy is not None: # we can compute this loss even if log_alpha is not a parameter alpha_loss = -self.log_alpha.exp() * (log_pi.detach() + self.target_entropy) else: # placeholder alpha_loss = torch.zeros_like(log_pi) return alpha_loss def _forward_vectorized(self, tensordict: TensorDictBase) -> TensorDictBase: obs_keys = self.actor_network.in_keys tensordict_select = tensordict.select( "reward", "done", "next", *obs_keys, "action" ) actor_params = torch.stack( [self.actor_network_params, self.target_actor_network_params], 0 ) tensordict_actor_grad = tensordict_select.select( *obs_keys ) # to avoid overwriting keys next_td_actor = step_mdp(tensordict_select).select( *self.actor_network.in_keys ) # next_observation -> tensordict_actor = torch.stack([tensordict_actor_grad, next_td_actor], 0) tensordict_actor = tensordict_actor.contiguous() with set_exploration_mode("random"): if self.gSDE: tensordict_actor.set( "_eps_gSDE", torch.zeros(tensordict_actor.shape, device=tensordict_actor.device), ) # vmap doesn't support sampling, so we take it out from the vmap td_params = vmap(self.actor_network.get_dist_params)( tensordict_actor, actor_params, ) if isinstance(self.actor_network, TensorDictSequential): sample_key = self.actor_network[-1].out_keys[0] tensordict_actor_dist = self.actor_network.build_dist_from_params( td_params ) else: sample_key = self.actor_network.out_keys[0] tensordict_actor_dist = self.actor_network.build_dist_from_params( td_params ) tensordict_actor[sample_key] = self._rsample(tensordict_actor_dist) tensordict_actor["sample_log_prob"] = tensordict_actor_dist.log_prob( tensordict_actor[sample_key] ) # repeat tensordict_actor to match the qvalue size _actor_loss_td = ( tensordict_actor[0] .select(*self.qvalue_network.in_keys) .expand(self.num_qvalue_nets, *tensordict_actor[0].batch_size) ) # for actor loss _qval_td = tensordict_select.select(*self.qvalue_network.in_keys).expand( self.num_qvalue_nets, *tensordict_select.select(*self.qvalue_network.in_keys).batch_size, ) # for qvalue loss _next_val_td = ( tensordict_actor[1] .select(*self.qvalue_network.in_keys) .expand(self.num_qvalue_nets, *tensordict_actor[1].batch_size) ) # for next value estimation tensordict_qval = torch.cat( [ _actor_loss_td, _next_val_td, _qval_td, ], 0, ) # cat params q_params_detach = self.qvalue_network_params.detach() qvalue_params = torch.cat( [ q_params_detach, self.target_qvalue_network_params, self.qvalue_network_params, ], 0, ) tensordict_qval = vmap(self.qvalue_network)( tensordict_qval, qvalue_params, ) state_action_value = tensordict_qval.get("state_action_value").squeeze(-1) ( state_action_value_actor, next_state_action_value_qvalue, state_action_value_qvalue, ) = state_action_value.split( [self.num_qvalue_nets, self.num_qvalue_nets, self.num_qvalue_nets], dim=0, ) sample_log_prob = tensordict_actor.get("sample_log_prob").squeeze(-1) ( action_log_prob_actor, next_action_log_prob_qvalue, ) = sample_log_prob.unbind(0) # E[alpha * log_pi(a) - Q(s, a)] where a is reparameterized loss_actor = -( state_action_value_actor.min(0)[0] - self.alpha * action_log_prob_actor ).mean() next_state_value = ( next_state_action_value_qvalue.min(0)[0] - self.alpha * next_action_log_prob_qvalue ) target_value = get_next_state_value( tensordict, gamma=self.gamma, pred_next_val=next_state_value, ) pred_val = state_action_value_qvalue td_error = (pred_val - target_value).pow(2) loss_qval = ( distance_loss( pred_val, target_value.expand_as(pred_val), loss_function=self.loss_function, ) .mean(-1) .sum() * 0.5 ) tensordict.set("td_error", td_error.detach().max(0)[0]) loss_alpha = self._loss_alpha(sample_log_prob) if not loss_qval.shape == loss_actor.shape: raise RuntimeError( f"QVal and actor loss have different shape: {loss_qval.shape} and {loss_actor.shape}" ) td_out = TensorDict( { "loss_actor": loss_actor.mean(), "loss_qvalue": loss_qval.mean(), "loss_alpha": loss_alpha.mean(), "alpha": self.alpha.detach(), "entropy": -sample_log_prob.mean().detach(), "state_action_value_actor": state_action_value_actor.mean().detach(), "action_log_prob_actor": action_log_prob_actor.mean().detach(), "next.state_value": next_state_value.mean().detach(), "target_value": target_value.mean().detach(), }, [], ) return td_out def _forward_explicit(self, tensordict: TensorDictBase) -> TensorDictBase: loss_actor, sample_log_prob = self._loss_actor_explicit(tensordict.clone(False)) loss_qval, td_error = self._loss_qval_explicit(tensordict.clone(False)) tensordict.set("td_error", td_error.detach().max(0)[0]) loss_alpha = self._loss_alpha(sample_log_prob) td_out = TensorDict( { "loss_actor": loss_actor.mean(), "loss_qvalue": loss_qval.mean(), "loss_alpha": loss_alpha.mean(), "alpha": self.alpha.detach(), "entropy": -sample_log_prob.mean().detach(), # "state_action_value_actor": state_action_value_actor.mean().detach(), # "action_log_prob_actor": action_log_prob_actor.mean().detach(), # "next.state_value": next_state_value.mean().detach(), # "target_value": target_value.mean().detach(), }, [], ) return td_out def _rsample( self, dist, ): # separated only for the purpose of making the sampling # deterministic to compare methods return dist.rsample() def _sample_reparam(self, tensordict, params): """Given a policy param batch and input data in a tensordict, writes a reparam sample and log-prob key.""" with set_exploration_mode("random"): if self.gSDE: raise NotImplementedError # vmap doesn't support sampling, so we take it out from the vmap td_params = self.actor_network.get_dist_params( tensordict, params, ) if isinstance(self.actor_network, TensorDictSequential): sample_key = self.actor_network[-1].out_keys[0] tensordict_actor_dist = self.actor_network.build_dist_from_params( td_params ) else: sample_key = self.actor_network.out_keys[0] tensordict_actor_dist = self.actor_network.build_dist_from_params( td_params ) tensordict[sample_key] = self._rsample(tensordict_actor_dist) tensordict["sample_log_prob"] = tensordict_actor_dist.log_prob( tensordict[sample_key] ) return tensordict def _loss_actor_explicit(self, tensordict): tensordict_actor = tensordict.clone(False) actor_params = self.actor_network_params tensordict_actor = self._sample_reparam(tensordict_actor, actor_params) action_log_prob_actor = tensordict_actor["sample_log_prob"] tensordict_qval = tensordict_actor.select(*self.qvalue_network.in_keys).expand( self.num_qvalue_nets, *tensordict_actor.batch_size ) # for actor loss qvalue_params = self.qvalue_network_params.detach() tensordict_qval = vmap(self.qvalue_network)( tensordict_qval, qvalue_params, ) state_action_value_actor = tensordict_qval.get("state_action_value").squeeze(-1) state_action_value_actor = state_action_value_actor.min(0)[0] # E[alpha * log_pi(a) - Q(s, a)] where a is reparameterized loss_actor = ( self.alpha * action_log_prob_actor - state_action_value_actor ).mean() return loss_actor, action_log_prob_actor def _loss_qval_explicit(self, tensordict): next_tensordict = step_mdp(tensordict) next_tensordict = self._sample_reparam( next_tensordict, self.target_actor_network_params ) next_action_log_prob_qvalue = next_tensordict["sample_log_prob"] next_state_action_value_qvalue = vmap(self.qvalue_network, (None, 0))( next_tensordict, self.target_qvalue_network_params, )["state_action_value"].squeeze(-1) next_state_value = ( next_state_action_value_qvalue.min(0)[0] - self.alpha * next_action_log_prob_qvalue ) pred_val = vmap(self.qvalue_network, (None, 0))( tensordict, self.qvalue_network_params, )["state_action_value"].squeeze(-1) target_value = get_next_state_value( tensordict, gamma=self.gamma, pred_next_val=next_state_value, ) # 1/2 * E[Q(s,a) - (r + gamma * (Q(s,a)-alpha log pi(s, a))) loss_qval = ( distance_loss( pred_val, target_value.expand_as(pred_val), loss_function=self.loss_function, ) .mean(-1) .sum() * 0.5 ) td_error = (pred_val - target_value).pow(2) return loss_qval, td_error if __name__ == "__main__": from tensordict.nn import TensorDictModule from torch import nn from torchrl.data import BoundedTensorSpec # Tests the vectorized version of SAC-v2 against plain implementation from torchrl.modules import ProbabilisticActor, ValueOperator from torchrl.modules.distributions import TanhNormal torch.manual_seed(0) action_spec = BoundedTensorSpec(-1, 1, shape=(3,)) class Splitter(nn.Linear): def forward(self, x): loc, scale = super().forward(x).chunk(2, -1) return loc, scale.exp() actor_module = TensorDictModule( Splitter(6, 6), in_keys=["obs"], out_keys=["loc", "scale"] ) actor = ProbabilisticActor( spec=action_spec, in_keys=["loc", "scale"], module=actor_module, distribution_class=TanhNormal, default_interaction_mode="random", return_log_prob=False, ) class QVal(nn.Linear): def forward(self, s: Tensor, a: Tensor) -> Tensor: return super().forward(torch.cat([s, a], -1)) qvalue = ValueOperator(QVal(9, 1), in_keys=["obs", "action"]) _rsample_old = SACLoss._rsample def _rsample_new(self, dist): return torch.ones_like(_rsample_old(self, dist)) SACLoss._rsample = _rsample_new loss = SACLoss(actor, qvalue) for batch in ((), (2, 3)): td_input = TensorDict( { "obs": torch.rand(*batch, 6), "action": torch.rand(*batch, 3).clamp(-1, 1), "next": {"obs": torch.rand(*batch, 6)}, "reward": torch.rand(*batch, 1), "done": torch.zeros(*batch, 1, dtype=torch.bool), }, batch, ) loss._explicit = True loss0 = loss(td_input) loss._explicit = False loss1 = loss(td_input) print("a", loss0["loss_actor"] - loss1["loss_actor"]) print("q", loss0["loss_qvalue"] - loss1["loss_qvalue"])
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import dataclasses import hydra import torch.cuda from hydra.core.config_store import ConfigStore from rlhive.rl_envs import RoboHiveEnv from torchrl.envs import ( CatTensors, DoubleToFloat, EnvCreator, ObservationNorm, ParallelEnv, R3MTransform, SelectTransform, TransformedEnv, ) from torchrl.envs.transforms import Compose, FlattenObservation, RewardScaling from torchrl.envs.utils import set_exploration_mode from torchrl.modules import OrnsteinUhlenbeckProcessWrapper from torchrl.record import VideoRecorder from torchrl.trainers.helpers.collectors import ( make_collector_offpolicy, OffPolicyCollectorConfig, ) from torchrl.trainers.helpers.envs import ( EnvConfig, initialize_observation_norm_transforms, retrieve_observation_norms_state_dict, ) from torchrl.trainers.helpers.logger import LoggerConfig from torchrl.trainers.helpers.losses import LossConfig, make_redq_loss from torchrl.trainers.helpers.models import make_redq_model, REDQModelConfig from torchrl.trainers.helpers.replay_buffer import make_replay_buffer, ReplayArgsConfig from torchrl.trainers.helpers.trainers import make_trainer, TrainerConfig from torchrl.trainers.loggers.utils import generate_exp_name, get_logger def make_env( task, reward_scaling, device, obs_norm_state_dict=None, action_dim_gsde=None, state_dim_gsde=None, ): base_env = RoboHiveEnv(task, device=device) env = make_transformed_env(env=base_env, reward_scaling=reward_scaling) if obs_norm_state_dict is not None: obs_norm = ObservationNorm( **obs_norm_state_dict, in_keys=["observation_vector"] ) env.append_transform(obs_norm) if action_dim_gsde is not None: env.append_transform( gSDENoise(action_dim=action_dim_gsde, state_dim=state_dim_gsde) ) return env def make_transformed_env( env, reward_scaling=5.0, stats=None, ): """ Apply transforms to the env (such as reward scaling and state normalization) """ env = TransformedEnv(env, SelectTransform("solved", "pixels", "observation")) env.append_transform( Compose( R3MTransform("resnet50", in_keys=["pixels"], download=True), FlattenObservation(-2, -1, in_keys=["r3m_vec"]), ) ) # Necessary to Compose R3MTransform with FlattenObservation; Track bug: https://github.com/pytorch/rl/issues/802 env.append_transform(RewardScaling(loc=0.0, scale=reward_scaling)) selected_keys = ["r3m_vec", "observation"] out_key = "observation_vector" env.append_transform(CatTensors(in_keys=selected_keys, out_key=out_key)) # we normalize the states if stats is None: _stats = {"loc": 0.0, "scale": 1.0} else: _stats = stats env.append_transform( ObservationNorm(**_stats, in_keys=[out_key], standard_normal=True) ) env.append_transform(DoubleToFloat(in_keys=[out_key], in_keys_inv=[])) return env config_fields = [ (config_field.name, config_field.type, config_field) for config_cls in ( TrainerConfig, OffPolicyCollectorConfig, EnvConfig, LossConfig, REDQModelConfig, LoggerConfig, ReplayArgsConfig, ) for config_field in dataclasses.fields(config_cls) ] Config = dataclasses.make_dataclass(cls_name="Config", fields=config_fields) cs = ConfigStore.instance() cs.store(name="config", node=Config) DEFAULT_REWARD_SCALING = { "Hopper-v1": 5, "Walker2d-v1": 5, "HalfCheetah-v1": 5, "cheetah": 5, "Ant-v2": 5, "Humanoid-v2": 20, "humanoid": 100, } @hydra.main(version_base=None, config_path=".", config_name="config") def main(cfg: "DictConfig"): # noqa: F821 device = ( torch.device("cpu") if torch.cuda.device_count() == 0 else torch.device("cuda:0") ) exp_name = generate_exp_name("REDQ", cfg.exp_name) logger = get_logger( logger_type=cfg.logger, logger_name="redq_logging", experiment_name=exp_name ) key, init_env_steps = None, None if not cfg.vecnorm and cfg.norm_stats: if not hasattr(cfg, "init_env_steps"): raise AttributeError("init_env_steps missing from arguments.") key = ("next", "observation_vector") init_env_steps = cfg.init_env_steps proof_env = make_env( task=cfg.env_name, reward_scaling=cfg.reward_scaling, device=device, ) initialize_observation_norm_transforms( proof_environment=proof_env, num_iter=init_env_steps, key=key ) _, obs_norm_state_dict = retrieve_observation_norms_state_dict(proof_env)[0] print(proof_env) model = make_redq_model( proof_env, cfg=cfg, device=device, in_keys=["observation_vector"], ) loss_module, target_net_updater = make_redq_loss(model, cfg) actor_model_explore = model[0] if cfg.ou_exploration: if cfg.gSDE: raise RuntimeError("gSDE and ou_exploration are incompatible") actor_model_explore = OrnsteinUhlenbeckProcessWrapper( actor_model_explore, annealing_num_steps=cfg.annealing_frames, sigma=cfg.ou_sigma, theta=cfg.ou_theta, ).to(device) if device == torch.device("cpu"): # mostly for debugging actor_model_explore.share_memory() if cfg.gSDE: with torch.no_grad(), set_exploration_mode("random"): # get dimensions to build the parallel env proof_td = actor_model_explore(proof_env.reset().to(device)) action_dim_gsde, state_dim_gsde = proof_td.get("_eps_gSDE").shape[-2:] del proof_td else: action_dim_gsde, state_dim_gsde = None, None proof_env.close() create_env_fn = make_env( # Pass EnvBase instead of the create_env_fn task=cfg.env_name, reward_scaling=cfg.reward_scaling, device=device, obs_norm_state_dict=obs_norm_state_dict, action_dim_gsde=action_dim_gsde, state_dim_gsde=state_dim_gsde, ) collector = make_collector_offpolicy( make_env=create_env_fn, actor_model_explore=actor_model_explore, cfg=cfg, # make_env_kwargs=[ # {"device": device} if device >= 0 else {} # for device in args.env_rendering_devices # ], ) replay_buffer = make_replay_buffer(device, cfg) # recorder = transformed_env_constructor( # cfg, # video_tag=video_tag, # norm_obs_only=True, # obs_norm_state_dict=obs_norm_state_dict, # logger=logger, # use_env_creator=False, # )() recorder = make_env( task=cfg.env_name, reward_scaling=cfg.reward_scaling, device=device, obs_norm_state_dict=obs_norm_state_dict, action_dim_gsde=action_dim_gsde, state_dim_gsde=state_dim_gsde, ) # remove video recorder from recorder to have matching state_dict keys if cfg.record_video: recorder_rm = TransformedEnv(recorder.base_env) for transform in recorder.transform: if not isinstance(transform, VideoRecorder): recorder_rm.append_transform(transform.clone()) else: recorder_rm = recorder if isinstance(create_env_fn, ParallelEnv): recorder_rm.load_state_dict(create_env_fn.state_dict()["worker0"]) create_env_fn.close() elif isinstance(create_env_fn, EnvCreator): recorder_rm.load_state_dict(create_env_fn().state_dict()) else: recorder_rm.load_state_dict(create_env_fn.state_dict()) # reset reward scaling for t in recorder.transform: if isinstance(t, RewardScaling): t.scale.fill_(1.0) t.loc.fill_(0.0) trainer = make_trainer( collector, loss_module, recorder, target_net_updater, actor_model_explore, replay_buffer, logger, cfg, ) final_seed = collector.set_seed(cfg.seed) print(f"init seed: {cfg.seed}, final seed: {final_seed}") trainer.train() return (logger.log_dir, trainer._log_dict) if __name__ == "__main__": main()
""" This is a job script for running policy gradient algorithms on gym tasks. Separate job scripts are provided to run few other algorithms - For DAPG see here: https://github.com/aravindr93/hand_dapg/tree/master/dapg/examples - For model-based NPG see here: https://github.com/aravindr93/mjrl/tree/master/mjrl/algos/model_accel """ from mjrl.utils.gym_env import GymEnv from mjrl.policies.gaussian_mlp import MLP from mjrl.baselines.mlp_baseline import MLPBaseline from mjrl.algos.npg_cg import NPG from mjrl.algos.batch_reinforce import BatchREINFORCE from mjrl.algos.ppo_clip import PPO from mjrl.utils.train_agent import train_agent from mjrl.utils.logger import DataLog from omegaconf import open_dict import os import json import gym # import mjrl.envs import time as timer import robohive from robohive.envs.env_variants import register_env_variant def train_loop(job_data) -> None: if 'env_hyper_params' in job_data.keys(): job_data.env = register_env_variant(job_data.env, job_data.env_hyper_params) e = GymEnv(job_data.env) policy_size = tuple(eval(job_data.policy_size)) vf_hidden_size = tuple(eval(job_data.vf_hidden_size)) policy = MLP(e.spec, hidden_sizes=policy_size, seed=job_data.seed, init_log_std=job_data.init_log_std, min_log_std=job_data.min_log_std) baseline = MLPBaseline(e.spec, reg_coef=1e-3, batch_size=job_data.vf_batch_size, hidden_sizes=vf_hidden_size, epochs=job_data.vf_epochs, learn_rate=job_data.vf_learn_rate) # Construct the algorithm if job_data.algorithm == 'NPG': # Other hyperparameters (like number of CG steps) can be specified in config for pass through # or default hyperparameters will be used agent = NPG(e, policy, baseline, normalized_step_size=job_data.rl_step_size, seed=job_data.seed, save_logs=True, **job_data.alg_hyper_params) elif job_data.algorithm == 'VPG': agent = BatchREINFORCE(e, policy, baseline, learn_rate=job_data.rl_step_size, seed=job_data.seed, save_logs=True, **job_data.alg_hyper_params) elif job_data.algorithm == 'NVPG': agent = BatchREINFORCE(e, policy, baseline, desired_kl=job_data.rl_step_size, seed=job_data.seed, save_logs=True, **job_data.alg_hyper_params) elif job_data.algorithm == 'PPO': # There are many hyperparameters for PPO. They can be specified in config for pass through # or defaults in the PPO algorithm will be used agent = PPO(e, policy, baseline, save_logs=True, **job_data.alg_hyper_params) else: NotImplementedError("Algorithm not found") # Update logger if WandB in Config if 'wandb_params' in job_data.keys() and job_data['wandb_params']['use_wandb']==True: if 'wandb_logdir' in job_data['wandb_params']: job_data['wandb_params']['wandb_logdir'] = job_data['wandb_params']['wandb_logdir'] else: with open_dict(job_data): job_data.wandb_params.wandb_logdir = os.getcwd() agent.logger = DataLog(**job_data['wandb_params'], wandb_config=job_data) print("========================================") print("Starting policy learning") print("========================================") ts = timer.time() train_agent(job_name='.', agent=agent, seed=job_data.seed, niter=job_data.rl_num_iter, gamma=job_data.rl_gamma, gae_lambda=job_data.rl_gae, num_cpu=job_data.num_cpu, sample_mode=job_data.sample_mode, num_traj=job_data.rl_num_traj, num_samples=job_data.rl_num_samples, save_freq=job_data.save_freq, evaluation_rollouts=job_data.eval_rollouts) print("========================================") print("Job Finished. Time taken = %f" % (timer.time()-ts)) print("========================================")
""" This is a launcher script for launching mjrl training using hydra """ import os import time as timer import hydra from omegaconf import DictConfig, OmegaConf from mjrl_job_script import train_loop # =============================================================================== # Process Inputs and configure job # =============================================================================== @hydra.main(config_name="hydra_npg_config", config_path="config") def configure_jobs(job_data): print("========================================") print("Job Configuration") print("========================================") OmegaConf.resolve(job_data) # resolve configs assert 'algorithm' in job_data.keys() assert any([job_data.algorithm == a for a in ['NPG', 'NVPG', 'VPG', 'PPO']]) assert 'sample_mode' in job_data.keys() assert any([job_data.sample_mode == m for m in ['samples', 'trajectories']]) job_data.alg_hyper_params = dict() if 'alg_hyper_params' not in job_data.keys() else job_data.alg_hyper_params with open('job_config.yaml', 'w') as fp: OmegaConf.save(config=job_data, f=fp.name) if job_data.sample_mode == 'trajectories': assert 'rl_num_traj' in job_data.keys() job_data.rl_num_samples = 0 # will be ignored elif job_data.sample_mode == 'samples': assert 'rl_num_samples' in job_data.keys() job_data.rl_num_traj = 0 # will be ignored else: print("Unknown sampling mode. Choose either trajectories or samples") exit() print(OmegaConf.to_yaml(job_data, resolve=True)) train_loop(job_data) if __name__ == "__main__": configure_jobs()
import robohive import click DESC=""" Script to render trajectories embeded in the env" """ @click.command(help=DESC) @click.option('-s', '--suite', type=str, help='environment suite to train', default="arms") @click.option('-l', '--launcher', type=click.Choice(['', None, "local", "slurm"]), default='') @click.option('-cn', '--config_name', type=str, default=None) @click.option('-cp', '--config_path', type=str, default='config') def get_train_cmd(suite, launcher, config_name, config_path): # Resolve Suite if suite=="multitask_": envs = ",".join(robohive.robohive_multitask_suite) if config_name==None: config_name="hydra_kitchen_config.yaml" elif suite=="arms": envs = ",".join(robohive.robohive_arm_suite) if config_name==None: config_name="hydra_arms_config.yaml" elif suite=="hands": envs = ",".join(robohive.robohive_hand_suite) if config_name==None: config_name="hydra_hand_config.yaml" elif suite=="quads": envs = ",".join(robohive.robohive_quad_suite) if config_name==None: config_name="hydra_quads_config.yaml" elif suite=="myobase": envs = ",".join(robohive.robohive_myobase_suite) if config_name==None: config_name="hydra_myo_config.yaml" elif suite=="myochallenge": envs = ",".join(robohive.robohive_myochal_suite) if config_name==None: config_name="hydra_myo_config.yaml" elif suite=="myodm": envs = ",".join(robohive.robohive_myodm_suite) if config_name==None: config_name="hydra_myo_config.yaml" else: raise ValueError(f"Unsupported suite:{suite}") # Resolve launcher if launcher=='' or launcher==None: launcher_spec = '' else: launcher_spec = f"--multirun hydra/output={launcher} hydra/launcher={launcher}" # Get final training command print(f"To train NPG via mjrl on {suite} suite, run the following command: ") print(f"python hydra_mjrl_launcher.py --config-path {config_path} --config-name {config_name} {launcher_spec} env={envs} seed=1,2,3") if __name__ == '__main__': get_train_cmd()
#!/usr/bin/env python """ MIT License Copyright (c) 2017 Guillaume Papin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. A wrapper script around clang-format, suitable for linting multiple files and to use for continuous integration. This is an alternative API for the clang-format command line. It runs over multiple files and directories in parallel. A diff output is produced and a sensible exit code is returned. """ import argparse import difflib import fnmatch import multiprocessing import os import signal import subprocess import sys import traceback from functools import partial try: from subprocess import DEVNULL # py3k except ImportError: DEVNULL = open(os.devnull, "wb") DEFAULT_EXTENSIONS = "c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx,cu" class ExitStatus: SUCCESS = 0 DIFF = 1 TROUBLE = 2 def list_files(files, recursive=False, extensions=None, exclude=None): if extensions is None: extensions = [] if exclude is None: exclude = [] out = [] for file in files: if recursive and os.path.isdir(file): for dirpath, dnames, fnames in os.walk(file): fpaths = [os.path.join(dirpath, fname) for fname in fnames] for pattern in exclude: # os.walk() supports trimming down the dnames list # by modifying it in-place, # to avoid unnecessary directory listings. dnames[:] = [ x for x in dnames if not fnmatch.fnmatch(os.path.join(dirpath, x), pattern) ] fpaths = [x for x in fpaths if not fnmatch.fnmatch(x, pattern)] for f in fpaths: ext = os.path.splitext(f)[1][1:] if ext in extensions: out.append(f) else: out.append(file) return out def make_diff(file, original, reformatted): return list( difflib.unified_diff( original, reformatted, fromfile=f"{file}\t(original)", tofile=f"{file}\t(reformatted)", n=3, ) ) class DiffError(Exception): def __init__(self, message, errs=None): super().__init__(message) self.errs = errs or [] class UnexpectedError(Exception): def __init__(self, message, exc=None): super().__init__(message) self.formatted_traceback = traceback.format_exc() self.exc = exc def run_clang_format_diff_wrapper(args, file): try: ret = run_clang_format_diff(args, file) return ret except DiffError: raise except Exception as e: raise UnexpectedError(f"{file}: {e.__class__.__name__}: {e}", e) def run_clang_format_diff(args, file): try: with open(file, encoding="utf-8") as f: original = f.readlines() except OSError as exc: raise DiffError(str(exc)) invocation = [args.clang_format_executable, file] # Use of utf-8 to decode the process output. # # Hopefully, this is the correct thing to do. # # It's done due to the following assumptions (which may be incorrect): # - clang-format will returns the bytes read from the files as-is, # without conversion, and it is already assumed that the files use utf-8. # - if the diagnostics were internationalized, they would use utf-8: # > Adding Translations to Clang # > # > Not possible yet! # > Diagnostic strings should be written in UTF-8, # > the client can translate to the relevant code page if needed. # > Each translation completely replaces the format string # > for the diagnostic. # > -- http://clang.llvm.org/docs/InternalsManual.html#internals-diag-translation try: proc = subprocess.Popen( invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, encoding="utf-8", ) except OSError as exc: raise DiffError( f"Command '{subprocess.list2cmdline(invocation)}' failed to start: {exc}" ) proc_stdout = proc.stdout proc_stderr = proc.stderr # hopefully the stderr pipe won't get full and block the process outs = list(proc_stdout.readlines()) errs = list(proc_stderr.readlines()) proc.wait() if proc.returncode: raise DiffError( "Command '{}' returned non-zero exit status {}".format( subprocess.list2cmdline(invocation), proc.returncode ), errs, ) return make_diff(file, original, outs), errs def bold_red(s): return "\x1b[1m\x1b[31m" + s + "\x1b[0m" def colorize(diff_lines): def bold(s): return "\x1b[1m" + s + "\x1b[0m" def cyan(s): return "\x1b[36m" + s + "\x1b[0m" def green(s): return "\x1b[32m" + s + "\x1b[0m" def red(s): return "\x1b[31m" + s + "\x1b[0m" for line in diff_lines: if line[:4] in ["--- ", "+++ "]: yield bold(line) elif line.startswith("@@ "): yield cyan(line) elif line.startswith("+"): yield green(line) elif line.startswith("-"): yield red(line) else: yield line def print_diff(diff_lines, use_color): if use_color: diff_lines = colorize(diff_lines) sys.stdout.writelines(diff_lines) def print_trouble(prog, message, use_colors): error_text = "error:" if use_colors: error_text = bold_red(error_text) print(f"{prog}: {error_text} {message}", file=sys.stderr) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--clang-format-executable", metavar="EXECUTABLE", help="path to the clang-format executable", default="clang-format", ) parser.add_argument( "--extensions", help=f"comma separated list of file extensions (default: {DEFAULT_EXTENSIONS})", default=DEFAULT_EXTENSIONS, ) parser.add_argument( "-r", "--recursive", action="store_true", help="run recursively over directories", ) parser.add_argument("files", metavar="file", nargs="+") parser.add_argument("-q", "--quiet", action="store_true") parser.add_argument( "-j", metavar="N", type=int, default=0, help="run N clang-format jobs in parallel (default number of cpus + 1)", ) parser.add_argument( "--color", default="auto", choices=["auto", "always", "never"], help="show colored diff (default: auto)", ) parser.add_argument( "-e", "--exclude", metavar="PATTERN", action="append", default=[], help="exclude paths matching the given glob-like pattern(s) from recursive search", ) args = parser.parse_args() # use default signal handling, like diff return SIGINT value on ^C # https://bugs.python.org/issue14229#msg156446 signal.signal(signal.SIGINT, signal.SIG_DFL) try: signal.SIGPIPE except AttributeError: # compatibility, SIGPIPE does not exist on Windows pass else: signal.signal(signal.SIGPIPE, signal.SIG_DFL) colored_stdout = False colored_stderr = False if args.color == "always": colored_stdout = True colored_stderr = True elif args.color == "auto": colored_stdout = sys.stdout.isatty() colored_stderr = sys.stderr.isatty() version_invocation = [args.clang_format_executable, "--version"] try: subprocess.check_call(version_invocation, stdout=DEVNULL) except subprocess.CalledProcessError as e: print_trouble(parser.prog, str(e), use_colors=colored_stderr) return ExitStatus.TROUBLE except OSError as e: print_trouble( parser.prog, f"Command '{subprocess.list2cmdline(version_invocation)}' failed to start: {e}", use_colors=colored_stderr, ) return ExitStatus.TROUBLE retcode = ExitStatus.SUCCESS files = list_files( args.files, recursive=args.recursive, exclude=args.exclude, extensions=args.extensions.split(","), ) if not files: return njobs = args.j if njobs == 0: njobs = multiprocessing.cpu_count() + 1 njobs = min(len(files), njobs) if njobs == 1: # execute directly instead of in a pool, # less overhead, simpler stacktraces it = (run_clang_format_diff_wrapper(args, file) for file in files) pool = None else: pool = multiprocessing.Pool(njobs) it = pool.imap_unordered(partial(run_clang_format_diff_wrapper, args), files) while True: try: outs, errs = next(it) except StopIteration: break except DiffError as e: print_trouble(parser.prog, str(e), use_colors=colored_stderr) retcode = ExitStatus.TROUBLE sys.stderr.writelines(e.errs) except UnexpectedError as e: print_trouble(parser.prog, str(e), use_colors=colored_stderr) sys.stderr.write(e.formatted_traceback) retcode = ExitStatus.TROUBLE # stop at the first unexpected error, # something could be very wrong, # don't process all files unnecessarily if pool: pool.terminate() break else: sys.stderr.writelines(errs) if outs == []: continue if not args.quiet: print_diff(outs, use_color=colored_stdout) if retcode == ExitStatus.SUCCESS: retcode = ExitStatus.DIFF return retcode if __name__ == "__main__": sys.exit(main())
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Training script for permute MNIST experiment. """ from __future__ import print_function import argparse import os import sys import math import time import datetime import numpy as np import tensorflow as tf from copy import deepcopy from six.moves import cPickle as pickle from utils.data_utils import construct_permute_mnist from utils.utils import get_sample_weights, sample_from_dataset, update_episodic_memory, concatenate_datasets, samples_for_each_class, sample_from_dataset_icarl, compute_fgt, update_reservior from utils.vis_utils import plot_acc_multiple_runs, plot_histogram, snapshot_experiment_meta_data, snapshot_experiment_eval from model import Model ############################################################### ################ Some definitions ############################# ### These will be edited by the command line options ########## ############################################################### ## Training Options NUM_RUNS = 10 # Number of experiments to average over TRAIN_ITERS = 5000 # Number of training iterations per task BATCH_SIZE = 16 LEARNING_RATE = 1e-3 RANDOM_SEED = 1234 VALID_OPTIMS = ['SGD', 'MOMENTUM', 'ADAM'] OPTIM = 'SGD' OPT_POWER = 0.9 OPT_MOMENTUM = 0.9 VALID_ARCHS = ['FC-S', 'FC-B'] ARCH = 'FC-S' ## Model options MODELS = ['VAN', 'PI', 'EWC', 'MAS', 'RWALK', 'A-GEM', 'S-GEM', 'FTR_EXT', 'PNN', 'ER'] #List of valid models IMP_METHOD = 'EWC' SYNAP_STGTH = 75000 FISHER_EMA_DECAY = 0.9 # Exponential moving average decay factor for Fisher computation (online Fisher) FISHER_UPDATE_AFTER = 10 # Number of training iterations for which the F_{\theta}^t is computed (see Eq. 10 in RWalk paper) SAMPLES_PER_CLASS = 25 # Number of samples per task INPUT_FEATURE_SIZE = 784 IMG_HEIGHT = 28 IMG_WIDTH = 28 IMG_CHANNELS = 1 TOTAL_CLASSES = 10 # Total number of classes in the dataset EPS_MEM_BATCH_SIZE = 256 DEBUG_EPISODIC_MEMORY = False USE_GPU = True K_FOR_CROSS_VAL = 3 TIME_MY_METHOD = False COUNT_VIOLATIONS = False MEASURE_PERF_ON_EPS_MEMORY = False ## Logging, saving and testing options LOG_DIR = './permute_mnist_results' ## Evaluation options ## Num Tasks NUM_TASKS = 20 MULTI_TASK = False def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Script for permutted mnist experiment.") parser.add_argument("--cross-validate-mode", action="store_true", help="If option is chosen then snapshoting after each batch is disabled") parser.add_argument("--online-cross-val", action="store_true", help="If option is chosen then enable the online cross validation of the learning rate") parser.add_argument("--train-single-epoch", action="store_true", help="If option is chosen then train for single epoch") parser.add_argument("--eval-single-head", action="store_true", help="If option is chosen then evaluate on a single head setting.") parser.add_argument("--arch", type=str, default=ARCH, help="Network Architecture for the experiment.\ \n \nSupported values: %s"%(VALID_ARCHS)) parser.add_argument("--num-runs", type=int, default=NUM_RUNS, help="Total runs/ experiments over which accuracy is averaged.") parser.add_argument("--train-iters", type=int, default=TRAIN_ITERS, help="Number of training iterations for each task.") parser.add_argument("--batch-size", type=int, default=BATCH_SIZE, help="Mini-batch size for each task.") parser.add_argument("--random-seed", type=int, default=RANDOM_SEED, help="Random Seed.") parser.add_argument("--learning-rate", type=float, default=LEARNING_RATE, help="Starting Learning rate for each task.") parser.add_argument("--optim", type=str, default=OPTIM, help="Optimizer for the experiment. \ \n \nSupported values: %s"%(VALID_OPTIMS)) parser.add_argument("--imp-method", type=str, default=IMP_METHOD, help="Model to be used for LLL. \ \n \nSupported values: %s"%(MODELS)) parser.add_argument("--synap-stgth", type=float, default=SYNAP_STGTH, help="Synaptic strength for the regularization.") parser.add_argument("--fisher-ema-decay", type=float, default=FISHER_EMA_DECAY, help="Exponential moving average decay for Fisher calculation at each step.") parser.add_argument("--fisher-update-after", type=int, default=FISHER_UPDATE_AFTER, help="Number of training iterations after which the Fisher will be updated.") parser.add_argument("--mem-size", type=int, default=SAMPLES_PER_CLASS, help="Number of samples per class from previous tasks.") parser.add_argument("--eps-mem-batch", type=int, default=EPS_MEM_BATCH_SIZE, help="Number of samples per class from previous tasks.") parser.add_argument("--examples-per-task", type=int, default=1000, help="Number of examples per task.") parser.add_argument("--log-dir", type=str, default=LOG_DIR, help="Directory where the plots and model accuracies will be stored.") return parser.parse_args() def train_task_sequence(model, sess, args): """ Train and evaluate LLL system such that we only see a example once Args: Returns: dict A dictionary containing mean and stds for the experiment """ # List to store accuracy for each run runs = [] batch_size = args.batch_size if model.imp_method == 'A-GEM' or model.imp_method == 'ER': use_episodic_memory = True else: use_episodic_memory = False # Loop over number of runs to average over for runid in range(args.num_runs): print('\t\tRun %d:'%(runid)) # Initialize the random seeds np.random.seed(args.random_seed+runid) # Load the permute mnist dataset datasets = construct_permute_mnist(model.num_tasks) episodic_mem_size = args.mem_size*model.num_tasks*TOTAL_CLASSES # Initialize all the variables in the model sess.run(tf.global_variables_initializer()) # Run the init ops model.init_updates(sess) # List to store accuracies for a run evals = [] # List to store the classes that we have so far - used at test time test_labels = np.arange(TOTAL_CLASSES) if use_episodic_memory: # Reserve a space for episodic memory episodic_images = np.zeros([episodic_mem_size, INPUT_FEATURE_SIZE]) episodic_labels = np.zeros([episodic_mem_size, TOTAL_CLASSES]) count_cls = np.zeros(TOTAL_CLASSES, dtype=np.int32) episodic_filled_counter = 0 examples_seen_so_far = 0 # Mask for softmax # Since all the classes are present in all the tasks so nothing to mask logit_mask = np.ones(TOTAL_CLASSES) if model.imp_method == 'PNN': pnn_train_phase = np.array(np.zeros(model.num_tasks), dtype=np.bool) pnn_logit_mask = np.ones([model.num_tasks, TOTAL_CLASSES]) if COUNT_VIOLATIONS: violation_count = np.zeros(model.num_tasks) vc = 0 # Training loop for all the tasks for task in range(len(datasets)): print('\t\tTask %d:'%(task)) # If not the first task then restore weights from previous task if(task > 0 and model.imp_method != 'PNN'): model.restore(sess) # Extract training images and labels for the current task task_train_images = datasets[task]['train']['images'] task_train_labels = datasets[task]['train']['labels'] # If multi_task is set the train using datasets of all the tasks if MULTI_TASK: if task == 0: for t_ in range(1, len(datasets)): task_train_images = np.concatenate((task_train_images, datasets[t_]['train']['images']), axis=0) task_train_labels = np.concatenate((task_train_labels, datasets[t_]['train']['labels']), axis=0) else: # Skip training for this task continue # Assign equal weights to all the examples task_sample_weights = np.ones([task_train_labels.shape[0]], dtype=np.float32) total_train_examples = task_train_images.shape[0] # Randomly suffle the training examples perm = np.arange(total_train_examples) np.random.shuffle(perm) train_x = task_train_images[perm][:args.examples_per_task] train_y = task_train_labels[perm][:args.examples_per_task] task_sample_weights = task_sample_weights[perm][:args.examples_per_task] print('Received {} images, {} labels at task {}'.format(train_x.shape[0], train_y.shape[0], task)) # Array to store accuracies when training for task T ftask = [] num_train_examples = train_x.shape[0] # Train a task observing sequence of data if args.train_single_epoch: num_iters = num_train_examples // batch_size else: num_iters = args.train_iters # Training loop for task T for iters in range(num_iters): if args.train_single_epoch and not args.cross_validate_mode: if (iters < 10) or (iters < 100 and iters % 10 == 0) or (iters % 100 == 0): # Snapshot the current performance across all tasks after each mini-batch fbatch = test_task_sequence(model, sess, datasets, args.online_cross_val) ftask.append(fbatch) offset = (iters * batch_size) % (num_train_examples - batch_size) residual = batch_size if model.imp_method == 'PNN': pnn_train_phase[:] = False pnn_train_phase[task] = True feed_dict = {model.x: train_x[offset:offset+batch_size], model.y_[task]: train_y[offset:offset+batch_size], model.sample_weights: task_sample_weights[offset:offset+batch_size], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 1.0} train_phase_dict = {m_t: i_t for (m_t, i_t) in zip(model.train_phase, pnn_train_phase)} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, pnn_logit_mask)} feed_dict.update(train_phase_dict) feed_dict.update(logit_mask_dict) else: feed_dict = {model.x: train_x[offset:offset+batch_size], model.y_: train_y[offset:offset+batch_size], model.sample_weights: task_sample_weights[offset:offset+batch_size], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: True} if model.imp_method == 'VAN': _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'PNN': feed_dict[model.task_id] = task _, loss = sess.run([model.train[task], model.unweighted_entropy[task]], feed_dict=feed_dict) elif model.imp_method == 'FTR_EXT': if task == 0: _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) else: _, loss = sess.run([model.train_classifier, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'EWC': # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Update fisher after every few iterations if (iters + 1) % model.fisher_update_after == 0: sess.run(model.set_running_fisher) sess.run(model.reset_tmp_fisher) _, _, loss = sess.run([model.set_tmp_fisher, model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'PI': _, _, _, loss = sess.run([model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'MAS': _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'A-GEM': if task == 0: # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: ## Compute and store the reference gradients on the previous tasks if episodic_filled_counter <= args.eps_mem_batch: mem_sample_mask = np.arange(episodic_filled_counter) else: # Sample a random subset from episodic memory buffer mem_sample_mask = np.random.choice(episodic_filled_counter, args.eps_mem_batch, replace=False) # Sample without replacement so that we don't sample an example more than once # Store the reference gradient sess.run(model.store_ref_grads, feed_dict={model.x: episodic_images[mem_sample_mask], model.y_: episodic_labels[mem_sample_mask], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: True}) if COUNT_VIOLATIONS: vc, _, loss = sess.run([model.violation_count, model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) else: # Compute the gradient for current task and project if need be _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) # Put the batch in the ring buffer for er_x, er_y_ in zip(train_x[offset:offset+residual], train_y[offset:offset+residual]): cls = np.unique(np.nonzero(er_y_))[-1] # Write the example at the location pointed by count_cls[cls] cls_to_index_map = cls with_in_task_offset = args.mem_size * cls_to_index_map mem_index = count_cls[cls] + with_in_task_offset + episodic_filled_counter episodic_images[mem_index] = er_x episodic_labels[mem_index] = er_y_ count_cls[cls] = (count_cls[cls] + 1) % args.mem_size elif model.imp_method == 'RWALK': # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Update fisher and importance score after every few iterations if (iters + 1) % model.fisher_update_after == 0: # Update the importance score using distance in riemannian manifold sess.run(model.update_big_omega_riemann) # Now that the score is updated, compute the new value for running Fisher sess.run(model.set_running_fisher) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Reset the delta_L sess.run([model.reset_small_omega]) _, _, _, _, loss = sess.run([model.set_tmp_fisher, model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'ER': mem_filled_so_far = examples_seen_so_far if (examples_seen_so_far < episodic_mem_size) else episodic_mem_size if mem_filled_so_far < args.eps_mem_batch: er_mem_indices = np.arange(mem_filled_so_far) else: er_mem_indices = np.random.choice(mem_filled_so_far, args.eps_mem_batch, replace=False) np.random.shuffle(er_mem_indices) # Train on a batch of episodic memory first er_train_x_batch = np.concatenate((episodic_images[er_mem_indices], train_x[offset:offset+residual]), axis=0) er_train_y_batch = np.concatenate((episodic_labels[er_mem_indices], train_y[offset:offset+residual]), axis=0) feed_dict = {model.x: er_train_x_batch, model.y_: er_train_y_batch, model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: True} _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) for er_x, er_y_ in zip(train_x[offset:offset+residual], train_y[offset:offset+residual]): update_reservior(er_x, er_y_, episodic_images, episodic_labels, episodic_mem_size, examples_seen_so_far) examples_seen_so_far += 1 if (iters % 100 == 0): print('Step {:d} {:.3f}'.format(iters, loss)) if (math.isnan(loss)): print('ERROR: NaNs NaNs Nans!!!') sys.exit(0) print('\t\t\t\tTraining for Task%d done!'%(task)) # Upaate the episodic memory filled counter if use_episodic_memory: episodic_filled_counter += args.mem_size * TOTAL_CLASSES if model.imp_method == 'A-GEM' and COUNT_VIOLATIONS: violation_count[task] = vc print('Task {}: Violation Count: {}'.format(task, violation_count)) sess.run(model.reset_violation_count, feed_dict=feed_dict) # Compute the inter-task updates, Fisher/ importance scores etc # Don't calculate the task updates for the last task if (task < (len(datasets) - 1)) or MEASURE_PERF_ON_EPS_MEMORY: model.task_updates(sess, task, task_train_images, np.arange(TOTAL_CLASSES)) print('\t\t\t\tTask updates after Task%d done!'%(task)) if args.train_single_epoch and not args.cross_validate_mode: fbatch = test_task_sequence(model, sess, datasets, False) ftask.append(fbatch) ftask = np.array(ftask) else: if MEASURE_PERF_ON_EPS_MEMORY: eps_mem = { 'images': episodic_images, 'labels': episodic_labels, } # Measure perf on episodic memory ftask = test_task_sequence(model, sess, eps_mem, args.online_cross_val) else: # List to store accuracy for all the tasks for the current trained model ftask = test_task_sequence(model, sess, datasets, args.online_cross_val) # Store the accuracies computed at task T in a list evals.append(ftask) # Reset the optimizer model.reset_optimizer(sess) #-> End for loop task runs.append(np.array(evals)) # End for loop runid runs = np.array(runs) return runs def test_task_sequence(model, sess, test_data, cross_validate_mode): """ Snapshot the current performance """ if TIME_MY_METHOD: # Only compute the training time return np.zeros(model.num_tasks) list_acc = [] if model.imp_method == 'PNN': pnn_logit_mask = np.ones([model.num_tasks, TOTAL_CLASSES]) else: logit_mask = np.ones(TOTAL_CLASSES) if MEASURE_PERF_ON_EPS_MEMORY: for task in range(model.num_tasks): mem_offset = task*SAMPLES_PER_CLASS*TOTAL_CLASSES feed_dict = {model.x: test_data['images'][mem_offset:mem_offset+SAMPLES_PER_CLASS*TOTAL_CLASSES], model.y_: test_data['labels'][mem_offset:mem_offset+SAMPLES_PER_CLASS*TOTAL_CLASSES], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False} acc = model.accuracy.eval(feed_dict = feed_dict) list_acc.append(acc) print(list_acc) return list_acc for task, _ in enumerate(test_data): if model.imp_method == 'PNN': pnn_train_phase = np.array(np.zeros(model.num_tasks), dtype=np.bool) feed_dict = {model.x: test_data[task]['test']['images'], model.y_[task]: test_data[task]['test']['labels'], model.keep_prob: 1.0} train_phase_dict = {m_t: i_t for (m_t, i_t) in zip(model.train_phase, pnn_train_phase)} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, pnn_logit_mask)} feed_dict.update(train_phase_dict) feed_dict.update(logit_mask_dict) acc = model.accuracy[task].eval(feed_dict = feed_dict) else: feed_dict = {model.x: test_data[task]['test']['images'], model.y_: test_data[task]['test']['labels'], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False} acc = model.accuracy.eval(feed_dict = feed_dict) list_acc.append(acc) return list_acc def main(): """ Create the model and start the training """ # Get the CL arguments args = get_arguments() # Check if the network architecture is valid if args.arch not in VALID_ARCHS: raise ValueError("Network architecture %s is not supported!"%(args.arch)) # Check if the method to compute importance is valid if args.imp_method not in MODELS: raise ValueError("Importance measure %s is undefined!"%(args.imp_method)) # Check if the optimizer is valid if args.optim not in VALID_OPTIMS: raise ValueError("Optimizer %s is undefined!"%(args.optim)) # Create log directories to store the results if not os.path.exists(args.log_dir): print('Log directory %s created!'%(args.log_dir)) os.makedirs(args.log_dir) # Generate the experiment key and store the meta data in a file exper_meta_data = {'DATASET': 'PERMUTE_MNIST', 'NUM_RUNS': args.num_runs, 'TRAIN_SINGLE_EPOCH': args.train_single_epoch, 'IMP_METHOD': args.imp_method, 'SYNAP_STGTH': args.synap_stgth, 'FISHER_EMA_DECAY': args.fisher_ema_decay, 'FISHER_UPDATE_AFTER': args.fisher_update_after, 'OPTIM': args.optim, 'LR': args.learning_rate, 'BATCH_SIZE': args.batch_size, 'MEM_SIZE': args.mem_size} experiment_id = "PERMUTE_MNIST_HERDING_%s_%s_%s_%s_%r_%s-"%(args.arch, args.train_single_epoch, args.imp_method, str(args.synap_stgth).replace('.', '_'), str(args.batch_size), str(args.mem_size)) + datetime.datetime.now().strftime("%y-%m-%d-%H-%M") snapshot_experiment_meta_data(args.log_dir, experiment_id, exper_meta_data) # Get the subset of data depending on training or cross-validation mode if args.online_cross_val: num_tasks = K_FOR_CROSS_VAL else: num_tasks = NUM_TASKS - K_FOR_CROSS_VAL # Variables to store the accuracies and standard deviations of the experiment acc_mean = dict() acc_std = dict() # Reset the default graph tf.reset_default_graph() graph = tf.Graph() with graph.as_default(): # Set the random seed tf.set_random_seed(args.random_seed) # Define Input and Output of the model x = tf.placeholder(tf.float32, shape=[None, INPUT_FEATURE_SIZE]) #x = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) if args.imp_method == 'PNN': y_ = [] for i in range(num_tasks): y_.append(tf.placeholder(tf.float32, shape=[None, TOTAL_CLASSES])) else: y_ = tf.placeholder(tf.float32, shape=[None, TOTAL_CLASSES]) # Define the optimizer if args.optim == 'ADAM': opt = tf.train.AdamOptimizer(learning_rate=args.learning_rate) elif args.optim == 'SGD': opt = tf.train.GradientDescentOptimizer(learning_rate=args.learning_rate) elif args.optim == 'MOMENTUM': base_lr = tf.constant(args.learning_rate) learning_rate = tf.scalar_mul(base_lr, tf.pow((1 - train_step / training_iters), OPT_POWER)) opt = tf.train.MomentumOptimizer(args.learning_rate, OPT_MOMENTUM) # Create the Model/ contruct the graph model = Model(x, y_, num_tasks, opt, args.imp_method, args.synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch) # Set up tf session and initialize variables. if USE_GPU: config = tf.ConfigProto() config.gpu_options.allow_growth = True else: config = tf.ConfigProto( device_count = {'GPU': 0} ) time_start = time.time() with tf.Session(config=config, graph=graph) as sess: runs = train_task_sequence(model, sess, args) # Close the session sess.close() time_end = time.time() time_spent = time_end - time_start # Store all the results in one dictionary to process later exper_acc = dict(mean=runs) # If cross-validation flag is enabled, store the stuff in a text file if args.cross_validate_mode: acc_mean = runs.mean(0) acc_std = runs.std(0) cross_validate_dump_file = args.log_dir + '/' + 'PERMUTE_MNIST_%s_%s'%(args.imp_method, args.optim) + '.txt' with open(cross_validate_dump_file, 'a') as f: if MULTI_TASK: f.write('GPU:{} \t ARCH: {} \t LR:{} \t LAMBDA: {} \t ACC: {}\n'.format(USE_GPU, args.arch, args.learning_rate, args.synap_stgth, acc_mean[-1, :].mean())) else: f.write('GPU: {} \t ARCH: {} \t LR:{} \t LAMBDA: {} \t ACC: {} \t Fgt: {} \t Time: {}\n'.format(USE_GPU, args.arch, args.learning_rate, args.synap_stgth, acc_mean[-1, :].mean(), compute_fgt(acc_mean), str(time_spent))) # Store the experiment output to a file snapshot_experiment_eval(args.log_dir, experiment_id, exper_acc) if __name__ == '__main__': main()
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Training script for split AWA experiment. """ from __future__ import print_function import argparse import os import sys import math import random import time import datetime import numpy as np import tensorflow as tf from copy import deepcopy from six.moves import cPickle as pickle from utils.data_utils import image_scaling, random_crop_and_pad_image, random_horizontal_flip, construct_split_awa from utils.utils import get_sample_weights, sample_from_dataset, update_episodic_memory, concatenate_datasets, samples_for_each_class, sample_from_dataset_icarl, compute_fgt, load_task_specific_data, load_task_specific_data_in_proportion from utils.vis_utils import plot_acc_multiple_runs, plot_histogram, snapshot_experiment_meta_data, snapshot_experiment_eval, snapshot_task_labels from model import Model ############################################################### ################ Some definitions ############################# ### These will be edited by the command line options ########## ############################################################### ## Training Options NUM_RUNS = 5 # Number of experiments to average over TRAIN_ITERS = 2000 # Number of training iterations per task BATCH_SIZE = 16 LEARNING_RATE = 0.1 RANDOM_SEED = 1234 VALID_OPTIMS = ['SGD', 'MOMENTUM', 'ADAM'] OPTIM = 'SGD' OPT_MOMENTUM = 0.9 OPT_POWER = 0.9 VALID_ARCHS = ['CNN', 'VGG', 'RESNET-B'] ARCH = 'RESNET-B' PRETRAIN = False ## Model options #MODELS = ['VAN', 'PI', 'EWC', 'MAS', 'RWALK', 'M-EWC', 'GEM', 'A-GEM', 'S-GEM'] #List of valid models MODELS = ['VAN', 'PI', 'EWC', 'MAS', 'RWALK', 'A-GEM'] #List of valid models IMP_METHOD = 'VAN' SYNAP_STGTH = 75000 FISHER_EMA_DECAY = 0.9 # Exponential moving average decay factor for Fisher computation (online Fisher) FISHER_UPDATE_AFTER = 50 # Number of training iterations for which the F_{\theta}^t is computed (see Eq. 10 in RWalk paper) SAMPLES_PER_CLASS = 20 # Number of samples per task IMG_HEIGHT = 224 IMG_WIDTH = 224 IMG_CHANNELS = 3 TOTAL_CLASSES = 50 # Total number of classes in the dataset MEASURE_CONVERGENCE_AFTER = 0.9 EPS_MEM_BATCH_SIZE = 128 DEBUG_EPISODIC_MEMORY = False KEEP_EPISODIC_MEMORY_FULL = False K_FOR_CROSS_VAL = 3 CLASSES_PER_TASK = 5 ## Logging, saving and testing options LOG_DIR = './split_awa_results' SNAPSHOT_DIR = './awa_snapshots/sgd' SAVE_MODEL_PARAMS = False RESNET18_IMAGENET_CHECKPOINT = './resnet-18-pretrained-imagenet/model.ckpt' ## Evaluation options ## Task split NUM_TASKS = 20 MULTI_TASK = False ## Dataset specific options DATA_DIR= './AWA_data/Animals_with_Attributes2/' AWA_TRAIN_LIST = './dataset_lists/AWA_train_list.txt' AWA_VAL_LIST = './dataset_lists/AWA_val_list.txt' AWA_TEST_LIST = './dataset_lists/AWA_test_list.txt' #AWA_TRAIN_LIST = './dataset_lists/tmp_list_awa.txt' #AWA_VAL_LIST = './dataset_lists/tmp_list_awa.txt' #AWA_TEST_LIST = './dataset_lists/tmp_list_awa.txt' # Define function to load/ store training weights. We will use ImageNet initialization later on def save(saver, sess, logdir, step): '''Save weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. logdir: path to the snapshots directory. step: current training step. ''' model_name = 'model.ckpt' checkpoint_path = os.path.join(logdir, model_name) if not os.path.exists(logdir): os.makedirs(logdir) saver.save(sess, checkpoint_path, global_step=step) print('The checkpoint has been created.') def load(saver, sess, ckpt_path): '''Load trained weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. ckpt_path: path to checkpoint file with parameters. ''' saver.restore(sess, ckpt_path) print("Restored model parameters from {}".format(ckpt_path)) def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Script for split AWA experiment.") parser.add_argument("--cross-validate-mode", action="store_true", help="If option is chosen then snapshoting after each batch is disabled") parser.add_argument("--online-cross-val", action="store_true", help="If option is chosen then enable the online cross validation of the learning rate") parser.add_argument("--train-single-epoch", action="store_true", help="If option is chosen then train for single epoch") parser.add_argument("--eval-single-head", action="store_true", help="If option is chosen then evaluate on a single head setting.") parser.add_argument("--arch", type=str, default=ARCH, help="Network Architecture for the experiment.\ \n \nSupported values: %s"%(VALID_ARCHS)) parser.add_argument("--num-runs", type=int, default=NUM_RUNS, help="Total runs/ experiments over which accuracy is averaged.") parser.add_argument("--train-iters", type=int, default=TRAIN_ITERS, help="Number of training iterations for each task.") parser.add_argument("--batch-size", type=int, default=BATCH_SIZE, help="Mini-batch size for each task.") parser.add_argument("--random-seed", type=int, default=RANDOM_SEED, help="Random Seed.") parser.add_argument("--learning-rate", type=float, default=LEARNING_RATE, help="Starting Learning rate for each task.") parser.add_argument("--optim", type=str, default=OPTIM, help="Optimizer for the experiment. \ \n \nSupported values: %s"%(VALID_OPTIMS)) parser.add_argument("--imp-method", type=str, default=IMP_METHOD, help="Model to be used for LLL. \ \n \nSupported values: %s"%(MODELS)) parser.add_argument("--synap-stgth", type=float, default=SYNAP_STGTH, help="Synaptic strength for the regularization.") parser.add_argument("--fisher-ema-decay", type=float, default=FISHER_EMA_DECAY, help="Exponential moving average decay for Fisher calculation at each step.") parser.add_argument("--fisher-update-after", type=int, default=FISHER_UPDATE_AFTER, help="Number of training iterations after which the Fisher will be updated.") parser.add_argument("--do-sampling", action="store_true", help="Whether to do sampling") parser.add_argument("--mem-size", type=int, default=SAMPLES_PER_CLASS, help="Number of samples per class from previous tasks.") parser.add_argument("--is-herding", action="store_true", help="Herding based sampling") parser.add_argument("--data-dir", type=str, default=DATA_DIR, help="Directory from where the AWA data will be read.\ NOTE: Provide path till <AWA_DIR>/Animals_with_Attributes2") parser.add_argument("--init-checkpoint", type=str, default=RESNET18_IMAGENET_CHECKPOINT, help="Path to TF checkpoint file or npz file containing initialization for ImageNet.\ NOTE: NPZ file for VGG and TF checkpoint for ResNet") parser.add_argument("--log-dir", type=str, default=LOG_DIR, help="Directory where the plots and model accuracies will be stored.") return parser.parse_args() def train_task_sequence(model, sess, saver, datasets, cross_validate_mode, train_single_epoch, do_sampling, is_herding, episodic_mem_size, train_iters, batch_size, num_runs, init_checkpoint, online_cross_val, random_seed): """ Train and evaluate LLL system such that we only see a example once Args: Returns: dict A dictionary containing mean and stds for the experiment """ # List to store accuracy for each run runs = [] task_labels_dataset = [] break_training = 0 # Loop over number of runs to average over for runid in range(num_runs): print('\t\tRun %d:'%(runid)) # Initialize the random seeds np.random.seed(random_seed+runid) random.seed(random_seed+runid) # Get the task labels from the total number of tasks and full label space task_labels = [] classes_per_task = CLASSES_PER_TASK classes_appearing_in_tasks = dict() for cls in range(TOTAL_CLASSES): classes_appearing_in_tasks[cls] = 0 if online_cross_val: label_array = np.arange(TOTAL_CLASSES) for tt in range(model.num_tasks): offset = tt * classes_per_task task_labels.append(list(label_array[offset:offset+classes_per_task])) else: for tt in range(model.num_tasks): task_labels.append(random.sample(range(K_FOR_CROSS_VAL*classes_per_task, TOTAL_CLASSES), classes_per_task)) for lab in task_labels[tt]: classes_appearing_in_tasks[lab] += 1 print('Task: {}, Labels:{}'.format(tt, task_labels[tt])) print('Class frequency in Tasks: {}'.format(classes_appearing_in_tasks)) # Store the task labels task_labels_dataset.append(task_labels) # Initialize all the variables in the model sess.run(tf.global_variables_initializer()) if PRETRAIN: # Load the variables from a checkpoint if model.network_arch == 'RESNET-B': # Define loader (weights which will be loaded from a checkpoint) restore_vars = [v for v in model.trainable_vars if 'fc' not in v.name] loader = tf.train.Saver(restore_vars) load(loader, sess, init_checkpoint) elif model.network_arch == 'VGG': # Load the pretrained weights from the npz file weights = np.load(init_checkpoint) keys = sorted(weights.keys()) for i, key in enumerate(keys[:-2]): # Load everything except the last layer sess.run(model.trainable_vars[i].assign(weights[key])) # Run the init ops model.init_updates(sess) # List to store accuracies for a run evals = [] if model.imp_method == 'S-GEM': # List to store the episodic memories of the previous tasks task_based_memory = [] if model.imp_method == 'A-GEM': # Reserve a space for episodic memory episodic_images = np.zeros([episodic_mem_size, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) episodic_labels = np.zeros([episodic_mem_size, model.num_tasks*TOTAL_CLASSES]) episodic_filled_counter = 0 a_gem_logit_mask = np.zeros([model.num_tasks, model.total_classes]) if do_sampling: # List to store important samples from the previous tasks last_task_x = None last_task_y_ = None # Mask for softmax logit_mask = np.zeros(model.total_classes) max_batch_dimension = 500 # Dict to store the number of times a class has already been seen in the training class_seen_already = dict() for cls in range(TOTAL_CLASSES): class_seen_already[cls] = 0 # Training loop for all the tasks for task in range(len(task_labels)): print('\t\tTask %d:'%(task)) # If not the first task then restore weights from previous task if(task > 0): model.restore(sess) # Increment the class seen count for cls in task_labels[task]: class_seen_already[cls] += 1 # Load the task specific dataset task_train_images, task_train_labels = load_task_specific_data_in_proportion(datasets[0]['train'], task_labels[task], classes_appearing_in_tasks, class_seen_already) print('Received {} images, {} labels at task {}'.format(task_train_images.shape[0], task_train_labels.shape[0], task)) print('Unique labels in the task: {}'.format(np.unique(np.nonzero(task_train_labels)[1]))) # Assign equal weights to all the examples task_sample_weights = np.ones([task_train_labels.shape[0]], dtype=np.float32) num_train_examples = task_train_images.shape[0] logit_mask[:] = 0 # Train a task observing sequence of data if train_single_epoch: # Ceiling operation num_iters = (num_train_examples + batch_size - 1) // batch_size else: num_iters = train_iters logit_mask_offset = task * TOTAL_CLASSES classes_adjusted_for_head = [cls + logit_mask_offset for cls in task_labels[task]] logit_mask[classes_adjusted_for_head] = 1.0 # Randomly suffle the training examples perm = np.arange(num_train_examples) np.random.shuffle(perm) train_x = task_train_images[perm] train_y = task_train_labels[perm] task_sample_weights = task_sample_weights[perm] # Array to store accuracies when training for task T if cross_validate_mode: # Because we will evalaute at the end ftask = 0 elif train_single_epoch: # Because we will evaluate after every mini-batch of every task ftask = np.zeros([max_batch_dimension+1, model.num_tasks]) batch_dim_count = 0 else: # Because we will evaluate after every task ftask = [] # Number of iterations after which convergence is checked convergence_iters = int(num_iters * MEASURE_CONVERGENCE_AFTER) final_train_labels = np.zeros([batch_size, model.total_classes]) head_offset = task * TOTAL_CLASSES # Training loop for task T for iters in range(num_iters): if train_single_epoch and not cross_validate_mode: if (iters < 11): # Snapshot the current performance across all tasks after each mini-batch fbatch = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task, online_cross_val) ftask[batch_dim_count] = fbatch # Increment the batch_dim_count batch_dim_count += 1 # Set the output labels over which the model needs to be trained if model.imp_method == 'A-GEM': a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][classes_adjusted_for_head] = 1.0 else: logit_mask[:] = 0 logit_mask[classes_adjusted_for_head] = 1.0 if train_single_epoch: offset = iters * batch_size if (offset+batch_size <= num_train_examples): residual = batch_size else: residual = num_train_examples - offset final_train_labels[:residual, head_offset:head_offset+TOTAL_CLASSES] = train_y[offset:offset+residual] feed_dict = {model.x: train_x[offset:offset+residual], model.y_: final_train_labels[:residual], model.sample_weights: task_sample_weights[offset:offset+residual], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5, model.train_phase: True} else: offset = (iters * batch_size) % (num_train_examples - batch_size) final_train_labels[:, head_offset:head_offset+TOTAL_CLASSES] = train_y[offset:offset+residual] feed_dict = {model.x: train_x[offset:offset+batch_size], model.y_: final_train_labels, model.sample_weights: task_sample_weights[offset:offset+batch_size], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5, model.train_phase: True} if model.imp_method == 'VAN': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'EWC' or model.imp_method == 'M-EWC': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Update fisher after every few iterations if (iters + 1) % model.fisher_update_after == 0: sess.run(model.set_running_fisher) sess.run(model.reset_tmp_fisher) if (iters >= convergence_iters) and (model.imp_method == 'M-EWC'): _, _, _, _, loss = sess.run([model.weights_old_ops_grouped, model.set_tmp_fisher, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) else: _, _, loss = sess.run([model.set_tmp_fisher, model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'PI': feed_dict[model.output_mask] = logit_mask _, _, _, loss = sess.run([model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'MAS': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'S-GEM': if task == 0: logit_mask[:] = 0 logit_mask[task_labels[task]] = 1.0 feed_dict[model.output_mask] = logit_mask # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: # Randomly sample a task from the previous tasks prev_task = np.random.randint(0, task) # Set the logit mask for the randomly sampled task logit_mask[:] = 0 logit_mask[task_labels[prev_task]] = 1.0 # Store the reference gradient sess.run(model.store_ref_grads, feed_dict={model.x: task_based_memory[prev_task]['images'], model.y_: task_based_memory[prev_task]['labels'], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: True}) # Compute the gradient for current task and project if need be logit_mask[:] = 0 logit_mask[task_labels[task]] = 1.0 feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) elif model.imp_method == 'A-GEM': if task == 0: a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][classes_adjusted_for_head] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: ## Compute and store the reference gradients on the previous tasks # Reset the reference gradients # Set the mask for all the previous tasks so far a_gem_logit_mask[:] = 0 for tt in range(task): logit_mask_offset = tt * TOTAL_CLASSES classes_adjusted_for_head = [cls + logit_mask_offset for cls in task_labels[tt]] a_gem_logit_mask[tt][classes_adjusted_for_head] = 1.0 if KEEP_EPISODIC_MEMORY_FULL: mem_sample_mask = np.random.choice(episodic_mem_size, EPS_MEM_BATCH_SIZE, replace=False) # Sample without replacement so that we don't sample an example more than once else: if episodic_filled_counter <= EPS_MEM_BATCH_SIZE: mem_sample_mask = np.arange(episodic_filled_counter) else: # Sample a random subset from episodic memory buffer mem_sample_mask = np.random.choice(episodic_filled_counter, EPS_MEM_BATCH_SIZE, replace=False) # Sample without replacement so that we don't sample an example more than once ref_feed_dict = {model.x: episodic_images[mem_sample_mask], model.y_: episodic_labels[mem_sample_mask], model.keep_prob: 1.0, model.train_phase: True} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} ref_feed_dict.update(logit_mask_dict) ref_feed_dict[model.mem_batch_size] = float(len(mem_sample_mask)) sess.run(model.store_ref_grads, feed_dict=ref_feed_dict) # Compute the gradient for current task and project if need be a_gem_logit_mask[:] = 0 logit_mask_offset = task * TOTAL_CLASSES classes_adjusted_for_head = [cls + logit_mask_offset for cls in task_labels[task]] a_gem_logit_mask[task][classes_adjusted_for_head] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) elif model.imp_method == 'RWALK': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Update fisher and importance score after every few iterations if (iters + 1) % model.fisher_update_after == 0: # Update the importance score using distance in riemannian manifold sess.run(model.update_big_omega_riemann) # Now that the score is updated, compute the new value for running Fisher sess.run(model.set_running_fisher) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Reset the delta_L sess.run([model.reset_small_omega]) _, _, _, _, loss = sess.run([model.set_tmp_fisher, model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) if (iters % 100 == 0): print('Step {:d} {:.3f}'.format(iters, loss)) if (math.isnan(loss)): print('ERROR: NaNs NaNs NaNs!!!') break_training = 1 break print('\t\t\t\tTraining for Task%d done!'%(task)) if break_training: break # Compute the inter-task updates, Fisher/ importance scores etc # Don't calculate the task updates for the last task if task < (len(task_labels) - 1): model.task_updates(sess, task, task_train_images, task_labels[task]) # TODO: For MAS, should the gradients be for current task or all the previous tasks print('\t\t\t\tTask updates after Task%d done!'%(task)) # If importance method is '*-GEM' then store the episodic memory for the task if 'GEM' in model.imp_method: data_to_sample_from = { 'images': task_train_images, 'labels': task_train_labels, } if model.imp_method == 'S-GEM': # Get the important samples from the current task if is_herding: # Sampling based on MoF # Compute the features of training data features_dim = model.image_feature_dim features = np.zeros([num_train_examples, features_dim]) samples_at_a_time = 32 residual = num_train_examples % samples_at_a_time for i in range(num_train_examples// samples_at_a_time): offset = i * samples_at_a_time features[offset:offset+samples_at_a_time] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+samples_at_a_time], model.y_: task_train_labels[offset:offset+samples_at_a_time], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) if residual > 0: offset = (i + 1) * samples_at_a_time features[offset:offset+residual] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+residual], model.y_: task_train_labels[offset:offset+residual], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) imp_images, imp_labels = sample_from_dataset_icarl(data_to_sample_from, features, task_labels[task], SAMPLES_PER_CLASS) else: # Random sampling # Do the uniform sampling/ only get examples from current task importance_array = np.ones(num_train_examples, dtype=np.float32) imp_images, imp_labels = sample_from_dataset(data_to_sample_from, importance_array, task_labels[task], SAMPLES_PER_CLASS) task_memory = { 'images': deepcopy(imp_images), 'labels': deepcopy(imp_labels), } task_based_memory.append(task_memory) elif model.imp_method == 'A-GEM': # Do the uniform sampling/ only get examples from current task importance_array = np.ones(num_train_examples, dtype=np.float32) if KEEP_EPISODIC_MEMORY_FULL: update_episodic_memory(data_to_sample_from, importance_array, episodic_mem_size, task, episodic_images, episodic_labels) else: imp_images, imp_labels = sample_from_dataset(data_to_sample_from, importance_array, task_labels[task], SAMPLES_PER_CLASS) if not KEEP_EPISODIC_MEMORY_FULL: # Fill the memory to always keep M/T samples per task total_imp_samples = imp_images.shape[0] eps_offset = task * total_imp_samples episodic_images[eps_offset:eps_offset+total_imp_samples] = imp_images episodic_labels[eps_offset:eps_offset+total_imp_samples, head_offset:head_offset+TOTAL_CLASSES] = imp_labels episodic_filled_counter += total_imp_samples print('Unique labels in the episodic memory: {}'.format(np.unique(np.nonzero(episodic_labels)[1]))) # Inspect episodic memory if DEBUG_EPISODIC_MEMORY: # Which labels are present in the memory unique_labels = np.unique(np.nonzero(episodic_labels)[-1]) print('Unique Labels present in the episodic memory'.format(unique_labels)) print('Labels count:') for lbl in unique_labels: print('Label {}: {} samples'.format(lbl, np.where(np.nonzero(episodic_labels)[-1] == lbl)[0].size)) # Is there any space which is not filled print('Empty space: {}'.format(np.where(np.sum(episodic_labels, axis=1) == 0))) print('Episodic memory of {} images at task {} saved!'.format(episodic_images.shape[0], task)) # If sampling flag is set, store few of the samples from previous task if do_sampling: # Do the uniform sampling/ only get examples from current task importance_array = np.ones([datasets[task]['train']['images'].shape[0]], dtype=np.float32) # Get the important samples from the current task imp_images, imp_labels = sample_from_dataset(datasets[task]['train'], importance_array, task_labels[task], SAMPLES_PER_CLASS) if imp_images is not None: if last_task_x is None: last_task_x = imp_images last_task_y_ = imp_labels else: last_task_x = np.concatenate((last_task_x, imp_images), axis=0) last_task_y_ = np.concatenate((last_task_y_, imp_labels), axis=0) # Delete the importance array now that you don't need it in the current run del importance_array print('\t\t\t\tEpisodic memory is saved for Task%d!'%(task)) if cross_validate_mode: # Only evaluate after the last task if (task == model.num_tasks - 1) or MULTI_TASK: # List to store accuracy for all the tasks for the current trained model ftask = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task, online_cross_val) elif train_single_epoch: fbatch = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task, False) print('Task: {} Acc: {}'.format(task, fbatch)) ftask[batch_dim_count] = fbatch else: # Multi-epoch training, so compute accuracy at the end ftask = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task, online_cross_val) if SAVE_MODEL_PARAMS: save(saver, sess, SNAPSHOT_DIR, iters) if not cross_validate_mode: # Store the accuracies computed at task T in a list evals.append(np.array(ftask)) # Reset the optimizer model.reset_optimizer(sess) #-> End for loop task if not cross_validate_mode: runs.append(np.array(evals)) if break_training: break # End for loop runid if cross_validate_mode: return np.mean(ftask), task_labels_dataset else: runs = np.array(runs) return runs, task_labels_dataset def test_task_sequence(model, sess, test_data, all_task_labels, task, cross_validate_mode): """ Snapshot the current performance """ final_acc = np.zeros(model.num_tasks) test_set = 'test' if model.imp_method == 'A-GEM': logit_mask = np.zeros([model.num_tasks, model.total_classes]) else: logit_mask = np.zeros(model.total_classes) for tt, labels in enumerate(all_task_labels): if tt > task: return final_acc samples_at_a_time = 10 task_images, task_labels = load_task_specific_data(test_data, labels) global_class_indices = np.column_stack(np.nonzero(task_labels)) logit_mask_offset = tt * TOTAL_CLASSES classes_adjusted_for_head = [cls + logit_mask_offset for cls in labels] logit_mask[:] = 0 if model.imp_method == 'A-GEM': logit_mask[tt][classes_adjusted_for_head] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, logit_mask)} else: logit_mask[classes_adjusted_for_head] = 1.0 acc = np.zeros(len(labels)) final_train_labels = np.zeros([samples_at_a_time, model.total_classes]) head_offset = tt * TOTAL_CLASSES for cli, cls in enumerate(labels): class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])]) class_indices = np.sort(class_indices, axis=None) task_test_images = task_images[class_indices] task_test_labels = task_labels[class_indices] total_test_samples = task_test_images.shape[0] total_corrects = 0 if total_test_samples < samples_at_a_time: i = -1 for i in range(total_test_samples/ samples_at_a_time): offset = i*samples_at_a_time final_train_labels[:, head_offset:head_offset+TOTAL_CLASSES] = task_test_labels[offset:offset+samples_at_a_time] feed_dict = {model.x: task_test_images[offset:offset+samples_at_a_time], model.y_: final_train_labels, model.keep_prob: 1.0, model.train_phase: False} if model.imp_method == 'A-GEM': feed_dict.update(logit_mask_dict) total_corrects += np.sum(sess.run(model.correct_predictions[tt], feed_dict=feed_dict)) else: feed_dict[model.output_mask] = logit_mask total_corrects += np.sum(sess.run(model.correct_predictions, feed_dict=feed_dict)) # Compute the corrects on residuals offset = (i+1)*samples_at_a_time num_residuals = total_test_samples % samples_at_a_time final_train_labels[:num_residuals, head_offset:head_offset+TOTAL_CLASSES] = task_test_labels[offset:offset+num_residuals] feed_dict = {model.x: task_test_images[offset:offset+num_residuals], model.y_: final_train_labels[:num_residuals], model.keep_prob: 1.0, model.train_phase: False} if model.imp_method == 'A-GEM': feed_dict.update(logit_mask_dict) total_corrects += np.sum(sess.run(model.correct_predictions[tt], feed_dict=feed_dict)) else: feed_dict[model.output_mask] = logit_mask total_corrects += np.sum(sess.run(model.correct_predictions, feed_dict=feed_dict)) # Accuracy if total_test_samples != 0: acc[cli] = total_corrects/ float(total_test_samples) final_acc[tt] = np.mean(acc) return final_acc def main(): """ Create the model and start the training """ # Get the CL arguments args = get_arguments() # Initialize the random seed of numpy np.random.seed(args.random_seed) # Check if the network architecture is valid if args.arch not in VALID_ARCHS: raise ValueError("Network architecture %s is not supported!"%(args.arch)) # Check if the method to compute importance is valid if args.imp_method not in MODELS: raise ValueError("Importance measure %s is undefined!"%(args.imp_method)) # Check if the optimizer is valid if args.optim not in VALID_OPTIMS: raise ValueError("Optimizer %s is undefined!"%(args.optim)) # Create log directories to store the results if not os.path.exists(args.log_dir): print('Log directory %s created!'%(args.log_dir)) os.makedirs(args.log_dir) if args.online_cross_val: num_tasks = K_FOR_CROSS_VAL else: num_tasks = NUM_TASKS - K_FOR_CROSS_VAL # Load the split AWA dataset for all the classes data_labs = [np.arange(TOTAL_CLASSES)] datasets = construct_split_awa(data_labs, args.data_dir, AWA_TRAIN_LIST, AWA_VAL_LIST, AWA_TEST_LIST, IMG_HEIGHT, IMG_WIDTH) if args.cross_validate_mode: #models_list = MODELS #learning_rate_list = [0.1, 0.03, 0.01, 0.003, 0.0003] models_list = [args.imp_method] learning_rate_list = [0.01] else: models_list = [args.imp_method] for imp_method in models_list: if imp_method == 'VAN': synap_stgth_list = [0] if args.online_cross_val or args.cross_validate_mode: pass else: learning_rate_list = [0.001] elif imp_method == 'PI': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10] else: synap_stgth_list = [1] learning_rate_list = [0.003] elif imp_method == 'EWC' or imp_method == 'M-EWC': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [100] learning_rate_list = [0.003] elif imp_method == 'MAS': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [1] learning_rate_list = [0.003] elif imp_method == 'RWALK': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [10] # Run again learning_rate_list = [0.003] elif imp_method == 'S-GEM': synap_stgth_list = [0] if args.online_cross_val: pass else: learning_rate_list = [args.learning_rate] elif imp_method == 'A-GEM': synap_stgth_list = [0] if args.online_cross_val or args.cross_validate_mode: pass else: learning_rate_list = [0.01] for synap_stgth in synap_stgth_list: for lr in learning_rate_list: # Generate the experiment key and store the meta data in a file exper_meta_data = {'ARCH': args.arch, 'DATASET': 'SPLIT_AWA', 'NUM_RUNS': args.num_runs, 'TRAIN_SINGLE_EPOCH': args.train_single_epoch, 'IMP_METHOD': imp_method, 'SYNAP_STGTH': synap_stgth, 'FISHER_EMA_DECAY': args.fisher_ema_decay, 'FISHER_UPDATE_AFTER': args.fisher_update_after, 'OPTIM': args.optim, 'LR': lr, 'BATCH_SIZE': args.batch_size, 'EPS_MEMORY': args.do_sampling, 'MEM_SIZE': args.mem_size, 'IS_HERDING': args.is_herding} experiment_id = "SPLIT_AWA_ONE_HOT_HERDING_%r_%s_%r_%s_%s_%s_%s_%r_%s-"%(args.is_herding, args.arch, args.train_single_epoch, imp_method, str(synap_stgth).replace('.', '_'), str(lr).replace('.', '_'), str(args.batch_size), args.do_sampling, str(args.mem_size)) + datetime.datetime.now().strftime("%y-%m-%d-%H-%M") snapshot_experiment_meta_data(args.log_dir, experiment_id, exper_meta_data) # Reset the default graph tf.reset_default_graph() graph = tf.Graph() with graph.as_default(): # Set the random seed tf.set_random_seed(args.random_seed) # Define Input and Output of the model x = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) y_ = tf.placeholder(tf.float32, shape=[None, num_tasks*TOTAL_CLASSES]) if not args.train_single_epoch: # Define ops for data augmentation x_aug = image_scaling(x) x_aug = random_crop_and_pad_image(x_aug, IMG_HEIGHT, IMG_WIDTH) # Define the optimizer if args.optim == 'ADAM': opt = tf.train.AdamOptimizer(learning_rate=lr) elif args.optim == 'SGD': opt = tf.train.GradientDescentOptimizer(learning_rate=lr) elif args.optim == 'MOMENTUM': base_lr = tf.constant(lr) learning_rate = tf.scalar_mul(base_lr, tf.pow((1 - train_step / training_iters), OPT_POWER)) opt = tf.train.MomentumOptimizer(lr, OPT_MOMENTUM) # Create the Model/ contruct the graph if args.train_single_epoch: # When training using a single epoch then there is no need for data augmentation model = Model(x, y_, num_tasks, opt, imp_method, synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch, is_ATT_DATASET=True) else: model = Model(x_aug, y_, num_tasks, opt, imp_method, synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch, is_ATT_DATASET=True, x_test=x) # Set up tf session and initialize variables. config = tf.ConfigProto() config.gpu_options.allow_growth = True time_start = time.time() with tf.Session(config=config, graph=graph) as sess: saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=100) runs, task_labels_dataset = train_task_sequence(model, sess, saver, datasets, args.cross_validate_mode, args.train_single_epoch, args.do_sampling, args.is_herding, args.mem_size*CLASSES_PER_TASK*num_tasks, args.train_iters, args.batch_size, args.num_runs, args.init_checkpoint, args.online_cross_val, args.random_seed) # Close the session sess.close() time_end = time.time() time_spent = time_end - time_start print('Time spent: {}'.format(time_spent)) # Clean up del model if args.cross_validate_mode: # If cross-validation flag is enabled, store the stuff in a text file cross_validate_dump_file = args.log_dir + '/' + 'SPLIT_AWA_%s_%s'%(imp_method, args.optim) + '.txt' with open(cross_validate_dump_file, 'a') as f: f.write('HERDING: {} \t ARCH: {} \t LR:{} \t LAMBDA: {} \t ACC: {}\n'.format(args.is_herding, args.arch, lr, synap_stgth, runs)) else: # Store all the results in one dictionary to process later exper_acc = dict(mean=runs) exper_labels = dict(labels=task_labels_dataset) # Store the experiment output to a file snapshot_experiment_eval(args.log_dir, experiment_id, exper_acc) snapshot_task_labels(args.log_dir, experiment_id, exper_labels) if __name__ == '__main__': main()
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Training script for split CUB experiment. """ from __future__ import print_function import argparse import os import sys import math import time import datetime import numpy as np import tensorflow as tf from copy import deepcopy from six.moves import cPickle as pickle from utils.data_utils import image_scaling, random_crop_and_pad_image, random_horizontal_flip, construct_split_cub from utils.utils import get_sample_weights, sample_from_dataset, update_episodic_memory_with_less_data, concatenate_datasets, samples_for_each_class, sample_from_dataset_icarl, load_task_specific_data from utils.vis_utils import plot_acc_multiple_runs, plot_histogram, snapshot_experiment_meta_data, snapshot_experiment_eval, snapshot_task_labels from model import Model ############################################################### ################ Some definitions ############################# ### These will be edited by the command line options ########## ############################################################### ## Training Options NUM_RUNS = 5 # Number of experiments to average over TRAIN_ITERS = 2000 # Number of training iterations per task BATCH_SIZE = 16 LEARNING_RATE = 0.1 RANDOM_SEED = 1234 VALID_OPTIMS = ['SGD', 'MOMENTUM', 'ADAM'] OPTIM = 'SGD' OPT_MOMENTUM = 0.9 OPT_POWER = 0.9 VALID_ARCHS = ['CNN', 'VGG', 'RESNET-B'] ARCH = 'RESNET-B' PRETRAIN = True ## Model options #MODELS = ['VAN', 'PI', 'EWC', 'MAS', 'RWALK', 'M-EWC', 'GEM', 'A-GEM', 'S-GEM'] #List of valid models MODELS = ['VAN', 'PI', 'EWC', 'MAS', 'RWALK', 'A-GEM'] #List of valid models IMP_METHOD = 'PI' SYNAP_STGTH = 75000 FISHER_EMA_DECAY = 0.9 # Exponential moving average decay factor for Fisher computation (online Fisher) FISHER_UPDATE_AFTER = 50 # Number of training iterations for which the F_{\theta}^t is computed (see Eq. 10 in RWalk paper) SAMPLES_PER_CLASS = 5 # Number of samples per task IMG_HEIGHT = 224 IMG_WIDTH = 224 IMG_CHANNELS = 3 TOTAL_CLASSES = 200 # Total number of classes in the dataset EPS_MEM_BATCH_SIZE = 128 DEBUG_EPISODIC_MEMORY = False KEEP_EPISODIC_MEMORY_FULL = False K_FOR_CROSS_VAL = 3 ## Logging, saving and testing options LOG_DIR = './split_cub_results' SNAPSHOT_DIR = './cub_snapshots/sgd' SAVE_MODEL_PARAMS = False ## Evaluation options ## Task split NUM_TASKS = 20 MULTI_TASK = False ## Dataset specific options DATA_DIR='CUB_data/CUB_200_2011/images' CUB_TRAIN_LIST = './dataset_lists/CUB_train_list.txt' CUB_TEST_LIST = './dataset_lists/CUB_test_list.txt' RESNET18_IMAGENET_CHECKPOINT = './resnet-18-pretrained-imagenet/model.ckpt' # Define function to load/ store training weights. We will use ImageNet initialization later on def save(saver, sess, logdir, step): '''Save weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. logdir: path to the snapshots directory. step: current training step. ''' model_name = 'model.ckpt' checkpoint_path = os.path.join(logdir, model_name) if not os.path.exists(logdir): os.makedirs(logdir) saver.save(sess, checkpoint_path, global_step=step) print('The checkpoint has been created.') def load(saver, sess, ckpt_path): '''Load trained weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. ckpt_path: path to checkpoint file with parameters. ''' saver.restore(sess, ckpt_path) print("Restored model parameters from {}".format(ckpt_path)) def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Script for split CUB experiment.") parser.add_argument("--cross-validate-mode", action="store_true", help="If option is chosen then snapshoting after each batch is disabled") parser.add_argument("--online-cross-val", action="store_true", help="If option is chosen then enable the online cross validation of the learning rate") parser.add_argument("--train-single-epoch", action="store_true", help="If option is chosen then train for single epoch") parser.add_argument("--eval-single-head", action="store_true", help="If option is chosen then evaluate on a single head setting.") parser.add_argument("--arch", type=str, default=ARCH, help="Network Architecture for the experiment.\ \n \nSupported values: %s"%(VALID_ARCHS)) parser.add_argument("--num-runs", type=int, default=NUM_RUNS, help="Total runs/ experiments over which accuracy is averaged.") parser.add_argument("--train-iters", type=int, default=TRAIN_ITERS, help="Number of training iterations for each task.") parser.add_argument("--batch-size", type=int, default=BATCH_SIZE, help="Mini-batch size for each task.") parser.add_argument("--random-seed", type=int, default=RANDOM_SEED, help="Random Seed.") parser.add_argument("--learning-rate", type=float, default=LEARNING_RATE, help="Starting Learning rate for each task.") parser.add_argument("--optim", type=str, default=OPTIM, help="Optimizer for the experiment. \ \n \nSupported values: %s"%(VALID_OPTIMS)) parser.add_argument("--imp-method", type=str, default=IMP_METHOD, help="Model to be used for LLL. \ \n \nSupported values: %s"%(MODELS)) parser.add_argument("--synap-stgth", type=float, default=SYNAP_STGTH, help="Synaptic strength for the regularization.") parser.add_argument("--fisher-ema-decay", type=float, default=FISHER_EMA_DECAY, help="Exponential moving average decay for Fisher calculation at each step.") parser.add_argument("--fisher-update-after", type=int, default=FISHER_UPDATE_AFTER, help="Number of training iterations after which the Fisher will be updated.") parser.add_argument("--do-sampling", action="store_true", help="Whether to do sampling") parser.add_argument("--mem-size", type=int, default=SAMPLES_PER_CLASS, help="Number of samples per class from previous tasks.") parser.add_argument("--is-herding", action="store_true", help="Herding based sampling") parser.add_argument("--data-dir", type=str, default=DATA_DIR, help="Directory from where the CUB data will be read.\ NOTE: Provide path till <CUB_DIR>/images") parser.add_argument("--init-checkpoint", type=str, default=RESNET18_IMAGENET_CHECKPOINT, help="Path to TF checkpoint file or npz file containing initialization for ImageNet.\ NOTE: NPZ file for VGG and TF checkpoint for ResNet") parser.add_argument("--log-dir", type=str, default=LOG_DIR, help="Directory where the plots and model accuracies will be stored.") return parser.parse_args() def train_task_sequence(model, sess, saver, datasets, cross_validate_mode, train_single_epoch, do_sampling, is_herding, mem_per_class, train_iters, batch_size, num_runs, init_checkpoint, online_cross_val, random_seed): """ Train and evaluate LLL system such that we only see a example once Args: Returns: dict A dictionary containing mean and stds for the experiment """ # List to store accuracy for each run runs = [] task_labels_dataset = [] break_training = 0 # Loop over number of runs to average over for runid in range(num_runs): print('\t\tRun %d:'%(runid)) # Initialize the random seeds np.random.seed(random_seed+runid) # Get the task labels from the total number of tasks and full label space task_labels = [] classes_per_task = TOTAL_CLASSES// NUM_TASKS total_classes = classes_per_task * model.num_tasks if online_cross_val: label_array = np.arange(total_classes) else: class_label_offset = K_FOR_CROSS_VAL * classes_per_task label_array = np.arange(class_label_offset, total_classes+class_label_offset) np.random.shuffle(label_array) for tt in range(model.num_tasks): tt_offset = tt*classes_per_task task_labels.append(list(label_array[tt_offset:tt_offset+classes_per_task])) print('Task: {}, Labels:{}'.format(tt, task_labels[tt])) # Store the task labels task_labels_dataset.append(task_labels) # Set episodic memory size episodic_mem_size = mem_per_class * total_classes # Initialize all the variables in the model sess.run(tf.global_variables_initializer()) if PRETRAIN: # Load the variables from a checkpoint if model.network_arch == 'RESNET-B': # Define loader (weights which will be loaded from a checkpoint) restore_vars = [v for v in model.trainable_vars if 'fc' not in v.name] loader = tf.train.Saver(restore_vars) load(loader, sess, init_checkpoint) elif model.network_arch == 'VGG': # Load the pretrained weights from the npz file weights = np.load(init_checkpoint) keys = sorted(weights.keys()) for i, key in enumerate(keys[:-2]): # Load everything except the last layer sess.run(model.trainable_vars[i].assign(weights[key])) # Run the init ops model.init_updates(sess) # List to store accuracies for a run evals = [] # List to store the classes that we have so far - used at test time test_labels = [] if model.imp_method == 'S-GEM': # List to store the episodic memories of the previous tasks task_based_memory = [] if model.imp_method == 'A-GEM': # Reserve a space for episodic memory episodic_images = np.zeros([episodic_mem_size, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) episodic_labels = np.zeros([episodic_mem_size, TOTAL_CLASSES]) episodic_filled_counter = 0 a_gem_logit_mask = np.zeros([model.num_tasks, TOTAL_CLASSES]) if do_sampling: # List to store important samples from the previous tasks last_task_x = None last_task_y_ = None # Mask for softmax logit_mask = np.zeros(TOTAL_CLASSES) # Training loop for all the tasks for task in range(len(task_labels)): print('\t\tTask %d:'%(task)) # If not the first task then restore weights from previous task if(task > 0): model.restore(sess) # If sampling flag is set append the previous datasets if do_sampling: task_tr_images, task_tr_labels = load_task_specific_data(datasets[0]['train'], task_labels[task]) if task > 0: task_train_images, task_train_labels = concatenate_datasets(task_tr_images, task_tr_labels, last_task_x, last_task_y_) else: task_train_images = task_tr_images task_train_labels = task_tr_labels else: # Extract training images and labels for the current task task_train_images, task_train_labels = load_task_specific_data(datasets[0]['train'], task_labels[task]) # If multi_task is set then train using all the datasets of all the tasks if MULTI_TASK: if task == 0: for t_ in range(1, len(task_labels)): task_tr_images, task_tr_labels = load_task_specific_data(datasets[0]['train'], task_labels[t_]) task_train_images = np.concatenate((task_train_images, task_tr_images), axis=0) task_train_labels = np.concatenate((task_train_labels, task_tr_labels), axis=0) else: # Skip training for this task continue print('Received {} images, {} labels at task {}'.format(task_train_images.shape[0], task_train_labels.shape[0], task)) print('Unique labels in the task: {}'.format(np.unique(np.nonzero(task_train_labels)[1]))) # Test for the tasks that we've seen so far test_labels.extend(task_labels[task]) # Declare variables to store sample importance if sampling flag is set if do_sampling: # Get the sample weighting task_sample_weights = get_sample_weights(task_train_labels, test_labels) else: # Assign equal weights to all the examples task_sample_weights = np.ones([task_train_labels.shape[0]], dtype=np.float32) num_train_examples = task_train_images.shape[0] logit_mask[:] = 0 # Train a task observing sequence of data if train_single_epoch: # Ceiling operation num_iters = (num_train_examples + batch_size - 1) // batch_size if cross_validate_mode: if do_sampling: logit_mask[test_labels] = 1.0 else: logit_mask[task_labels[task]] = 1.0 else: num_iters = train_iters # Set the mask only once before starting the training for the task if do_sampling: logit_mask[test_labels] = 1.0 else: logit_mask[task_labels[task]] = 1.0 if MULTI_TASK: logit_mask[:] = 1.0 # Randomly suffle the training examples perm = np.arange(num_train_examples) np.random.shuffle(perm) train_x = task_train_images[perm] train_y = task_train_labels[perm] task_sample_weights = task_sample_weights[perm] # Array to store accuracies when training for task T ftask = [] # Training loop for task T for iters in range(num_iters): if train_single_epoch and not cross_validate_mode and not MULTI_TASK: if (iters < 10) or (iters % 5 == 0): # Snapshot the current performance across all tasks after each mini-batch fbatch = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task) ftask.append(fbatch) # Set the output labels over which the model needs to be trained if model.imp_method == 'A-GEM': a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][task_labels[task]] = 1.0 else: logit_mask[:] = 0 if do_sampling: logit_mask[test_labels] = 1.0 else: logit_mask[task_labels[task]] = 1.0 if train_single_epoch: offset = iters * batch_size if (offset+batch_size <= num_train_examples): residual = batch_size else: residual = num_train_examples - offset feed_dict = {model.x: train_x[offset:offset+residual], model.y_: train_y[offset:offset+residual], model.sample_weights: task_sample_weights[offset:offset+residual], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5, model.train_phase: True} else: offset = (iters * batch_size) % (num_train_examples - batch_size) feed_dict = {model.x: train_x[offset:offset+batch_size], model.y_: train_y[offset:offset+batch_size], model.sample_weights: task_sample_weights[offset:offset+batch_size], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5, model.train_phase: True} if model.imp_method == 'VAN': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'EWC': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Update fisher after every few iterations if (iters + 1) % model.fisher_update_after == 0: sess.run(model.set_running_fisher) sess.run(model.reset_tmp_fisher) _, _, loss = sess.run([model.set_tmp_fisher, model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'PI': feed_dict[model.output_mask] = logit_mask _, _, _, loss = sess.run([model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'MAS': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'S-GEM': if task == 0: logit_mask[:] = 0 logit_mask[task_labels[task]] = 1.0 feed_dict[model.output_mask] = logit_mask # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: # Randomly sample a task from the previous tasks prev_task = np.random.randint(0, task) # Set the logit mask for the randomly sampled task logit_mask[:] = 0 logit_mask[task_labels[prev_task]] = 1.0 # Store the reference gradient sess.run(model.store_ref_grads, feed_dict={model.x: task_based_memory[prev_task]['images'], model.y_: task_based_memory[prev_task]['labels'], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: True}) # Compute the gradient for current task and project if need be logit_mask[:] = 0 logit_mask[task_labels[task]] = 1.0 feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) elif model.imp_method == 'A-GEM': if task == 0: a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][task_labels[task]] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: ## Compute and store the reference gradients on the previous tasks # Set the mask for all the previous tasks so far a_gem_logit_mask[:] = 0 for tt in range(task): a_gem_logit_mask[tt][task_labels[tt]] = 1.0 if KEEP_EPISODIC_MEMORY_FULL: mem_sample_mask = np.random.choice(episodic_mem_size, EPS_MEM_BATCH_SIZE, replace=False) # Sample without replacement so that we don't sample an example more than once else: if episodic_filled_counter <= EPS_MEM_BATCH_SIZE: mem_sample_mask = np.arange(episodic_filled_counter) else: # Sample a random subset from episodic memory buffer mem_sample_mask = np.random.choice(episodic_filled_counter, EPS_MEM_BATCH_SIZE, replace=False) # Sample without replacement so that we don't sample an example more than once # Store the reference gradient ref_feed_dict = {model.x: episodic_images[mem_sample_mask], model.y_: episodic_labels[mem_sample_mask], model.keep_prob: 1.0, model.train_phase: True} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} ref_feed_dict.update(logit_mask_dict) ref_feed_dict[model.mem_batch_size] = float(len(mem_sample_mask)) sess.run(model.store_ref_grads, feed_dict=ref_feed_dict) # Compute the gradient for current task and project if need be a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][task_labels[task]] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) elif model.imp_method == 'RWALK': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Update fisher and importance score after every few iterations if (iters + 1) % model.fisher_update_after == 0: # Update the importance score using distance in riemannian manifold sess.run(model.update_big_omega_riemann) # Now that the score is updated, compute the new value for running Fisher sess.run(model.set_running_fisher) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Reset the delta_L sess.run([model.reset_small_omega]) _, _, _, _, loss = sess.run([model.set_tmp_fisher, model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) if (iters % 50 == 0): print('Step {:d} {:.3f}'.format(iters, loss)) if (math.isnan(loss)): print('ERROR: NaNs NaNs NaNs!!!') break_training = 1 break print('\t\t\t\tTraining for Task%d done!'%(task)) if break_training: break # Compute the inter-task updates, Fisher/ importance scores etc # Don't calculate the task updates for the last task if task < (len(task_labels) - 1): model.task_updates(sess, task, task_train_images, task_labels[task]) # TODO: For MAS, should the gradients be for current task or all the previous tasks print('\t\t\t\tTask updates after Task%d done!'%(task)) # If importance method is '*-GEM' then store the episodic memory for the task if 'GEM' in model.imp_method: data_to_sample_from = { 'images': task_train_images, 'labels': task_train_labels, } if model.imp_method == 'S-GEM': # Get the important samples from the current task if is_herding: # Sampling based on MoF # Compute the features of training data features_dim = model.image_feature_dim features = np.zeros([num_train_examples, features_dim]) samples_at_a_time = 32 residual = num_train_examples % samples_at_a_time for i in range(num_train_examples// samples_at_a_time): offset = i * samples_at_a_time features[offset:offset+samples_at_a_time] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+samples_at_a_time], model.y_: task_train_labels[offset:offset+samples_at_a_time], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) if residual > 0: offset = (i + 1) * samples_at_a_time features[offset:offset+residual] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+residual], model.y_: task_train_labels[offset:offset+residual], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) imp_images, imp_labels = sample_from_dataset_icarl(data_to_sample_from, features, task_labels[task], SAMPLES_PER_CLASS) else: # Random sampling # Do the uniform sampling/ only get examples from current task importance_array = np.ones(num_train_examples, dtype=np.float32) imp_images, imp_labels = sample_from_dataset(data_to_sample_from, importance_array, task_labels[task], SAMPLES_PER_CLASS) task_memory = { 'images': deepcopy(imp_images), 'labels': deepcopy(imp_labels), } task_based_memory.append(task_memory) elif model.imp_method == 'A-GEM': if is_herding: # Sampling based on MoF # Compute the features of training data features_dim = model.image_feature_dim features = np.zeros([num_train_examples, features_dim]) samples_at_a_time = 32 residual = num_train_examples % samples_at_a_time for i in range(num_train_examples// samples_at_a_time): offset = i * samples_at_a_time features[offset:offset+samples_at_a_time] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+samples_at_a_time], model.y_: task_train_labels[offset:offset+samples_at_a_time], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) if residual > 0: offset = (i + 1) * samples_at_a_time features[offset:offset+residual] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+residual], model.y_: task_train_labels[offset:offset+residual], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) if KEEP_EPISODIC_MEMORY_FULL: update_episodic_memory(data_to_sample_from, features, episodic_mem_size, task, episodic_images, episodic_labels, task_labels=task_labels[task], is_herding=True) else: imp_images, imp_labels = sample_from_dataset_icarl(data_to_sample_from, features, task_labels[task], SAMPLES_PER_CLASS) else: # Random sampling # Do the uniform sampling/ only get examples from current task importance_array = np.ones(num_train_examples, dtype=np.float32) if KEEP_EPISODIC_MEMORY_FULL: update_episodic_memory(data_to_sample_from, importance_array, episodic_mem_size, task, episodic_images, episodic_labels) else: imp_images, imp_labels = sample_from_dataset(data_to_sample_from, importance_array, task_labels[task], SAMPLES_PER_CLASS) if not KEEP_EPISODIC_MEMORY_FULL: # Fill the memory to always keep M/T samples per task total_imp_samples = imp_images.shape[0] eps_offset = task * total_imp_samples episodic_images[eps_offset:eps_offset+total_imp_samples] = imp_images episodic_labels[eps_offset:eps_offset+total_imp_samples] = imp_labels episodic_filled_counter += total_imp_samples print('Unique labels in the episodic memory: {}'.format(np.unique(np.nonzero(episodic_labels)[1]))) # Inspect episodic memory if DEBUG_EPISODIC_MEMORY: # Which labels are present in the memory unique_labels = np.unique(np.nonzero(episodic_labels)[-1]) print('Unique Labels present in the episodic memory'.format(unique_labels)) print('Labels count:') for lbl in unique_labels: print('Label {}: {} samples'.format(lbl, np.where(np.nonzero(episodic_labels)[-1] == lbl)[0].size)) # Is there any space which is not filled print('Empty space: {}'.format(np.where(np.sum(episodic_labels, axis=1) == 0))) print('Episodic memory of {} images at task {} saved!'.format(episodic_images.shape[0], task)) # If sampling flag is set, store few of the samples from previous task if do_sampling: # Do the uniform sampling/ only get examples from current task importance_array = np.ones([task_train_images.shape[0]], dtype=np.float32) # Get the important samples from the current task task_data = { 'images': task_tr_images, 'labels': task_tr_labels, } imp_images, imp_labels = sample_from_dataset(task_data, importance_array, task_labels[task], SAMPLES_PER_CLASS) if imp_images is not None: if last_task_x is None: last_task_x = imp_images last_task_y_ = imp_labels else: last_task_x = np.concatenate((last_task_x, imp_images), axis=0) last_task_y_ = np.concatenate((last_task_y_, imp_labels), axis=0) # Delete the importance array now that you don't need it in the current run del importance_array print('\t\t\t\tEpisodic memory is saved for Task%d!'%(task)) if cross_validate_mode: # Only evaluate after the last task if (task == model.num_tasks - 1) or MULTI_TASK: # List to store accuracy for all the tasks for the current trained model ftask = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task) elif train_single_epoch: fbatch = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task) print('Task: {} Acc: {}'.format(task, fbatch)) ftask.append(fbatch) else: # Multi-epoch training, so compute accuracy at the end ftask = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task) if SAVE_MODEL_PARAMS: save(saver, sess, SNAPSHOT_DIR, iters) if not cross_validate_mode: # Store the accuracies computed at task T in a list evals.append(np.array(ftask)) # Reset the optimizer model.reset_optimizer(sess) #-> End for loop task if not cross_validate_mode: runs.append(np.array(evals)) if break_training: break # End for loop runid if cross_validate_mode: return np.mean(ftask), task_labels_dataset else: runs = np.array(runs) return runs, task_labels_dataset def test_task_sequence(model, sess, test_data, test_tasks, task): """ Snapshot the current performance """ final_acc = np.zeros(model.num_tasks) if model.imp_method == 'A-GEM': logit_mask = np.zeros([model.num_tasks, TOTAL_CLASSES]) else: logit_mask = np.zeros(TOTAL_CLASSES) for tt, labels in enumerate(test_tasks): if not MULTI_TASK: if tt > task: return final_acc task_test_images, task_test_labels = load_task_specific_data(test_data, labels) total_test_samples = task_test_images.shape[0] samples_at_a_time = 10 total_corrects = 0 logit_mask[:] = 0 if model.imp_method == 'A-GEM': logit_mask[tt][labels] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, logit_mask)} else: logit_mask[labels] = 1.0 for i in range(total_test_samples/ samples_at_a_time): offset = i*samples_at_a_time feed_dict = {model.x: task_test_images[offset:offset+samples_at_a_time], model.y_: task_test_labels[offset:offset+samples_at_a_time], model.keep_prob: 1.0, model.train_phase: False} if model.imp_method == 'A-GEM': feed_dict.update(logit_mask_dict) total_corrects += np.sum(sess.run(model.correct_predictions[tt], feed_dict=feed_dict)) else: feed_dict[model.output_mask] = logit_mask total_corrects += np.sum(sess.run(model.correct_predictions, feed_dict=feed_dict)) # Compute the corrects on residuals offset = (i+1)*samples_at_a_time num_residuals = total_test_samples % samples_at_a_time feed_dict = {model.x: task_test_images[offset:offset+num_residuals], model.y_: task_test_labels[offset:offset+num_residuals], model.keep_prob: 1.0, model.train_phase: False} if model.imp_method == 'A-GEM': feed_dict.update(logit_mask_dict) total_corrects += np.sum(sess.run(model.correct_predictions[tt], feed_dict=feed_dict)) else: feed_dict[model.output_mask] = logit_mask total_corrects += np.sum(sess.run(model.correct_predictions, feed_dict=feed_dict)) # Mean accuracy on the task acc = total_corrects/ float(total_test_samples) final_acc[tt] = acc return final_acc def main(): """ Create the model and start the training """ # Get the CL arguments args = get_arguments() # Check if the network architecture is valid if args.arch not in VALID_ARCHS: raise ValueError("Network architecture %s is not supported!"%(args.arch)) # Check if the method to compute importance is valid if args.imp_method not in MODELS: raise ValueError("Importance measure %s is undefined!"%(args.imp_method)) # Check if the optimizer is valid if args.optim not in VALID_OPTIMS: raise ValueError("Optimizer %s is undefined!"%(args.optim)) # Create log directories to store the results if not os.path.exists(args.log_dir): print('Log directory %s created!'%(args.log_dir)) os.makedirs(args.log_dir) if args.online_cross_val: num_tasks = K_FOR_CROSS_VAL else: num_tasks = NUM_TASKS - K_FOR_CROSS_VAL # Load the split CUB dataset data_labs = [np.arange(TOTAL_CLASSES)] datasets = construct_split_cub(data_labs, args.data_dir, CUB_TRAIN_LIST, CUB_TEST_LIST, IMG_HEIGHT, IMG_WIDTH) if args.cross_validate_mode: #models_list = MODELS #learning_rate_list = [0.3, 0.1, 0.01, 0.003, 0.001] models_list = [args.imp_method] learning_rate_list = [0.03] else: models_list = [args.imp_method] for imp_method in models_list: if imp_method == 'VAN': synap_stgth_list = [0] if args.online_cross_val or args.cross_validate_mode: pass else: learning_rate_list = [0.03] elif imp_method == 'PI': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10] else: synap_stgth_list = [0.1] learning_rate_list = [0.03] elif imp_method == 'EWC' or imp_method == 'M-EWC': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [1] learning_rate_list = [0.03] elif imp_method == 'MAS': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [0.1] learning_rate_list = [0.03] elif imp_method == 'RWALK': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [1] learning_rate_list = [0.03] elif imp_method == 'S-GEM': synap_stgth_list = [0] if args.online_cross_val: pass else: learning_rate_list = [args.learning_rate] elif imp_method == 'A-GEM': synap_stgth_list = [0] if args.online_cross_val or args.cross_validate_mode: pass else: learning_rate_list = [0.03] for synap_stgth in synap_stgth_list: for lr in learning_rate_list: # Generate the experiment key and store the meta data in a file exper_meta_data = {'ARCH': args.arch, 'DATASET': 'SPLIT_CUB', 'NUM_RUNS': args.num_runs, 'TRAIN_SINGLE_EPOCH': args.train_single_epoch, 'IMP_METHOD': imp_method, 'SYNAP_STGTH': synap_stgth, 'FISHER_EMA_DECAY': args.fisher_ema_decay, 'FISHER_UPDATE_AFTER': args.fisher_update_after, 'OPTIM': args.optim, 'LR': lr, 'BATCH_SIZE': args.batch_size, 'EPS_MEMORY': args.do_sampling, 'MEM_SIZE': args.mem_size, 'IS_HERDING': args.is_herding} experiment_id = "SPLIT_CUB_ONE_HOT_HERDING_%r_%s_%r_%s_%s_%s_%s_%r_%s-"%(args.is_herding, args.arch, args.train_single_epoch, imp_method, str(synap_stgth).replace('.', '_'), str(lr).replace('.', '_'), str(args.batch_size), args.do_sampling, str(args.mem_size)) + datetime.datetime.now().strftime("%y-%m-%d-%H-%M") snapshot_experiment_meta_data(args.log_dir, experiment_id, exper_meta_data) # Reset the default graph #tf.reset_default_graph() graph = tf.Graph() with graph.as_default(): # Set the random seed tf.set_random_seed(RANDOM_SEED) # Define Input and Output of the model x = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) y_ = tf.placeholder(tf.float32, shape=[None, TOTAL_CLASSES]) if not args.train_single_epoch: # Define ops for data augmentation x_aug = image_scaling(x) x_aug = random_crop_and_pad_image(x_aug, IMG_HEIGHT, IMG_WIDTH) # Define the optimizer if args.optim == 'ADAM': opt = tf.train.AdamOptimizer(learning_rate=lr) elif args.optim == 'SGD': opt = tf.train.GradientDescentOptimizer(learning_rate=lr) elif args.optim == 'MOMENTUM': base_lr = tf.constant(lr) learning_rate = tf.scalar_mul(base_lr, tf.pow((1 - train_step / training_iters), OPT_POWER)) opt = tf.train.MomentumOptimizer(lr, OPT_MOMENTUM) # Create the Model/ contruct the graph if args.train_single_epoch: # When training using a single epoch then there is no need for data augmentation model = Model(x, y_, num_tasks, opt, imp_method, synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch, is_ATT_DATASET=True) else: model = Model(x_aug, y_, num_tasks, opt, imp_method, synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch, is_ATT_DATASET=True, x_test=x) # Set up tf session and initialize variables. config = tf.ConfigProto() config.gpu_options.allow_growth = True time_start = time.time() with tf.Session(config=config, graph=graph) as sess: saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=100) runs, task_labels_dataset = train_task_sequence(model, sess, saver, datasets, args.cross_validate_mode, args.train_single_epoch, args.do_sampling, args.is_herding, args.mem_size, args.train_iters, args.batch_size, args.num_runs, args.init_checkpoint, args.online_cross_val, args.random_seed) # Close the session sess.close() time_end = time.time() time_spent = time_end - time_start print('Time spent: {}'.format(time_spent)) # Clean up del model if args.cross_validate_mode: # If cross-validation flag is enabled, store the stuff in a text file cross_validate_dump_file = args.log_dir + '/' + 'SPLIT_CUB_%s_%s'%(imp_method, args.optim) + '.txt' with open(cross_validate_dump_file, 'a') as f: f.write('HERDING: {} \t ARCH: {} \t LR:{} \t LAMBDA: {} \t ACC: {}\n'.format(args.is_herding, args.arch, lr, synap_stgth, runs)) else: # Store all the results in one dictionary to process later exper_acc = dict(mean=runs) exper_labels = dict(labels=task_labels_dataset) # Store the experiment output to a file snapshot_experiment_eval(args.log_dir, experiment_id, exper_acc) snapshot_task_labels(args.log_dir, experiment_id, exper_labels) if __name__ == '__main__': main()
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Training script for split CIFAR 100 experiment. """ from __future__ import print_function import argparse import os import sys import math import time import datetime import numpy as np import tensorflow as tf from copy import deepcopy from six.moves import cPickle as pickle from utils.data_utils import construct_split_cifar from utils.utils import get_sample_weights, sample_from_dataset, update_episodic_memory, concatenate_datasets, samples_for_each_class, sample_from_dataset_icarl, compute_fgt, load_task_specific_data from utils.utils import average_acc_stats_across_runs, average_fgt_stats_across_runs, update_reservior from utils.vis_utils import plot_acc_multiple_runs, plot_histogram, snapshot_experiment_meta_data, snapshot_experiment_eval, snapshot_task_labels from model import Model ############################################################### ################ Some definitions ############################# ### These will be edited by the command line options ########## ############################################################### ## Training Options NUM_RUNS = 5 # Number of experiments to average over TRAIN_ITERS = 2000 # Number of training iterations per task BATCH_SIZE = 16 LEARNING_RATE = 0.1 RANDOM_SEED = 1234 VALID_OPTIMS = ['SGD', 'MOMENTUM', 'ADAM'] OPTIM = 'SGD' OPT_MOMENTUM = 0.9 OPT_POWER = 0.9 VALID_ARCHS = ['CNN', 'RESNET-S', 'RESNET-B', 'VGG'] ARCH = 'RESNET-S' ## Model options MODELS = ['VAN', 'PI', 'EWC', 'MAS', 'RWALK', 'M-EWC', 'S-GEM', 'A-GEM', 'FTR_EXT', 'PNN', 'ER'] #List of valid models IMP_METHOD = 'EWC' SYNAP_STGTH = 75000 FISHER_EMA_DECAY = 0.9 # Exponential moving average decay factor for Fisher computation (online Fisher) FISHER_UPDATE_AFTER = 50 # Number of training iterations for which the F_{\theta}^t is computed (see Eq. 10 in RWalk paper) SAMPLES_PER_CLASS = 13 IMG_HEIGHT = 32 IMG_WIDTH = 32 IMG_CHANNELS = 3 TOTAL_CLASSES = 100 # Total number of classes in the dataset VISUALIZE_IMPORTANCE_MEASURE = False MEASURE_CONVERGENCE_AFTER = 0.9 EPS_MEM_BATCH_SIZE = 256 DEBUG_EPISODIC_MEMORY = False K_FOR_CROSS_VAL = 3 TIME_MY_METHOD = False COUNT_VIOLATONS = False MEASURE_PERF_ON_EPS_MEMORY = False ## Logging, saving and testing options LOG_DIR = './split_cifar_results' RESNET18_CIFAR10_CHECKPOINT = './resnet-18-pretrained-cifar10/model.ckpt-19999' ## Evaluation options ## Task split NUM_TASKS = 20 MULTI_TASK = False # Define function to load/ store training weights. We will use ImageNet initialization later on def save(saver, sess, logdir, step): '''Save weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. logdir: path to the snapshots directory. step: current training step. ''' model_name = 'model.ckpt' checkpoint_path = os.path.join(logdir, model_name) if not os.path.exists(logdir): os.makedirs(logdir) saver.save(sess, checkpoint_path, global_step=step) print('The checkpoint has been created.') def load(saver, sess, ckpt_path): '''Load trained weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. ckpt_path: path to checkpoint file with parameters. ''' saver.restore(sess, ckpt_path) print("Restored model parameters from {}".format(ckpt_path)) def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Script for split cifar experiment.") parser.add_argument("--cross-validate-mode", action="store_true", help="If option is chosen then snapshoting after each batch is disabled") parser.add_argument("--online-cross-val", action="store_true", help="If option is chosen then enable the online cross validation of the learning rate") parser.add_argument("--train-single-epoch", action="store_true", help="If option is chosen then train for single epoch") parser.add_argument("--eval-single-head", action="store_true", help="If option is chosen then evaluate on a single head setting.") parser.add_argument("--arch", type=str, default=ARCH, help="Network Architecture for the experiment.\ \n \nSupported values: %s"%(VALID_ARCHS)) parser.add_argument("--num-runs", type=int, default=NUM_RUNS, help="Total runs/ experiments over which accuracy is averaged.") parser.add_argument("--train-iters", type=int, default=TRAIN_ITERS, help="Number of training iterations for each task.") parser.add_argument("--batch-size", type=int, default=BATCH_SIZE, help="Mini-batch size for each task.") parser.add_argument("--random-seed", type=int, default=RANDOM_SEED, help="Random Seed.") parser.add_argument("--learning-rate", type=float, default=LEARNING_RATE, help="Starting Learning rate for each task.") parser.add_argument("--optim", type=str, default=OPTIM, help="Optimizer for the experiment. \ \n \nSupported values: %s"%(VALID_OPTIMS)) parser.add_argument("--imp-method", type=str, default=IMP_METHOD, help="Model to be used for LLL. \ \n \nSupported values: %s"%(MODELS)) parser.add_argument("--synap-stgth", type=float, default=SYNAP_STGTH, help="Synaptic strength for the regularization.") parser.add_argument("--fisher-ema-decay", type=float, default=FISHER_EMA_DECAY, help="Exponential moving average decay for Fisher calculation at each step.") parser.add_argument("--fisher-update-after", type=int, default=FISHER_UPDATE_AFTER, help="Number of training iterations after which the Fisher will be updated.") parser.add_argument("--mem-size", type=int, default=SAMPLES_PER_CLASS, help="Total size of episodic memory.") parser.add_argument("--eps-mem-batch", type=int, default=EPS_MEM_BATCH_SIZE, help="Number of samples per class from previous tasks.") parser.add_argument("--log-dir", type=str, default=LOG_DIR, help="Directory where the plots and model accuracies will be stored.") return parser.parse_args() def train_task_sequence(model, sess, datasets, args): """ Train and evaluate LLL system such that we only see a example once Args: Returns: dict A dictionary containing mean and stds for the experiment """ # List to store accuracy for each run runs = [] task_labels_dataset = [] if model.imp_method == 'A-GEM' or model.imp_method == 'ER': use_episodic_memory = True else: use_episodic_memory = False batch_size = args.batch_size # Loop over number of runs to average over for runid in range(args.num_runs): print('\t\tRun %d:'%(runid)) # Initialize the random seeds np.random.seed(args.random_seed+runid) # Get the task labels from the total number of tasks and full label space task_labels = [] classes_per_task = TOTAL_CLASSES// NUM_TASKS total_classes = classes_per_task * model.num_tasks if args.online_cross_val: label_array = np.arange(total_classes) else: class_label_offset = K_FOR_CROSS_VAL * classes_per_task label_array = np.arange(class_label_offset, total_classes+class_label_offset) np.random.shuffle(label_array) for tt in range(model.num_tasks): tt_offset = tt*classes_per_task task_labels.append(list(label_array[tt_offset:tt_offset+classes_per_task])) print('Task: {}, Labels:{}'.format(tt, task_labels[tt])) # Store the task labels task_labels_dataset.append(task_labels) # Set episodic memory size episodic_mem_size = args.mem_size * total_classes # Initialize all the variables in the model sess.run(tf.global_variables_initializer()) # Run the init ops model.init_updates(sess) # List to store accuracies for a run evals = [] # List to store the classes that we have so far - used at test time test_labels = [] if use_episodic_memory: # Reserve a space for episodic memory episodic_images = np.zeros([episodic_mem_size, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) episodic_labels = np.zeros([episodic_mem_size, TOTAL_CLASSES]) episodic_filled_counter = 0 nd_logit_mask = np.zeros([model.num_tasks, TOTAL_CLASSES]) count_cls = np.zeros(TOTAL_CLASSES, dtype=np.int32) episodic_filled_counter = 0 examples_seen_so_far = 0 # Mask for softmax logit_mask = np.zeros(TOTAL_CLASSES) if COUNT_VIOLATONS: violation_count = np.zeros(model.num_tasks) vc = 0 # Training loop for all the tasks for task in range(len(task_labels)): print('\t\tTask %d:'%(task)) # If not the first task then restore weights from previous task if(task > 0 and model.imp_method != 'PNN'): model.restore(sess) if model.imp_method == 'PNN': pnn_train_phase = np.array(np.zeros(model.num_tasks), dtype=np.bool) pnn_train_phase[task] = True pnn_logit_mask = np.zeros([model.num_tasks, TOTAL_CLASSES]) # If not in the cross validation mode then concatenate the train and validation sets task_tr_images, task_tr_labels = load_task_specific_data(datasets[0]['train'], task_labels[task]) task_val_images, task_val_labels = load_task_specific_data(datasets[0]['validation'], task_labels[task]) task_train_images, task_train_labels = concatenate_datasets(task_tr_images, task_tr_labels, task_val_images, task_val_labels) # If multi_task is set then train using all the datasets of all the tasks if MULTI_TASK: if task == 0: for t_ in range(1, len(task_labels)): task_tr_images, task_tr_labels = load_task_specific_data(datasets[0]['train'], task_labels[t_]) task_train_images = np.concatenate((task_train_images, task_tr_images), axis=0) task_train_labels = np.concatenate((task_train_labels, task_tr_labels), axis=0) else: # Skip training for this task continue print('Received {} images, {} labels at task {}'.format(task_train_images.shape[0], task_train_labels.shape[0], task)) print('Unique labels in the task: {}'.format(np.unique(np.nonzero(task_train_labels)[1]))) # Test for the tasks that we've seen so far test_labels += task_labels[task] # Assign equal weights to all the examples task_sample_weights = np.ones([task_train_labels.shape[0]], dtype=np.float32) num_train_examples = task_train_images.shape[0] logit_mask[:] = 0 # Train a task observing sequence of data if args.train_single_epoch: # Ceiling operation num_iters = (num_train_examples + batch_size - 1) // batch_size if args.cross_validate_mode: logit_mask[task_labels[task]] = 1.0 else: num_iters = args.train_iters # Set the mask only once before starting the training for the task logit_mask[task_labels[task]] = 1.0 if MULTI_TASK: logit_mask[:] = 1.0 # Randomly suffle the training examples perm = np.arange(num_train_examples) np.random.shuffle(perm) train_x = task_train_images[perm] train_y = task_train_labels[perm] task_sample_weights = task_sample_weights[perm] # Array to store accuracies when training for task T ftask = [] # Number of iterations after which convergence is checked convergence_iters = int(num_iters * MEASURE_CONVERGENCE_AFTER) # Training loop for task T for iters in range(num_iters): if args.train_single_epoch and not args.cross_validate_mode and not MULTI_TASK: if (iters <= 20) or (iters > 20 and iters % 50 == 0): # Snapshot the current performance across all tasks after each mini-batch fbatch = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task) ftask.append(fbatch) if model.imp_method == 'PNN': pnn_train_phase[:] = False pnn_train_phase[task] = True pnn_logit_mask[:] = 0 pnn_logit_mask[task][task_labels[task]] = 1.0 elif model.imp_method == 'A-GEM': nd_logit_mask[:] = 0 nd_logit_mask[task][task_labels[task]] = 1.0 else: # Set the output labels over which the model needs to be trained logit_mask[:] = 0 logit_mask[task_labels[task]] = 1.0 if args.train_single_epoch: offset = iters * batch_size if (offset+batch_size <= num_train_examples): residual = batch_size else: residual = num_train_examples - offset if model.imp_method == 'PNN': feed_dict = {model.x: train_x[offset:offset+residual], model.y_[task]: train_y[offset:offset+residual], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5} train_phase_dict = {m_t: i_t for (m_t, i_t) in zip(model.train_phase, pnn_train_phase)} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, pnn_logit_mask)} feed_dict.update(train_phase_dict) feed_dict.update(logit_mask_dict) else: feed_dict = {model.x: train_x[offset:offset+residual], model.y_: train_y[offset:offset+residual], model.sample_weights: task_sample_weights[offset:offset+residual], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5, model.train_phase: True} else: offset = (iters * batch_size) % (num_train_examples - batch_size) if model.imp_method == 'PNN': feed_dict = {model.x: train_x[offset:offset+batch_size], model.y_[task]: train_y[offset:offset+batch_size], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5} train_phase_dict = {m_t: i_t for (m_t, i_t) in zip(model.train_phase, pnn_train_phase)} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, pnn_logit_mask)} feed_dict.update(train_phase_dict) feed_dict.update(logit_mask_dict) else: feed_dict = {model.x: train_x[offset:offset+batch_size], model.y_: train_y[offset:offset+batch_size], model.sample_weights: task_sample_weights[offset:offset+batch_size], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5, model.train_phase: True} if model.imp_method == 'VAN': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'PNN': _, loss = sess.run([model.train[task], model.unweighted_entropy[task]], feed_dict=feed_dict) elif model.imp_method == 'FTR_EXT': feed_dict[model.output_mask] = logit_mask if task == 0: _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) else: _, loss = sess.run([model.train_classifier, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'EWC' or model.imp_method == 'M-EWC': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Update fisher after every few iterations if (iters + 1) % model.fisher_update_after == 0: sess.run(model.set_running_fisher) sess.run(model.reset_tmp_fisher) if (iters >= convergence_iters) and (model.imp_method == 'M-EWC'): _, _, _, _, loss = sess.run([model.weights_old_ops_grouped, model.set_tmp_fisher, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) else: _, _, loss = sess.run([model.set_tmp_fisher, model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'PI': feed_dict[model.output_mask] = logit_mask _, _, _, loss = sess.run([model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'MAS': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'A-GEM': if task == 0: nd_logit_mask[:] = 0 nd_logit_mask[task][task_labels[task]] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, nd_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: ## Compute and store the reference gradients on the previous tasks # Set the mask for all the previous tasks so far nd_logit_mask[:] = 0 for tt in range(task): nd_logit_mask[tt][task_labels[tt]] = 1.0 if episodic_filled_counter <= args.eps_mem_batch: mem_sample_mask = np.arange(episodic_filled_counter) else: # Sample a random subset from episodic memory buffer mem_sample_mask = np.random.choice(episodic_filled_counter, args.eps_mem_batch, replace=False) # Sample without replacement so that we don't sample an example more than once # Store the reference gradient ref_feed_dict = {model.x: episodic_images[mem_sample_mask], model.y_: episodic_labels[mem_sample_mask], model.keep_prob: 1.0, model.train_phase: True} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, nd_logit_mask)} ref_feed_dict.update(logit_mask_dict) ref_feed_dict[model.mem_batch_size] = float(len(mem_sample_mask)) sess.run(model.store_ref_grads, feed_dict=ref_feed_dict) # Compute the gradient for current task and project if need be nd_logit_mask[:] = 0 nd_logit_mask[task][task_labels[task]] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, nd_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size if COUNT_VIOLATONS: vc, _, loss = sess.run([model.violation_count, model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) else: _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) # Put the batch in the ring buffer for er_x, er_y_ in zip(train_x[offset:offset+residual], train_y[offset:offset+residual]): cls = np.unique(np.nonzero(er_y_))[-1] # Write the example at the location pointed by count_cls[cls] cls_to_index_map = np.where(np.array(task_labels[task]) == cls)[0][0] with_in_task_offset = args.mem_size * cls_to_index_map mem_index = count_cls[cls] + with_in_task_offset + episodic_filled_counter episodic_images[mem_index] = er_x episodic_labels[mem_index] = er_y_ count_cls[cls] = (count_cls[cls] + 1) % args.mem_size elif model.imp_method == 'RWALK': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Update fisher and importance score after every few iterations if (iters + 1) % model.fisher_update_after == 0: # Update the importance score using distance in riemannian manifold sess.run(model.update_big_omega_riemann) # Now that the score is updated, compute the new value for running Fisher sess.run(model.set_running_fisher) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Reset the delta_L sess.run([model.reset_small_omega]) _, _, _, _, loss = sess.run([model.set_tmp_fisher, model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'ER': mem_filled_so_far = examples_seen_so_far if (examples_seen_so_far < episodic_mem_size) else episodic_mem_size if mem_filled_so_far < args.eps_mem_batch: er_mem_indices = np.arange(mem_filled_so_far) else: er_mem_indices = np.random.choice(mem_filled_so_far, args.eps_mem_batch, replace=False) np.random.shuffle(er_mem_indices) nd_logit_mask[:] = 0 for tt in range(task+1): nd_logit_mask[tt][task_labels[tt]] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, nd_logit_mask)} er_train_x_batch = np.concatenate((episodic_images[er_mem_indices], train_x[offset:offset+residual]), axis=0) er_train_y_batch = np.concatenate((episodic_labels[er_mem_indices], train_y[offset:offset+residual]), axis=0) feed_dict = {model.x: er_train_x_batch, model.y_: er_train_y_batch, model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 1.0, model.train_phase: True} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = float(er_train_x_batch.shape[0]) _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) # Reservoir update for er_x, er_y_ in zip(train_x[offset:offset+residual], train_y[offset:offset+residual]): update_reservior(er_x, er_y_, episodic_images, episodic_labels, episodic_mem_size, examples_seen_so_far) examples_seen_so_far += 1 if (iters % 100 == 0): print('Step {:d} {:.3f}'.format(iters, loss)) if (math.isnan(loss)): print('ERROR: NaNs NaNs NaNs!!!') sys.exit(0) print('\t\t\t\tTraining for Task%d done!'%(task)) if use_episodic_memory: episodic_filled_counter += args.mem_size * classes_per_task if model.imp_method == 'A-GEM': if COUNT_VIOLATONS: violation_count[task] = vc print('Task {}: Violation Count: {}'.format(task, violation_count)) sess.run(model.reset_violation_count, feed_dict=feed_dict) # Compute the inter-task updates, Fisher/ importance scores etc # Don't calculate the task updates for the last task if (task < (len(task_labels) - 1)) or MEASURE_PERF_ON_EPS_MEMORY: model.task_updates(sess, task, task_train_images, task_labels[task]) # TODO: For MAS, should the gradients be for current task or all the previous tasks print('\t\t\t\tTask updates after Task%d done!'%(task)) if VISUALIZE_IMPORTANCE_MEASURE: if runid == 0: for i in range(len(model.fisher_diagonal_at_minima)): if i == 0: flatten_fisher = np.array(model.fisher_diagonal_at_minima[i].eval()).flatten() else: flatten_fisher = np.concatenate((flatten_fisher, np.array(model.fisher_diagonal_at_minima[i].eval()).flatten())) #flatten_fisher [flatten_fisher > 0.1] = 0.1 if args.train_single_epoch: plot_histogram(flatten_fisher, 100, '/private/home/arslanch/Dropbox/LLL_experiments/Single_Epoch/importance_vis/single_epoch/m_ewc/hist_fisher_task%s.png'%(task)) else: plot_histogram(flatten_fisher, 100, '/private/home/arslanch/Dropbox/LLL_experiments/Single_Epoch/importance_vis/single_epoch/m_ewc/hist_fisher_task%s.png'%(task)) if args.train_single_epoch and not args.cross_validate_mode: fbatch = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task) print('Task: {}, Acc: {}'.format(task, fbatch)) ftask.append(fbatch) ftask = np.array(ftask) if model.imp_method == 'PNN': pnn_train_phase[:] = False pnn_train_phase[task] = True pnn_logit_mask[:] = 0 pnn_logit_mask[task][task_labels[task]] = 1.0 else: if MEASURE_PERF_ON_EPS_MEMORY: eps_mem = { 'images': episodic_images, 'labels': episodic_labels, } # Measure perf on episodic memory ftask = test_task_sequence(model, sess, eps_mem, task_labels, task, classes_per_task=classes_per_task) else: # List to store accuracy for all the tasks for the current trained model ftask = test_task_sequence(model, sess, datasets[0]['test'], task_labels, task) print('Task: {}, Acc: {}'.format(task, ftask)) # Store the accuracies computed at task T in a list evals.append(ftask) # Reset the optimizer model.reset_optimizer(sess) #-> End for loop task runs.append(np.array(evals)) # End for loop runid runs = np.array(runs) return runs, task_labels_dataset def test_task_sequence(model, sess, test_data, test_tasks, task, classes_per_task=0): """ Snapshot the current performance """ if TIME_MY_METHOD: # Only compute the training time return np.zeros(model.num_tasks) final_acc = np.zeros(model.num_tasks) if model.imp_method == 'PNN' or model.imp_method == 'A-GEM' or model.imp_method == 'ER': logit_mask = np.zeros([model.num_tasks, TOTAL_CLASSES]) else: logit_mask = np.zeros(TOTAL_CLASSES) if MEASURE_PERF_ON_EPS_MEMORY: for tt, labels in enumerate(test_tasks): # Multi-head evaluation setting logit_mask[:] = 0 logit_mask[labels] = 1.0 mem_offset = tt*SAMPLES_PER_CLASS*classes_per_task feed_dict = {model.x: test_data['images'][mem_offset:mem_offset+SAMPLES_PER_CLASS*classes_per_task], model.y_: test_data['labels'][mem_offset:mem_offset+SAMPLES_PER_CLASS*classes_per_task], model.keep_prob: 1.0, model.train_phase: False, model.output_mask: logit_mask} acc = model.accuracy.eval(feed_dict = feed_dict) final_acc[tt] = acc return final_acc for tt, labels in enumerate(test_tasks): if not MULTI_TASK: if tt > task: return final_acc task_test_images, task_test_labels = load_task_specific_data(test_data, labels) if model.imp_method == 'PNN': pnn_train_phase = np.array(np.zeros(model.num_tasks), dtype=np.bool) logit_mask[:] = 0 logit_mask[tt][labels] = 1.0 feed_dict = {model.x: task_test_images, model.y_[tt]: task_test_labels, model.keep_prob: 1.0} train_phase_dict = {m_t: i_t for (m_t, i_t) in zip(model.train_phase, pnn_train_phase)} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, logit_mask)} feed_dict.update(train_phase_dict) feed_dict.update(logit_mask_dict) acc = model.accuracy[tt].eval(feed_dict = feed_dict) elif model.imp_method == 'A-GEM' or model.imp_method == 'ER': logit_mask[:] = 0 logit_mask[tt][labels] = 1.0 feed_dict = {model.x: task_test_images, model.y_: task_test_labels, model.keep_prob: 1.0, model.train_phase: False} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, logit_mask)} feed_dict.update(logit_mask_dict) acc = model.accuracy[tt].eval(feed_dict = feed_dict) else: logit_mask[:] = 0 logit_mask[labels] = 1.0 feed_dict = {model.x: task_test_images, model.y_: task_test_labels, model.keep_prob: 1.0, model.train_phase: False, model.output_mask: logit_mask} acc = model.accuracy.eval(feed_dict = feed_dict) final_acc[tt] = acc return final_acc def main(): """ Create the model and start the training """ # Get the CL arguments args = get_arguments() # Check if the network architecture is valid if args.arch not in VALID_ARCHS: raise ValueError("Network architecture %s is not supported!"%(args.arch)) # Check if the method to compute importance is valid if args.imp_method not in MODELS: raise ValueError("Importance measure %s is undefined!"%(args.imp_method)) # Check if the optimizer is valid if args.optim not in VALID_OPTIMS: raise ValueError("Optimizer %s is undefined!"%(args.optim)) # Create log directories to store the results if not os.path.exists(args.log_dir): print('Log directory %s created!'%(args.log_dir)) os.makedirs(args.log_dir) # Generate the experiment key and store the meta data in a file exper_meta_data = {'ARCH': args.arch, 'DATASET': 'SPLIT_CIFAR', 'NUM_RUNS': args.num_runs, 'TRAIN_SINGLE_EPOCH': args.train_single_epoch, 'IMP_METHOD': args.imp_method, 'SYNAP_STGTH': args.synap_stgth, 'FISHER_EMA_DECAY': args.fisher_ema_decay, 'FISHER_UPDATE_AFTER': args.fisher_update_after, 'OPTIM': args.optim, 'LR': args.learning_rate, 'BATCH_SIZE': args.batch_size, 'MEM_SIZE': args.mem_size} experiment_id = "SPLIT_CIFAR_HERDING_%s_%r_%s_%s_%s_%s_%s-"%(args.arch, args.train_single_epoch, args.imp_method, str(args.synap_stgth).replace('.', '_'), str(args.learning_rate).replace('.', '_'), str(args.batch_size), str(args.mem_size)) + datetime.datetime.now().strftime("%y-%m-%d-%H-%M") snapshot_experiment_meta_data(args.log_dir, experiment_id, exper_meta_data) # Get the task labels from the total number of tasks and full label space if args.online_cross_val: num_tasks = K_FOR_CROSS_VAL else: num_tasks = NUM_TASKS - K_FOR_CROSS_VAL # Load the split cifar dataset data_labs = [np.arange(TOTAL_CLASSES)] datasets = construct_split_cifar(data_labs) # Variables to store the accuracies and standard deviations of the experiment acc_mean = dict() acc_std = dict() # Reset the default graph tf.reset_default_graph() graph = tf.Graph() with graph.as_default(): # Set the random seed tf.set_random_seed(args.random_seed) # Define Input and Output of the model x = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) if args.imp_method == 'PNN': y_ = [] for i in range(num_tasks): y_.append(tf.placeholder(tf.float32, shape=[None, TOTAL_CLASSES])) else: y_ = tf.placeholder(tf.float32, shape=[None, TOTAL_CLASSES]) # Define the optimizer if args.optim == 'ADAM': opt = tf.train.AdamOptimizer(learning_rate=args.learning_rate) elif args.optim == 'SGD': opt = tf.train.GradientDescentOptimizer(learning_rate=args.learning_rate) elif args.optim == 'MOMENTUM': base_lr = tf.constant(args.learning_rate) learning_rate = tf.scalar_mul(base_lr, tf.pow((1 - train_step / training_iters), OPT_POWER)) opt = tf.train.MomentumOptimizer(args.learning_rate, OPT_MOMENTUM) # Create the Model/ contruct the graph model = Model(x, y_, num_tasks, opt, args.imp_method, args.synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch) # Set up tf session and initialize variables. config = tf.ConfigProto() config.gpu_options.allow_growth = True time_start = time.time() with tf.Session(config=config, graph=graph) as sess: runs, task_labels_dataset = train_task_sequence(model, sess, datasets, args) # Close the session sess.close() time_end = time.time() time_spent = time_end - time_start # Store all the results in one dictionary to process later exper_acc = dict(mean=runs) exper_labels = dict(labels=task_labels_dataset) # If cross-validation flag is enabled, store the stuff in a text file if args.cross_validate_mode: acc_mean, acc_std = average_acc_stats_across_runs(runs, model.imp_method) fgt_mean, fgt_std = average_fgt_stats_across_runs(runs, model.imp_method) cross_validate_dump_file = args.log_dir + '/' + 'SPLIT_CIFAR_%s_%s'%(args.imp_method, args.optim) + '.txt' with open(cross_validate_dump_file, 'a') as f: if MULTI_TASK: f.write('HERDING: {} \t ARCH: {} \t LR:{} \t LAMBDA: {} \t ACC: {}\n'.format(args.arch, args.learning_rate, args.synap_stgth, acc_mean[-1,:].mean())) else: f.write('ARCH: {} \t LR:{} \t LAMBDA: {} \t ACC: {} \t Fgt: {} \t Time: {}\n'.format(args.arch, args.learning_rate, args.synap_stgth, acc_mean, fgt_mean, str(time_spent))) # Store the experiment output to a file snapshot_experiment_eval(args.log_dir, experiment_id, exper_acc) snapshot_task_labels(args.log_dir, experiment_id, exper_labels) if __name__ == '__main__': main()
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Training script for split AWA experiment with hybrid learning. """ from __future__ import print_function import argparse import os import sys import math import random import time import datetime import numpy as np import tensorflow as tf from copy import deepcopy from six.moves import cPickle as pickle from utils.data_utils import image_scaling, random_crop_and_pad_image, random_horizontal_flip, construct_split_awa from utils.utils import get_sample_weights, sample_from_dataset, concatenate_datasets, update_episodic_memory, samples_for_each_class, sample_from_dataset_icarl, load_task_specific_data, load_task_specific_data_in_proportion from utils.vis_utils import plot_acc_multiple_runs, plot_histogram, snapshot_experiment_meta_data, snapshot_experiment_eval, snapshot_task_labels from model import Model ############################################################### ################ Some definitions ############################# ### These will be edited by the command line options ########## ############################################################### ## Training Options NUM_RUNS = 5 # Number of experiments to average over TRAIN_ITERS = 2000 # Number of training iterations per task BATCH_SIZE = 16 LEARNING_RATE = 0.1 RANDOM_SEED = 1234 VALID_OPTIMS = ['SGD', 'MOMENTUM', 'ADAM'] OPTIM = 'SGD' OPT_MOMENTUM = 0.9 OPT_POWER = 0.9 VALID_ARCHS = ['CNN', 'VGG', 'RESNET-B'] ARCH = 'RESNET-B' PRETRAIN = False ## Model options MODELS = ['VAN', 'PI', 'EWC', 'MAS', 'RWALK', 'A-GEM'] #List of valid models IMP_METHOD = 'VAN' SYNAP_STGTH = 75000 FISHER_EMA_DECAY = 0.9 # Exponential moving average decay factor for Fisher computation (online Fisher) FISHER_UPDATE_AFTER = 50 # Number of training iterations for which the F_{\theta}^t is computed (see Eq. 10 in RWalk paper) SAMPLES_PER_CLASS = 20 # Number of samples per task IMG_HEIGHT = 224 IMG_WIDTH = 224 IMG_CHANNELS = 3 TOTAL_CLASSES = 50 # Total number of classes in the dataset MEASURE_CONVERGENCE_AFTER = 0.9 EPS_MEM_BATCH_SIZE = 128 DEBUG_EPISODIC_MEMORY = False KEEP_EPISODIC_MEMORY_FULL = False K_FOR_CROSS_VAL = 3 CLASSES_PER_TASK = 5 ## Logging, saving and testing options LOG_DIR = './split_awa_results' SNAPSHOT_DIR = './awa_snapshots' SAVE_MODEL_PARAMS = False RESNET18_IMAGENET_CHECKPOINT = './resnet-18-pretrained-imagenet/model.ckpt' ## Evaluation options ## Task split NUM_TASKS = 20 MULTI_TASK = False ## Dataset specific options ATTR_DIMS = 85 DATA_DIR= './AWA_data/Animals_with_Attributes2/' AWA_TRAIN_LIST = './dataset_lists/AWA_train_list.txt' AWA_VAL_LIST = './dataset_lists/AWA_val_list.txt' AWA_TEST_LIST = './dataset_lists/AWA_test_list.txt' #AWA_TRAIN_LIST = './dataset_lists/tmp_list_awa.txt' #AWA_VAL_LIST = './dataset_lists/tmp_list_awa.txt' #AWA_TEST_LIST = './dataset_lists/tmp_list_awa.txt' AWA_ATTR_LIST = 'dataset_lists/AWA_attr_in_order.pickle' # Define function to load/ store training weights. We will use ImageNet initialization later on def save(saver, sess, logdir, step): '''Save weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. logdir: path to the snapshots directory. step: current training step. ''' model_name = 'model.ckpt' checkpoint_path = os.path.join(logdir, model_name) if not os.path.exists(logdir): os.makedirs(logdir) saver.save(sess, checkpoint_path, global_step=step) print('The checkpoint has been created.') def load(saver, sess, ckpt_path): '''Load trained weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. ckpt_path: path to checkpoint file with parameters. ''' saver.restore(sess, ckpt_path) print("Restored model parameters from {}".format(ckpt_path)) def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Script for split AWA Hybrid experiment.") parser.add_argument("--cross-validate-mode", action="store_true", help="If option is chosen then snapshoting after each batch is disabled") parser.add_argument("--online-cross-val", action="store_true", help="If option is chosen then enable the online cross validation of the learning rate") parser.add_argument("--train-single-epoch", action="store_true", help="If option is chosen then train for single epoch") parser.add_argument("--set-hybrid", action="store_true", help="If option is chosen then train using hybrid model") parser.add_argument("--eval-single-head", action="store_true", help="If option is chosen then evaluate on a single head setting.") parser.add_argument("--arch", type=str, default=ARCH, help="Network Architecture for the experiment.\ \n \nSupported values: %s"%(VALID_ARCHS)) parser.add_argument("--num-runs", type=int, default=NUM_RUNS, help="Total runs/ experiments over which accuracy is averaged.") parser.add_argument("--train-iters", type=int, default=TRAIN_ITERS, help="Number of training iterations for each task.") parser.add_argument("--batch-size", type=int, default=BATCH_SIZE, help="Mini-batch size for each task.") parser.add_argument("--random-seed", type=int, default=RANDOM_SEED, help="Random Seed.") parser.add_argument("--learning-rate", type=float, default=LEARNING_RATE, help="Starting Learning rate for each task.") parser.add_argument("--optim", type=str, default=OPTIM, help="Optimizer for the experiment. \ \n \nSupported values: %s"%(VALID_OPTIMS)) parser.add_argument("--imp-method", type=str, default=IMP_METHOD, help="Model to be used for LLL. \ \n \nSupported values: %s"%(MODELS)) parser.add_argument("--synap-stgth", type=float, default=SYNAP_STGTH, help="Synaptic strength for the regularization.") parser.add_argument("--fisher-ema-decay", type=float, default=FISHER_EMA_DECAY, help="Exponential moving average decay for Fisher calculation at each step.") parser.add_argument("--fisher-update-after", type=int, default=FISHER_UPDATE_AFTER, help="Number of training iterations after which the Fisher will be updated.") parser.add_argument("--do-sampling", action="store_true", help="Whether to do sampling") parser.add_argument("--mem-size", type=int, default=SAMPLES_PER_CLASS, help="Number of samples per class from previous tasks.") parser.add_argument("--is-herding", action="store_true", help="Herding based sampling") parser.add_argument("--data-dir", type=str, default=DATA_DIR, help="Directory from where the AWA data will be read.\ NOTE: Provide path till <AWA_DIR>/Animals_with_Attributes2") parser.add_argument("--init-checkpoint", type=str, default=RESNET18_IMAGENET_CHECKPOINT, help="TF checkpoint file containing initialization for ImageNet.\ NOTE: NPZ file for VGG and TF Checkpoint for ResNet") parser.add_argument("--log-dir", type=str, default=LOG_DIR, help="Directory where the plots and model accuracies will be stored.") return parser.parse_args() def train_task_sequence(model, sess, saver, datasets, class_attr, num_classes_per_task, cross_validate_mode, train_single_epoch, do_sampling, is_herding, episodic_mem_size, train_iters, batch_size, num_runs, init_checkpoint, online_cross_val, random_seed): """ Train and evaluate LLL system such that we only see a example once Args: Returns: dict A dictionary containing mean and stds for the experiment """ # List to store accuracy for each run runs = [] task_labels_dataset = [] break_training = 0 # Loop over number of runs to average over for runid in range(num_runs): print('\t\tRun %d:'%(runid)) # Initialize the random seeds np.random.seed(random_seed+runid) random.seed(random_seed+runid) # Get the task labels from the total number of tasks and full label space task_labels = [] classes_per_task = num_classes_per_task classes_appearing_in_tasks = dict() for cls in range(TOTAL_CLASSES): classes_appearing_in_tasks[cls] = 0 if online_cross_val: label_array = np.arange(TOTAL_CLASSES) for tt in range(model.num_tasks): offset = tt * classes_per_task task_labels.append(list(label_array[offset:offset+classes_per_task])) else: for tt in range(model.num_tasks): task_labels.append(random.sample(range(K_FOR_CROSS_VAL*classes_per_task, TOTAL_CLASSES), classes_per_task)) for lab in task_labels[tt]: classes_appearing_in_tasks[lab] += 1 print('Task: {}, Labels:{}'.format(tt, task_labels[tt])) print('Class frequency in Tasks: {}'.format(classes_appearing_in_tasks)) # Store the task labels task_labels_dataset.append(task_labels) # Initialize all the variables in the model sess.run(tf.global_variables_initializer()) if PRETRAIN: # Load the variables from a checkpoint if model.network_arch == 'RESNET-B': # Define loader (weights which will be loaded from a checkpoint) restore_vars = [v for v in model.trainable_vars if 'fc' not in v.name and 'attr_embed' not in v.name] loader = tf.train.Saver(restore_vars) load(loader, sess, init_checkpoint) elif model.network_arch == 'VGG': # Load the pretrained weights from the npz file weights = np.load(init_checkpoint) keys = sorted(weights.keys()) for i, key in enumerate(keys[:-2]): # Load everything except the last layer sess.run(model.trainable_vars[i].assign(weights[key])) # Run the init ops model.init_updates(sess) # List to store accuracies for a run evals = [] if model.imp_method == 'S-GEM': # List to store the episodic memories of the previous tasks task_based_memory = [] if model.imp_method == 'A-GEM': # Reserve a space for episodic memory episodic_images = np.zeros([episodic_mem_size, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) episodic_labels = np.zeros([episodic_mem_size, model.num_tasks*TOTAL_CLASSES]) episodic_filled_counter = 0 a_gem_logit_mask = np.zeros([model.num_tasks, model.total_classes]) # Labels for all the tasks that we have seen in the past prev_task_labels = [] prev_class_attrs = np.zeros([model.total_classes, class_attr.shape[1]]) if do_sampling: # List to store important samples from the previous tasks last_task_x = None last_task_y_ = None # Mask for softmax logit_mask = np.zeros(model.total_classes) max_batch_dimension = 500 # Dict to store the number of times a class has already been seen in the training class_seen_already = dict() for cls in range(TOTAL_CLASSES): class_seen_already[cls] = 0 # Training loop for all the tasks for task in range(len(task_labels)): print('\t\tTask %d:'%(task)) # If not the first task then restore weights from previous task if(task > 0): model.restore(sess) # Increment the class seen count for cls in task_labels[task]: class_seen_already[cls] += 1 task_train_images, task_train_labels = load_task_specific_data_in_proportion(datasets[0]['train'], task_labels[task], classes_appearing_in_tasks, class_seen_already) print('Received {} images, {} labels at task {}'.format(task_train_images.shape[0], task_train_labels.shape[0], task)) print('Unique labels in the task: {}'.format(np.unique(np.nonzero(task_train_labels)[1]))) # Assign equal weights to all the examples task_sample_weights = np.ones([task_train_labels.shape[0]], dtype=np.float32) num_train_examples = task_train_images.shape[0] # Train a task observing sequence of data logit_mask[:] = 0 if train_single_epoch: # Ceiling operation num_iters = (num_train_examples + batch_size - 1) // batch_size else: num_iters = train_iters logit_mask_offset = task * TOTAL_CLASSES classes_adjusted_for_head = [cls + logit_mask_offset for cls in task_labels[task]] logit_mask[classes_adjusted_for_head] = 1.0 # Randomly suffle the training examples perm = np.arange(num_train_examples) np.random.shuffle(perm) train_x = task_train_images[perm] train_y = task_train_labels[perm] task_sample_weights = task_sample_weights[perm] # Array to store accuracies when training for task T if cross_validate_mode: # Because we will evaluate at the end ftask = 0 elif train_single_epoch: # Because we will evaluate after every mini-batch of every task ftask = np.zeros([max_batch_dimension+1, model.num_tasks]) batch_dim_count = 0 else: # Multi-epoch because we will evaluate after every task ftask = [] # Attribute mask masked_class_attrs = np.zeros([model.total_classes, class_attr.shape[1]]) masked_class_attrs[classes_adjusted_for_head] = class_attr[task_labels[task]] #masked_class_attrs[task_labels[task]] = class_attr[task_labels[task]] # Number of iterations after which convergence is checked convergence_iters = int(num_iters * MEASURE_CONVERGENCE_AFTER) final_train_labels = np.zeros([batch_size, model.total_classes]) head_offset = task * TOTAL_CLASSES # Training loop for task T for iters in range(num_iters): if train_single_epoch and not cross_validate_mode: if (iters < 11): # Snapshot the current performance across all tasks after each mini-batch fbatch = test_task_sequence(model, sess, datasets[0]['test'], class_attr, num_classes_per_task, task_labels, task, online_cross_val) ftask[batch_dim_count] = fbatch # Increment the batch_dim_count batch_dim_count += 1 # Set the output labels over which the model needs to be trained if model.imp_method == 'A-GEM': a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][classes_adjusted_for_head] = 1.0 else: logit_mask[:] = 0 logit_mask[classes_adjusted_for_head] = 1.0 offset = iters * batch_size if (offset+batch_size <= num_train_examples): residual = batch_size else: residual = num_train_examples - offset final_train_labels[:residual, head_offset:head_offset+TOTAL_CLASSES] = train_y[offset:offset+residual] feed_dict = {model.x: train_x[offset:offset+residual], model.y_: final_train_labels[:residual], model.class_attr: masked_class_attrs, model.sample_weights: task_sample_weights[offset:offset+residual], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5, model.train_phase: True} if model.imp_method == 'VAN': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'EWC' or model.imp_method == 'M-EWC': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Update fisher after every few iterations if (iters + 1) % model.fisher_update_after == 0: sess.run(model.set_running_fisher) sess.run(model.reset_tmp_fisher) if (iters >= convergence_iters) and (model.imp_method == 'M-EWC'): _, _, _, _, loss = sess.run([model.weights_old_ops_grouped, model.set_tmp_fisher, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) else: _, _, loss = sess.run([model.set_tmp_fisher, model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'PI': feed_dict[model.output_mask] = logit_mask _, _, _, loss = sess.run([model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'MAS': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'S-GEM': if task == 0: logit_mask[:] = 0 logit_mask[task_labels[task]] = 1.0 feed_dict[model.output_mask] = logit_mask # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: # Randomly sample a task from the previous tasks prev_task = np.random.randint(0, task) # Set the logit mask for the randomly sampled task logit_mask[:] = 0 logit_mask[task_labels[prev_task]] = 1.0 prev_class_attrs = np.zeros_like(class_attr) if online_cross_val: attr_offset = prev_task * num_classes_per_task else: attr_offset = (prev_task + K_FOR_CROSS_VAL) * num_classes_per_task prev_class_attrs[attr_offset:attr_offset+num_classes_per_task] = class_attr[attr_offset:attr_offset+num_classes_per_task] # Store the reference gradient sess.run(model.store_ref_grads, feed_dict={model.x: task_based_memory[prev_task]['images'], model.y_: task_based_memory[prev_task]['labels'], model.class_attr: prev_class_attrs, model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: True}) # Compute the gradient for current task and project if need be logit_mask[:] = 0 logit_mask[task_labels[task]] = 1.0 feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) elif model.imp_method == 'A-GEM': if task == 0: a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][classes_adjusted_for_head] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: ## Compute and store the reference gradients on the previous tasks # Set the mask for all the previous tasks so far a_gem_logit_mask[:] = 0 for tt in range(task): logit_mask_offset = tt * TOTAL_CLASSES classes_adjusted_for_head = [cls + logit_mask_offset for cls in task_labels[tt]] a_gem_logit_mask[tt][classes_adjusted_for_head] = 1.0 if KEEP_EPISODIC_MEMORY_FULL: mem_sample_mask = np.random.choice(episodic_mem_size, EPS_MEM_BATCH_SIZE, replace=False) # Sample without replacement so that we don't sample an example more than once else: if episodic_filled_counter <= EPS_MEM_BATCH_SIZE: mem_sample_mask = np.arange(episodic_filled_counter) else: # Sample a random subset from episodic memory buffer mem_sample_mask = np.random.choice(episodic_filled_counter, EPS_MEM_BATCH_SIZE, replace=False) # Sample without replacement so that we don't sample an example more than once # Store the reference gradient ref_feed_dict = {model.x: episodic_images[mem_sample_mask], model.y_: episodic_labels[mem_sample_mask], model.class_attr: prev_class_attrs, model.keep_prob: 1.0, model.train_phase: True} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} ref_feed_dict.update(logit_mask_dict) ref_feed_dict[model.mem_batch_size] = float(len(mem_sample_mask)) sess.run(model.store_ref_grads, feed_dict=ref_feed_dict) # Compute the gradient for current task and project if need be a_gem_logit_mask[:] = 0 logit_mask_offset = task * TOTAL_CLASSES classes_adjusted_for_head = [cls + logit_mask_offset for cls in task_labels[task]] a_gem_logit_mask[task][classes_adjusted_for_head] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) elif model.imp_method == 'RWALK': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Update fisher and importance score after every few iterations if (iters + 1) % model.fisher_update_after == 0: # Update the importance score using distance in riemannian manifold sess.run(model.update_big_omega_riemann) # Now that the score is updated, compute the new value for running Fisher sess.run(model.set_running_fisher) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Reset the delta_L sess.run([model.reset_small_omega]) _, _, _, _, loss = sess.run([model.set_tmp_fisher, model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) if (iters % 100 == 0): print('Step {:d} {:.3f}'.format(iters, loss)) if (math.isnan(loss)): print('ERROR: NaNs NaNs NaNs!!!') break_training = 1 break print('\t\t\t\tTraining for Task%d done!'%(task)) if model.imp_method == 'A-GEM': # Update the previous task labels prev_task_labels.extend(classes_adjusted_for_head) prev_class_attrs[classes_adjusted_for_head] = class_attr[task_labels[task]] if break_training: break # Compute the inter-task updates, Fisher/ importance scores etc # Don't calculate the task updates for the last task if task < (len(task_labels) - 1): # TODO: For MAS, should the gradients be for current task or all the previous tasks model.task_updates(sess, task, task_train_images, task_labels[task], num_classes_per_task=num_classes_per_task, class_attr=class_attr, online_cross_val=online_cross_val) print('\t\t\t\tTask updates after Task%d done!'%(task)) # If importance method is '*-GEM' then store the episodic memory for the task if 'GEM' in model.imp_method: data_to_sample_from = { 'images': task_train_images, 'labels': task_train_labels, } if model.imp_method == 'S-GEM': # Get the important samples from the current task if is_herding: # Sampling based on MoF # Compute the features of training data features_dim = model.image_feature_dim features = np.zeros([num_train_examples, features_dim]) samples_at_a_time = 32 residual = num_train_examples % samples_at_a_time for i in range(num_train_examples// samples_at_a_time): offset = i * samples_at_a_time features[offset:offset+samples_at_a_time] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+samples_at_a_time], model.y_: task_train_labels[offset:offset+samples_at_a_time], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) if residual > 0: offset = (i + 1) * samples_at_a_time features[offset:offset+residual] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+residual], model.y_: task_train_labels[offset:offset+residual], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) imp_images, imp_labels = sample_from_dataset_icarl(data_to_sample_from, features, task_labels[task], SAMPLES_PER_CLASS) else: # Random sampling # Do the uniform sampling/ only get examples from current task importance_array = np.ones(num_train_examples, dtype=np.float32) imp_images, imp_labels = sample_from_dataset(data_to_sample_from, importance_array, task_labels[task], SAMPLES_PER_CLASS) task_memory = { 'images': deepcopy(imp_images), 'labels': deepcopy(imp_labels), } task_based_memory.append(task_memory) elif model.imp_method == 'A-GEM': # Do the uniform sampling/ only get examples from current task importance_array = np.ones(num_train_examples, dtype=np.float32) if KEEP_EPISODIC_MEMORY_FULL: update_episodic_memory(data_to_sample_from, importance_array, episodic_mem_size, task, episodic_images, episodic_labels) else: imp_images, imp_labels = sample_from_dataset(data_to_sample_from, importance_array, task_labels[task], SAMPLES_PER_CLASS) if not KEEP_EPISODIC_MEMORY_FULL: # Fill the memory to always keep M/T samples per task total_imp_samples = imp_images.shape[0] eps_offset = task * total_imp_samples episodic_images[eps_offset:eps_offset+total_imp_samples] = imp_images episodic_labels[eps_offset:eps_offset+total_imp_samples, head_offset:head_offset+TOTAL_CLASSES] = imp_labels episodic_filled_counter += total_imp_samples print('Unique labels in the episodic memory: {}'.format(np.unique(np.nonzero(episodic_labels)[1]))) # Inspect episodic memory if DEBUG_EPISODIC_MEMORY: # Which labels are present in the memory unique_labels = np.unique(np.nonzero(episodic_labels)[-1]) print('Unique Labels present in the episodic memory'.format(unique_labels)) print('Labels count:') for lbl in unique_labels: print('Label {}: {} samples'.format(lbl, np.where(np.nonzero(episodic_labels)[-1] == lbl)[0].size)) # Is there any space which is not filled print('Empty space: {}'.format(np.where(np.sum(episodic_labels, axis=1) == 0))) print('Episodic memory of {} images at task {} saved!'.format(episodic_images.shape[0], task)) # If sampling flag is set, store few of the samples from previous task if do_sampling: # Do the uniform sampling/ only get examples from current task importance_array = np.ones([datasets[task]['train']['images'].shape[0]], dtype=np.float32) # Get the important samples from the current task imp_images, imp_labels = sample_from_dataset(datasets[task]['train'], importance_array, task_labels[task], SAMPLES_PER_CLASS) if imp_images is not None: if last_task_x is None: last_task_x = imp_images last_task_y_ = imp_labels else: last_task_x = np.concatenate((last_task_x, imp_images), axis=0) last_task_y_ = np.concatenate((last_task_y_, imp_labels), axis=0) # Delete the importance array now that you don't need it in the current run del importance_array print('\t\t\t\tEpisodic memory is saved for Task%d!'%(task)) if cross_validate_mode: if (task == model.num_tasks - 1) or MULTI_TASK: # List to store accuracy for all the tasks for the current trained model ftask = test_task_sequence(model, sess, datasets[0]['test'], class_attr, num_classes_per_task, task_labels, task, online_cross_val) elif train_single_epoch: fbatch = test_task_sequence(model, sess, datasets[0]['test'], class_attr, num_classes_per_task, task_labels, task, False) ftask[batch_dim_count] = fbatch print('Task: {}, {}'.format(task, fbatch)) else: # Multi-epoch training, so compute accuracy at the end ftask = test_task_sequence(model, sess, datasets[0]['test'], class_attr, num_classes_per_task, task_labels, task, online_cross_val) if SAVE_MODEL_PARAMS: save(saver, sess, SNAPSHOT_DIR, iters) if not cross_validate_mode: # Store the accuracies computed at task T in a list evals.append(np.array(ftask)) # Reset the optimizer model.reset_optimizer(sess) #-> End for loop task if not cross_validate_mode: runs.append(np.array(evals)) if break_training: break # End for loop runid if cross_validate_mode: return np.mean(ftask) else: runs = np.array(runs) return runs, task_labels_dataset def test_task_sequence(model, sess, test_data, class_attr, num_classes_per_task, all_task_labels, task, online_cross_val): """ Snapshot the current performance """ final_acc = np.zeros(model.num_tasks) test_set = 'test' if model.imp_method == 'A-GEM': logit_mask = np.zeros([model.num_tasks, model.total_classes]) else: logit_mask = np.zeros(model.total_classes) for tt, labels in enumerate(all_task_labels): if tt > task: return final_acc samples_at_a_time = 10 task_images, task_labels = load_task_specific_data(test_data, labels) global_class_indices = np.column_stack(np.nonzero(task_labels)) logit_mask_offset = tt * TOTAL_CLASSES classes_adjusted_for_head = [cls + logit_mask_offset for cls in labels] logit_mask[:] = 0 if model.imp_method == 'A-GEM': logit_mask[tt][classes_adjusted_for_head] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, logit_mask)} else: logit_mask[classes_adjusted_for_head] = 1.0 #masked_class_attrs = np.zeros_like(class_attr) #masked_class_attrs[labels] = class_attr[labels] masked_class_attrs = np.zeros([model.total_classes, class_attr.shape[1]]) masked_class_attrs[classes_adjusted_for_head] = class_attr[labels] final_train_labels = np.zeros([samples_at_a_time, model.total_classes]) head_offset = tt * TOTAL_CLASSES acc = np.zeros(len(labels)) for cli, cls in enumerate(labels): class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])]) class_indices = np.sort(class_indices, axis=None) task_test_images = task_images[class_indices] task_test_labels = task_labels[class_indices] total_test_samples = task_test_images.shape[0] total_corrects = 0 if total_test_samples < samples_at_a_time: i = -1 for i in range(total_test_samples/ samples_at_a_time): offset = i*samples_at_a_time final_train_labels[:, head_offset:head_offset+TOTAL_CLASSES] = task_test_labels[offset:offset+samples_at_a_time] feed_dict = {model.x: task_test_images[offset:offset+samples_at_a_time], model.y_: final_train_labels, model.class_attr: masked_class_attrs, model.keep_prob: 1.0, model.train_phase: False} if model.imp_method == 'A-GEM': feed_dict.update(logit_mask_dict) corrects = sess.run(model.correct_predictions[tt], feed_dict=feed_dict) else: feed_dict[model.output_mask] = logit_mask corrects = sess.run(model.correct_predictions, feed_dict=feed_dict) total_corrects += np.sum(corrects) # Compute the corrects on residuals offset = (i+1)*samples_at_a_time num_residuals = total_test_samples % samples_at_a_time final_train_labels[:num_residuals, head_offset:head_offset+TOTAL_CLASSES] = task_test_labels[offset:offset+num_residuals] feed_dict = {model.x: task_test_images[offset:offset+num_residuals], model.y_: final_train_labels[:num_residuals], model.class_attr: masked_class_attrs, model.keep_prob: 1.0, model.train_phase: False} if model.imp_method == 'A-GEM': feed_dict.update(logit_mask_dict) corrects = sess.run(model.correct_predictions[tt], feed_dict=feed_dict) else: feed_dict[model.output_mask] = logit_mask corrects = sess.run(model.correct_predictions, feed_dict=feed_dict) total_corrects += np.sum(corrects) if total_test_samples != 0: # Mean accuracy on the task acc[cli] = total_corrects/ float(total_test_samples) final_acc[tt] = np.mean(acc) return final_acc def main(): """ Create the model and start the training """ # Get the CL arguments args = get_arguments() # Initialize the random seed of numpy np.random.seed(args.random_seed) # Check if the network architecture is valid if args.arch not in VALID_ARCHS: raise ValueError("Network architecture %s is not supported!"%(args.arch)) # Check if the method to compute importance is valid if args.imp_method not in MODELS: raise ValueError("Importance measure %s is undefined!"%(args.imp_method)) # Check if the optimizer is valid if args.optim not in VALID_OPTIMS: raise ValueError("Optimizer %s is undefined!"%(args.optim)) # Create log directories to store the results if not os.path.exists(args.log_dir): print('Log directory %s created!'%(args.log_dir)) os.makedirs(args.log_dir) if args.online_cross_val: num_tasks = K_FOR_CROSS_VAL else: num_tasks = NUM_TASKS - K_FOR_CROSS_VAL # Load the split AWA dataset data_labs = [np.arange(TOTAL_CLASSES)] datasets, AWA_attr = construct_split_awa(data_labs, args.data_dir, AWA_TRAIN_LIST, AWA_VAL_LIST, AWA_TEST_LIST, IMG_HEIGHT, IMG_WIDTH, attr_file=AWA_ATTR_LIST) if args.online_cross_val: AWA_attr[K_FOR_CROSS_VAL*CLASSES_PER_TASK:] = 0 else: AWA_attr[:K_FOR_CROSS_VAL*CLASSES_PER_TASK] = 0 print('Attributes: {}'.format(np.sum(AWA_attr, axis=1))) if args.cross_validate_mode: models_list = MODELS learning_rate_list = [0.1, 0.03, 0.01, 0.001, 0.0003] else: models_list = [args.imp_method] for imp_method in models_list: if imp_method == 'VAN': synap_stgth_list = [0] if args.online_cross_val or args.cross_validate_mode: pass else: learning_rate_list = [0.003] elif imp_method == 'PI': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10] else: synap_stgth_list = [10] learning_rate_list = [0.003] elif imp_method == 'EWC' or imp_method == 'M-EWC': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [100] learning_rate_list = [0.003] elif imp_method == 'MAS': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [0.1] learning_rate_list = [0.001] elif imp_method == 'RWALK': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [10] # Check again! learning_rate_list = [0.003] elif imp_method == 'S-GEM': synap_stgth_list = [0] if args.online_cross_val: pass else: learning_rate_list = [args.learning_rate] elif imp_method == 'A-GEM': synap_stgth_list = [0] if args.online_cross_val or args.cross_validate_mode: pass else: learning_rate_list = [0.003] for synap_stgth in synap_stgth_list: for lr in learning_rate_list: # Generate the experiment key and store the meta data in a file exper_meta_data = {'ARCH': args.arch, 'DATASET': 'SPLIT_AWA', 'HYBRID': args.set_hybrid, 'NUM_RUNS': args.num_runs, 'TRAIN_SINGLE_EPOCH': args.train_single_epoch, 'IMP_METHOD': imp_method, 'SYNAP_STGTH': synap_stgth, 'FISHER_EMA_DECAY': args.fisher_ema_decay, 'FISHER_UPDATE_AFTER': args.fisher_update_after, 'OPTIM': args.optim, 'LR': lr, 'BATCH_SIZE': args.batch_size, 'EPS_MEMORY': args.do_sampling, 'MEM_SIZE': args.mem_size, 'IS_HERDING': args.is_herding} experiment_id = "SPLIT_AWA_HERDING_%r_HYB_%r_%s_%r_%s_%s_%s_%r_%s-"%(args.is_herding, args.set_hybrid, args.arch, args.train_single_epoch, imp_method, str(synap_stgth).replace('.', '_'), str(args.batch_size), args.do_sampling, str(args.mem_size)) + datetime.datetime.now().strftime("%y-%m-%d-%H-%M") snapshot_experiment_meta_data(args.log_dir, experiment_id, exper_meta_data) # Reset the default graph tf.reset_default_graph() graph = tf.Graph() with graph.as_default(): # Set the random seed tf.set_random_seed(args.random_seed) # Define Input and Output of the model x = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) y_ = tf.placeholder(tf.float32, shape=[None, num_tasks*TOTAL_CLASSES]) attr = tf.placeholder(tf.float32, shape=[num_tasks*TOTAL_CLASSES, ATTR_DIMS]) if not args.train_single_epoch: # Define ops for data augmentation x_aug = image_scaling(x) x_aug = random_crop_and_pad_image(x_aug, IMG_HEIGHT, IMG_WIDTH) # Define the optimizer if args.optim == 'ADAM': opt = tf.train.AdamOptimizer(learning_rate=lr) elif args.optim == 'SGD': opt = tf.train.GradientDescentOptimizer(learning_rate=lr) elif args.optim == 'MOMENTUM': base_lr = tf.constant(lr) learning_rate = tf.scalar_mul(base_lr, tf.pow((1 - train_step / training_iters), OPT_POWER)) opt = tf.train.MomentumOptimizer(lr, OPT_MOMENTUM) # Create the Model/ contruct the graph if args.train_single_epoch: # When training using a single epoch then there is no need for data augmentation model = Model(x, y_, num_tasks, opt, imp_method, synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch, is_ATT_DATASET=True, attr=attr) else: model = Model(x_aug, y_, num_tasks, opt, imp_method, synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch, is_ATT_DATASET=True, x_test=x, attr=attr) # Set up tf session and initialize variables. config = tf.ConfigProto() config.gpu_options.allow_growth = True time_start = time.time() with tf.Session(config=config, graph=graph) as sess: saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=100) runs, task_labels_dataset = train_task_sequence(model, sess, saver, datasets, AWA_attr, CLASSES_PER_TASK, args.cross_validate_mode, args.train_single_epoch, args.do_sampling, args.is_herding, args.mem_size*CLASSES_PER_TASK*num_tasks, args.train_iters, args.batch_size, args.num_runs, args.init_checkpoint, args.online_cross_val, args.random_seed) # Close the session sess.close() time_end = time.time() time_spent = time_end - time_start print('Time spent: {}'.format(time_spent)) # Clean up del model if args.cross_validate_mode: # If cross-validation flag is enabled, store the stuff in a text file cross_validate_dump_file = args.log_dir + '/' + 'SPLIT_AWA_HYBRID_%s_%s'%(imp_method, args.optim) + '.txt' with open(cross_validate_dump_file, 'a') as f: f.write('HERDING: {} \t ARCH: {} \t LR:{} \t LAMBDA: {} \t ACC: {}\n'.format(args.is_herding, args.arch, lr, synap_stgth, runs)) else: # Store all the results in one dictionary to process later exper_acc = dict(mean=runs) exper_labels = dict(labels=task_labels_dataset) # Store the experiment output to a file snapshot_experiment_eval(args.log_dir, experiment_id, exper_acc) snapshot_task_labels(args.log_dir, experiment_id, exper_labels) if __name__ == '__main__': main()
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Training script for split CUB experiment with zero shot transfer. """ from __future__ import print_function import argparse import os import sys import math import time import datetime import numpy as np import tensorflow as tf from copy import deepcopy from six.moves import cPickle as pickle from utils.data_utils import image_scaling, random_crop_and_pad_image, random_horizontal_flip, construct_split_cub from utils.utils import get_sample_weights, sample_from_dataset, concatenate_datasets, update_episodic_memory_with_less_data, samples_for_each_class, sample_from_dataset_icarl, load_task_specific_data from utils.vis_utils import plot_acc_multiple_runs, plot_histogram, snapshot_experiment_meta_data, snapshot_experiment_eval, snapshot_task_labels from model import Model ############################################################### ################ Some definitions ############################# ### These will be edited by the command line options ########## ############################################################### ## Training Options NUM_RUNS = 5 # Number of experiments to average over TRAIN_ITERS = 2000 # Number of training iterations per task BATCH_SIZE = 16 LEARNING_RATE = 0.1 RANDOM_SEED = 1234 VALID_OPTIMS = ['SGD', 'MOMENTUM', 'ADAM'] OPTIM = 'SGD' OPT_MOMENTUM = 0.9 OPT_POWER = 0.9 VALID_ARCHS = ['CNN', 'VGG', 'RESNET-B'] ARCH = 'RESNET-B' PRETRAIN = True ## Model options MODELS = ['VAN', 'PI', 'EWC', 'MAS', 'RWALK', 'A-GEM'] #List of valid models IMP_METHOD = 'EWC' SYNAP_STGTH = 75000 FISHER_EMA_DECAY = 0.9 # Exponential moving average decay factor for Fisher computation (online Fisher) FISHER_UPDATE_AFTER = 50 # Number of training iterations for which the F_{\theta}^t is computed (see Eq. 10 in RWalk paper) SAMPLES_PER_CLASS = 5 # Number of samples per task IMG_HEIGHT = 224 IMG_WIDTH = 224 IMG_CHANNELS = 3 TOTAL_CLASSES = 200 # Total number of classes in the dataset EPS_MEM_BATCH_SIZE = 128 DEBUG_EPISODIC_MEMORY = False KEEP_EPISODIC_MEMORY_FULL = False K_FOR_CROSS_VAL = 3 ## Logging, saving and testing options LOG_DIR = './split_cub_results' SNAPSHOT_DIR = './cub_snapshots' SAVE_MODEL_PARAMS = False ## Evaluation options ## Task split NUM_TASKS = 20 MULTI_TASK = False ## Dataset specific options ATTR_DIMS = 312 DATA_DIR='CUB_data/CUB_200_2011/images' #CUB_TRAIN_LIST = 'dataset_lists/tmp_list.txt' #CUB_TEST_LIST = 'dataset_lists/tmp_list.txt' CUB_TRAIN_LIST = 'dataset_lists/CUB_train_list.txt' CUB_TEST_LIST = 'dataset_lists/CUB_test_list.txt' CUB_ATTR_LIST = 'dataset_lists/CUB_attr_in_order.pickle' RESNET18_IMAGENET_CHECKPOINT = './resnet-18-pretrained-imagenet/model.ckpt' # Define function to load/ store training weights. We will use ImageNet initialization later on def save(saver, sess, logdir, step): '''Save weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. logdir: path to the snapshots directory. step: current training step. ''' model_name = 'model.ckpt' checkpoint_path = os.path.join(logdir, model_name) if not os.path.exists(logdir): os.makedirs(logdir) saver.save(sess, checkpoint_path, global_step=step) print('The checkpoint has been created.') def load(saver, sess, ckpt_path): '''Load trained weights. Args: saver: TensorFlow Saver object. sess: TensorFlow session. ckpt_path: path to checkpoint file with parameters. ''' saver.restore(sess, ckpt_path) print("Restored model parameters from {}".format(ckpt_path)) def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Script for split CUB hybrid experiment.") parser.add_argument("--cross-validate-mode", action="store_true", help="If option is chosen then snapshoting after each batch is disabled") parser.add_argument("--online-cross-val", action="store_true", help="If option is chosen then enable the online cross validation of the learning rate") parser.add_argument("--train-single-epoch", action="store_true", help="If option is chosen then train for single epoch") parser.add_argument("--set-hybrid", action="store_true", help="If option is chosen then train using hybrid model") parser.add_argument("--eval-single-head", action="store_true", help="If option is chosen then evaluate on a single head setting.") parser.add_argument("--arch", type=str, default=ARCH, help="Network Architecture for the experiment.\ \n \nSupported values: %s"%(VALID_ARCHS)) parser.add_argument("--num-runs", type=int, default=NUM_RUNS, help="Total runs/ experiments over which accuracy is averaged.") parser.add_argument("--train-iters", type=int, default=TRAIN_ITERS, help="Number of training iterations for each task.") parser.add_argument("--batch-size", type=int, default=BATCH_SIZE, help="Mini-batch size for each task.") parser.add_argument("--random-seed", type=int, default=RANDOM_SEED, help="Random Seed.") parser.add_argument("--learning-rate", type=float, default=LEARNING_RATE, help="Starting Learning rate for each task.") parser.add_argument("--optim", type=str, default=OPTIM, help="Optimizer for the experiment. \ \n \nSupported values: %s"%(VALID_OPTIMS)) parser.add_argument("--imp-method", type=str, default=IMP_METHOD, help="Model to be used for LLL. \ \n \nSupported values: %s"%(MODELS)) parser.add_argument("--synap-stgth", type=float, default=SYNAP_STGTH, help="Synaptic strength for the regularization.") parser.add_argument("--fisher-ema-decay", type=float, default=FISHER_EMA_DECAY, help="Exponential moving average decay for Fisher calculation at each step.") parser.add_argument("--fisher-update-after", type=int, default=FISHER_UPDATE_AFTER, help="Number of training iterations after which the Fisher will be updated.") parser.add_argument("--do-sampling", action="store_true", help="Whether to do sampling") parser.add_argument("--mem-size", type=int, default=SAMPLES_PER_CLASS, help="Number of samples per class from previous tasks.") parser.add_argument("--is-herding", action="store_true", help="Herding based sampling") parser.add_argument("--data-dir", type=str, default=DATA_DIR, help="Directory from where the CUB data will be read.\ NOTE: Provide path till <CUB_DIR>/images") parser.add_argument("--init-checkpoint", type=str, default=RESNET18_IMAGENET_CHECKPOINT, help="TF checkpoint file containing initialization for ImageNet.\ NOTE: NPZ file for VGG and TF Checkpoint for ResNet") parser.add_argument("--log-dir", type=str, default=LOG_DIR, help="Directory where the plots and model accuracies will be stored.") return parser.parse_args() def train_task_sequence(model, sess, saver, datasets, class_attr, classes_per_task, cross_validate_mode, train_single_epoch, do_sampling, is_herding, mem_per_class, train_iters, batch_size, num_runs, init_checkpoint, online_cross_val, random_seed): """ Train and evaluate LLL system such that we only see a example once Args: Returns: dict A dictionary containing mean and stds for the experiment """ # List to store accuracy for each run runs = [] task_labels_dataset = [] break_training = 0 # Loop over number of runs to average over for runid in range(num_runs): print('\t\tRun %d:'%(runid)) # Initialize the random seeds np.random.seed(random_seed+runid) # Get the task labels from the total number of tasks and full label space task_labels = [] total_classes = classes_per_task * model.num_tasks if online_cross_val: label_array = np.arange(total_classes) else: class_label_offset = K_FOR_CROSS_VAL * classes_per_task label_array = np.arange(class_label_offset, total_classes+class_label_offset) np.random.shuffle(label_array) for tt in range(model.num_tasks): tt_offset = tt*classes_per_task task_labels.append(list(label_array[tt_offset:tt_offset+classes_per_task])) print('Task: {}, Labels:{}'.format(tt, task_labels[tt])) # Store the task labels task_labels_dataset.append(task_labels) # Set episodic memory size episodic_mem_size = mem_per_class * total_classes # Initialize all the variables in the model sess.run(tf.global_variables_initializer()) if PRETRAIN: # Load the variables from a checkpoint if model.network_arch == 'RESNET-B': # Define loader (weights which will be loaded from a checkpoint) restore_vars = [v for v in model.trainable_vars if 'fc' not in v.name and 'attr_embed' not in v.name] loader = tf.train.Saver(restore_vars) load(loader, sess, init_checkpoint) elif model.network_arch == 'VGG': # Load the pretrained weights from the npz file weights = np.load(init_checkpoint) keys = sorted(weights.keys()) for i, key in enumerate(keys[:-2]): # Load everything except the last layer sess.run(model.trainable_vars[i].assign(weights[key])) # Run the init ops model.init_updates(sess) # List to store accuracies for a run evals = [] # List to store the classes that we have so far - used at test time test_labels = [] if model.imp_method == 'S-GEM': # List to store the episodic memories of the previous tasks task_based_memory = [] if model.imp_method == 'A-GEM': # Reserve a space for episodic memory episodic_images = np.zeros([episodic_mem_size, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) episodic_labels = np.zeros([episodic_mem_size, TOTAL_CLASSES]) episodic_filled_counter = 0 a_gem_logit_mask = np.zeros([model.num_tasks, TOTAL_CLASSES]) # Labels for all the tasks that we have seen in the past prev_task_labels = [] prev_class_attrs = np.zeros_like(class_attr) if do_sampling: # List to store important samples from the previous tasks last_task_x = None last_task_y_ = None # Mask for the softmax logit_mask = np.zeros(TOTAL_CLASSES) # Training loop for all the tasks for task in range(len(task_labels)): print('\t\tTask %d:'%(task)) # If not the first task then restore weights from previous task if(task > 0): model.restore(sess) # If sampling flag is set append the previous datasets if do_sampling: task_tr_images, task_tr_labels = load_task_specific_data(datasets[0]['train'], task_labels[task]) if task > 0: task_train_images, task_train_labels = concatenate_datasets(task_tr_images, task_tr_labels, last_task_x, last_task_y_) else: task_train_images = task_tr_images task_train_labels = task_tr_labels else: # Extract training images and labels for the current task task_train_images, task_train_labels = load_task_specific_data(datasets[0]['train'], task_labels[task]) # If multi_task is set then train using all the datasets of all the tasks if MULTI_TASK: if task == 0: for t_ in range(1, len(task_labels)): task_tr_images, task_tr_labels = load_task_specific_data(datasets[0]['train'], task_labels[t_]) task_train_images = np.concatenate((task_train_images, task_tr_images), axis=0) task_train_labels = np.concatenate((task_train_labels, task_tr_labels), axis=0) else: # Skip training for this task continue print('Received {} images, {} labels at task {}'.format(task_train_images.shape[0], task_train_labels.shape[0], task)) # Test for the tasks that we've seen so far test_labels.extend(task_labels[task]) # Declare variables to store sample importance if sampling flag is set if do_sampling: # Get the sample weighting task_sample_weights = get_sample_weights(task_train_labels, test_labels) else: # Assign equal weights to all the examples task_sample_weights = np.ones([task_train_labels.shape[0]], dtype=np.float32) num_train_examples = task_train_images.shape[0] # Train a task observing sequence of data logit_mask[:] = 0 if train_single_epoch: # Ceiling operation num_iters = (num_train_examples + batch_size - 1) // batch_size if cross_validate_mode: if do_sampling: logit_mask[test_labels] = 1.0 else: logit_mask[task_labels[task]] = 1.0 else: num_iters = train_iters if do_sampling: logit_mask[test_labels] = 1.0 else: logit_mask[task_labels[task]] = 1.0 # Randomly suffle the training examples perm = np.arange(num_train_examples) np.random.shuffle(perm) train_x = task_train_images[perm] train_y = task_train_labels[perm] task_sample_weights = task_sample_weights[perm] # Array to store accuracies when training for task T ftask = [] if MULTI_TASK: logit_mask[:] = 1.0 masked_class_attrs = class_attr else: # Attribute mask masked_class_attrs = np.zeros_like(class_attr) if do_sampling: masked_class_attrs[test_labels] = class_attr[test_labels] else: masked_class_attrs[task_labels[task]] = class_attr[task_labels[task]] # Training loop for task T for iters in range(num_iters): if train_single_epoch and not cross_validate_mode and not MULTI_TASK: #if (iters <= 50 and iters % 5 == 0) or (iters > 50 and iters % 50 == 0): if (iters < 10) or (iters % 5 == 0): # Snapshot the current performance across all tasks after each mini-batch fbatch = test_task_sequence(model, sess, datasets[0]['test'], class_attr, classes_per_task, task_labels, task) ftask.append(fbatch) # Set the output labels over which the model needs to be trained if model.imp_method == 'A-GEM': a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][task_labels[task]] = 1.0 else: logit_mask[:] = 0 if do_sampling: logit_mask[test_labels] = 1.0 else: logit_mask[task_labels[task]] = 1.0 if train_single_epoch: offset = iters * batch_size if (offset+batch_size <= num_train_examples): residual = batch_size else: residual = num_train_examples - offset feed_dict = {model.x: train_x[offset:offset+residual], model.y_: train_y[offset:offset+residual], model.class_attr: masked_class_attrs, model.sample_weights: task_sample_weights[offset:offset+residual], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5, model.train_phase: True} else: offset = (iters * batch_size) % (num_train_examples - batch_size) feed_dict = {model.x: train_x[offset:offset+batch_size], model.y_: train_y[offset:offset+batch_size], model.class_attr: masked_class_attrs, model.sample_weights: task_sample_weights[offset:offset+batch_size], model.training_iters: num_iters, model.train_step: iters, model.keep_prob: 0.5, model.train_phase: True} if model.imp_method == 'VAN': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'EWC': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Update fisher after every few iterations if (iters + 1) % model.fisher_update_after == 0: sess.run(model.set_running_fisher) sess.run(model.reset_tmp_fisher) _, _, loss = sess.run([model.set_tmp_fisher, model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'PI': feed_dict[model.output_mask] = logit_mask _, _, _, loss = sess.run([model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'MAS': feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train, model.reg_loss], feed_dict=feed_dict) elif model.imp_method == 'S-GEM': if task == 0: logit_mask[:] = 0 logit_mask[task_labels[task]] = 1.0 feed_dict[model.output_mask] = logit_mask # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: # Randomly sample a task from the previous tasks prev_task = np.random.randint(0, task) # Set the logit mask for the randomly sampled task logit_mask[:] = 0 logit_mask[task_labels[prev_task]] = 1.0 prev_class_attrs = np.zeros_like(class_attr) prev_class_attrs[task_labels[prev_task]] = class_attr[task_labels[prev_task]] # Store the reference gradient sess.run(model.store_ref_grads, feed_dict={model.x: task_based_memory[prev_task]['images'], model.y_: task_based_memory[prev_task]['labels'], model.class_attr: prev_class_attrs, model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: True}) # Compute the gradient for current task and project if need be logit_mask[:] = 0 logit_mask[task_labels[task]] = 1.0 feed_dict[model.output_mask] = logit_mask _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) elif model.imp_method == 'A-GEM': if task == 0: a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][task_labels[task]] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size # Normal application of gradients _, loss = sess.run([model.train_first_task, model.agem_loss], feed_dict=feed_dict) else: ## Compute and store the reference gradients on the previous tasks # Set the mask for all the previous tasks so far a_gem_logit_mask[:] = 0 for tt in range(task): a_gem_logit_mask[tt][task_labels[tt]] = 1.0 if KEEP_EPISODIC_MEMORY_FULL: mem_sample_mask = np.random.choice(episodic_mem_size, EPS_MEM_BATCH_SIZE, replace=False) # Sample without replacement so that we don't sample an example more than once else: if episodic_filled_counter <= EPS_MEM_BATCH_SIZE: mem_sample_mask = np.arange(episodic_filled_counter) else: # Sample a random subset from episodic memory buffer mem_sample_mask = np.random.choice(episodic_filled_counter, EPS_MEM_BATCH_SIZE, replace=False) # Sample without replacement so that we don't sample an example more than once ref_feed_dict = {model.x: episodic_images[mem_sample_mask], model.y_: episodic_labels[mem_sample_mask], model.class_attr: prev_class_attrs, model.keep_prob: 1.0, model.train_phase: True} logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} ref_feed_dict.update(logit_mask_dict) ref_feed_dict[model.mem_batch_size] = float(len(mem_sample_mask)) sess.run(model.store_ref_grads, feed_dict=ref_feed_dict) # Compute the gradient for current task and project if need be a_gem_logit_mask[:] = 0 a_gem_logit_mask[task][task_labels[task]] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, a_gem_logit_mask)} feed_dict.update(logit_mask_dict) feed_dict[model.mem_batch_size] = batch_size _, loss = sess.run([model.train_subseq_tasks, model.agem_loss], feed_dict=feed_dict) elif model.imp_method == 'RWALK': feed_dict[model.output_mask] = logit_mask # If first iteration of the first task then set the initial value of the running fisher if task == 0 and iters == 0: sess.run([model.set_initial_running_fisher], feed_dict=feed_dict) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Update fisher and importance score after every few iterations if (iters + 1) % model.fisher_update_after == 0: # Update the importance score using distance in riemannian manifold sess.run(model.update_big_omega_riemann) # Now that the score is updated, compute the new value for running Fisher sess.run(model.set_running_fisher) # Store the current value of the weights sess.run(model.weights_delta_old_grouped) # Reset the delta_L sess.run([model.reset_small_omega]) _, _, _, _, loss = sess.run([model.set_tmp_fisher, model.weights_old_ops_grouped, model.train, model.update_small_omega, model.reg_loss], feed_dict=feed_dict) if (iters % 50 == 0): print('Step {:d} {:.3f}'.format(iters, loss)) if (math.isnan(loss)): print('ERROR: NaNs NaNs NaNs!!!') break_training = 1 break print('\t\t\t\tTraining for Task%d done!'%(task)) if model.imp_method == 'A-GEM': # Update the previous task labels and attributes prev_task_labels += task_labels[task] prev_class_attrs[prev_task_labels] = class_attr[prev_task_labels] if break_training: break # Compute the inter-task updates, Fisher/ importance scores etc # Don't calculate the task updates for the last task if task < (len(task_labels) - 1): # TODO: For MAS, should the gradients be for current task or all the previous tasks model.task_updates(sess, task, task_train_images, task_labels[task], num_classes_per_task=classes_per_task, class_attr=class_attr, online_cross_val=online_cross_val) print('\t\t\t\tTask updates after Task%d done!'%(task)) # If importance method is '*-GEM' then store the episodic memory for the task if 'GEM' in model.imp_method: data_to_sample_from = { 'images': task_train_images, 'labels': task_train_labels, } if model.imp_method == 'S-GEM': # Get the important samples from the current task if is_herding: # Sampling based on MoF # Compute the features of training data features_dim = model.image_feature_dim features = np.zeros([num_train_examples, features_dim]) samples_at_a_time = 32 residual = num_train_examples % samples_at_a_time for i in range(num_train_examples// samples_at_a_time): offset = i * samples_at_a_time features[offset:offset+samples_at_a_time] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+samples_at_a_time], model.y_: task_train_labels[offset:offset+samples_at_a_time], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) if residual > 0: offset = (i + 1) * samples_at_a_time features[offset:offset+residual] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+residual], model.y_: task_train_labels[offset:offset+residual], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) imp_images, imp_labels = sample_from_dataset_icarl(data_to_sample_from, features, task_labels[task], SAMPLES_PER_CLASS) else: # Random sampling # Do the uniform sampling/ only get examples from current task importance_array = np.ones(num_train_examples, dtype=np.float32) imp_images, imp_labels = sample_from_dataset(data_to_sample_from, importance_array, task_labels[task], SAMPLES_PER_CLASS) task_memory = { 'images': deepcopy(imp_images), 'labels': deepcopy(imp_labels), } task_based_memory.append(task_memory) elif model.imp_method == 'A-GEM': if is_herding: # Sampling based on MoF # Compute the features of training data features_dim = model.image_feature_dim features = np.zeros([num_train_examples, features_dim]) samples_at_a_time = 32 residual = num_train_examples % samples_at_a_time for i in range(num_train_examples// samples_at_a_time): offset = i * samples_at_a_time features[offset:offset+samples_at_a_time] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+samples_at_a_time], model.y_: task_train_labels[offset:offset+samples_at_a_time], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) if residual > 0: offset = (i + 1) * samples_at_a_time features[offset:offset+residual] = sess.run(model.features, feed_dict={model.x: task_train_images[offset:offset+residual], model.y_: task_train_labels[offset:offset+residual], model.keep_prob: 1.0, model.output_mask: logit_mask, model.train_phase: False}) if KEEP_EPISODIC_MEMORY_FULL: update_episodic_memory(data_to_sample_from, features, episodic_mem_size, task, episodic_images, episodic_labels, task_labels=task_labels[task], is_herding=True) else: imp_images, imp_labels = sample_from_dataset_icarl(data_to_sample_from, features, task_labels[task], SAMPLES_PER_CLASS) else: # Random sampling # Do the uniform sampling/ only get examples from current task importance_array = np.ones(num_train_examples, dtype=np.float32) if KEEP_EPISODIC_MEMORY_FULL: update_episodic_memory(data_to_sample_from, importance_array, episodic_mem_size, task, episodic_images, episodic_labels) else: imp_images, imp_labels = sample_from_dataset(data_to_sample_from, importance_array, task_labels[task], SAMPLES_PER_CLASS) if not KEEP_EPISODIC_MEMORY_FULL: # Fill the memory to always keep M/T samples per task total_imp_samples = imp_images.shape[0] eps_offset = task * total_imp_samples episodic_images[eps_offset:eps_offset+total_imp_samples] = imp_images episodic_labels[eps_offset:eps_offset+total_imp_samples] = imp_labels episodic_filled_counter += total_imp_samples # Inspect episodic memory if DEBUG_EPISODIC_MEMORY: # Which labels are present in the memory unique_labels = np.unique(np.nonzero(episodic_labels)[-1]) print('Unique Labels present in the episodic memory'.format(unique_labels)) print('Labels count:') for lbl in unique_labels: print('Label {}: {} samples'.format(lbl, np.where(np.nonzero(episodic_labels)[-1] == lbl)[0].size)) # Is there any space which is not filled print('Empty space: {}'.format(np.where(np.sum(episodic_labels, axis=1) == 0))) print('Episodic memory of {} images at task {} saved!'.format(episodic_images.shape[0], task)) # If sampling flag is set, store few of the samples from previous task if do_sampling: # Do the uniform sampling/ only get examples from current task importance_array = np.ones([task_train_images.shape[0]], dtype=np.float32) # Get the important samples from the current task task_data = { 'images': task_tr_images, 'labels': task_tr_labels, } imp_images, imp_labels = sample_from_dataset(task_data, importance_array, task_labels[task], SAMPLES_PER_CLASS) if imp_images is not None: if last_task_x is None: last_task_x = imp_images last_task_y_ = imp_labels else: last_task_x = np.concatenate((last_task_x, imp_images), axis=0) last_task_y_ = np.concatenate((last_task_y_, imp_labels), axis=0) # Delete the importance array now that you don't need it in the current run del importance_array print('\t\t\t\tEpisodic memory is saved for Task%d!'%(task)) if cross_validate_mode: if (task == model.num_tasks - 1) or MULTI_TASK: # List to store accuracy for all the tasks for the current trained model ftask = test_task_sequence(model, sess, datasets[0]['test'], class_attr, classes_per_task, task_labels, task) elif train_single_epoch: fbatch = test_task_sequence(model, sess, datasets[0]['test'], class_attr, classes_per_task, task_labels, task) print('Task: {} Acc: {}'.format(task, fbatch)) ftask.append(fbatch) else: # Multi-epoch training, so compute accuracy at the end ftask = test_task_sequence(model, sess, datasets[0]['test'], class_attr, classes_per_task, task_labels, task) if SAVE_MODEL_PARAMS: save(saver, sess, SNAPSHOT_DIR, iters) if not cross_validate_mode: # Store the accuracies computed at task T in a list evals.append(np.array(ftask)) # Reset the optimizer model.reset_optimizer(sess) #-> End for loop task if not cross_validate_mode: runs.append(np.array(evals)) if break_training: break # End for loop runid if cross_validate_mode: return np.mean(ftask) else: runs = np.array(runs) return runs, task_labels_dataset def test_task_sequence(model, sess, test_data, class_attr, num_classes_per_task, test_tasks, task): """ Snapshot the current performance """ final_acc = np.zeros(model.num_tasks) if model.imp_method == 'A-GEM': logit_mask = np.zeros([model.num_tasks, TOTAL_CLASSES]) else: logit_mask = np.zeros(TOTAL_CLASSES) for tt, labels in enumerate(test_tasks): if not MULTI_TASK: if tt > task: return final_acc masked_class_attrs = np.zeros_like(class_attr) masked_class_attrs[labels] = class_attr[labels] task_test_images, task_test_labels = load_task_specific_data(test_data, labels) total_test_samples = task_test_images.shape[0] samples_at_a_time = 10 total_corrects = 0 logit_mask[:] = 0 if model.imp_method == 'A-GEM': logit_mask[tt][labels] = 1.0 logit_mask_dict = {m_t: i_t for (m_t, i_t) in zip(model.output_mask, logit_mask)} else: logit_mask[labels] = 1.0 for i in range(total_test_samples/ samples_at_a_time): offset = i*samples_at_a_time feed_dict = {model.x: task_test_images[offset:offset+samples_at_a_time], model.y_: task_test_labels[offset:offset+samples_at_a_time], model.class_attr: masked_class_attrs, model.keep_prob: 1.0, model.train_phase: False} if model.imp_method == 'A-GEM': feed_dict.update(logit_mask_dict) total_corrects += np.sum(sess.run(model.correct_predictions[tt], feed_dict=feed_dict)) else: feed_dict[model.output_mask] = logit_mask total_corrects += np.sum(sess.run(model.correct_predictions, feed_dict=feed_dict)) # Compute the corrects on residuals offset = (i+1)*samples_at_a_time num_residuals = total_test_samples % samples_at_a_time feed_dict = {model.x: task_test_images[offset:offset+num_residuals], model.y_: task_test_labels[offset:offset+num_residuals], model.class_attr: masked_class_attrs, model.keep_prob: 1.0, model.train_phase: False} if model.imp_method == 'A-GEM': feed_dict.update(logit_mask_dict) total_corrects += np.sum(sess.run(model.correct_predictions[tt], feed_dict=feed_dict)) else: feed_dict[model.output_mask] = logit_mask total_corrects += np.sum(sess.run(model.correct_predictions, feed_dict=feed_dict)) # Mean accuracy on the task acc = total_corrects/ float(total_test_samples) final_acc[tt] = acc return final_acc def main(): """ Create the model and start the training """ # Get the CL arguments args = get_arguments() # Check if the network architecture is valid if args.arch not in VALID_ARCHS: raise ValueError("Network architecture %s is not supported!"%(args.arch)) # Check if the method to compute importance is valid if args.imp_method not in MODELS: raise ValueError("Importance measure %s is undefined!"%(args.imp_method)) # Check if the optimizer is valid if args.optim not in VALID_OPTIMS: raise ValueError("Optimizer %s is undefined!"%(args.optim)) # Create log directories to store the results if not os.path.exists(args.log_dir): print('Log directory %s created!'%(args.log_dir)) os.makedirs(args.log_dir) # Get the task labels from the total number of tasks and full label space classes_per_task = TOTAL_CLASSES// NUM_TASKS if args.online_cross_val: num_tasks = K_FOR_CROSS_VAL else: num_tasks = NUM_TASKS - K_FOR_CROSS_VAL # Load the split CUB dataset data_labs = [np.arange(TOTAL_CLASSES)] datasets, CUB_attr = construct_split_cub(data_labs, args.data_dir, CUB_TRAIN_LIST, CUB_TEST_LIST, IMG_HEIGHT, IMG_WIDTH, attr_file=CUB_ATTR_LIST) if args.online_cross_val: CUB_attr[K_FOR_CROSS_VAL*classes_per_task:] = 0 else: CUB_attr[:K_FOR_CROSS_VAL*classes_per_task] = 0 if args.cross_validate_mode: models_list = MODELS learning_rate_list = [0.3, 0.1, 0.01, 0.003, 0.001] else: models_list = [args.imp_method] for imp_method in models_list: if imp_method == 'VAN': synap_stgth_list = [0] if args.online_cross_val or args.cross_validate_mode: pass else: learning_rate_list = [0.03] elif imp_method == 'PI': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10] else: synap_stgth_list = [0.1] learning_rate_list = [0.03] elif imp_method == 'EWC' or imp_method == 'M-EWC': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [10] learning_rate_list = [0.03] elif imp_method == 'MAS': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [0.1] learning_rate_list = [0.03] elif imp_method == 'RWALK': if args.online_cross_val or args.cross_validate_mode: synap_stgth_list = [0.1, 1, 10, 100] else: synap_stgth_list = [1] learning_rate_list = [0.03] elif imp_method == 'S-GEM': synap_stgth_list = [0] if args.online_cross_val: pass else: learning_rate_list = [args.learning_rate] elif imp_method == 'A-GEM': synap_stgth_list = [0] if args.online_cross_val or args.cross_validate_mode: pass else: learning_rate_list = [0.03] for synap_stgth in synap_stgth_list: for lr in learning_rate_list: # Generate the experiment key and store the meta data in a file exper_meta_data = {'ARCH': args.arch, 'DATASET': 'SPLIT_CUB', 'HYBRID': args.set_hybrid, 'NUM_RUNS': args.num_runs, 'TRAIN_SINGLE_EPOCH': args.train_single_epoch, 'IMP_METHOD': imp_method, 'SYNAP_STGTH': synap_stgth, 'FISHER_EMA_DECAY': args.fisher_ema_decay, 'FISHER_UPDATE_AFTER': args.fisher_update_after, 'OPTIM': args.optim, 'LR': lr, 'BATCH_SIZE': args.batch_size, 'EPS_MEMORY': args.do_sampling, 'MEM_SIZE': args.mem_size, 'IS_HERDING': args.is_herding} experiment_id = "SPLIT_CUB_HERDING_%r_HYB_%r_%s_%r_%s_%s_%s_%r_%s-"%(args.is_herding, args.set_hybrid, args.arch, args.train_single_epoch, imp_method, str(synap_stgth).replace('.', '_'), str(args.batch_size), args.do_sampling, str(args.mem_size)) + datetime.datetime.now().strftime("%y-%m-%d-%H-%M") snapshot_experiment_meta_data(args.log_dir, experiment_id, exper_meta_data) # Reset the default graph tf.reset_default_graph() graph = tf.Graph() with graph.as_default(): # Set the random seed tf.set_random_seed(RANDOM_SEED) # Define Input and Output of the model x = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) y_ = tf.placeholder(tf.float32, shape=[None, TOTAL_CLASSES]) attr = tf.placeholder(tf.float32, shape=[TOTAL_CLASSES, ATTR_DIMS]) if not args.train_single_epoch: # Define ops for data augmentation x_aug = image_scaling(x) x_aug = random_crop_and_pad_image(x_aug, IMG_HEIGHT, IMG_WIDTH) # Define the optimizer if args.optim == 'ADAM': opt = tf.train.AdamOptimizer(learning_rate=lr) elif args.optim == 'SGD': opt = tf.train.GradientDescentOptimizer(learning_rate=lr) elif args.optim == 'MOMENTUM': base_lr = tf.constant(lr) learning_rate = tf.scalar_mul(base_lr, tf.pow((1 - train_step / training_iters), OPT_POWER)) opt = tf.train.MomentumOptimizer(lr, OPT_MOMENTUM) # Create the Model/ contruct the graph if args.train_single_epoch: # When training using a single epoch then there is no need for data augmentation model = Model(x, y_, num_tasks, opt, imp_method, synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch, is_ATT_DATASET=True, attr=attr) else: model = Model(x_aug, y_, num_tasks, opt, imp_method, synap_stgth, args.fisher_update_after, args.fisher_ema_decay, network_arch=args.arch, is_ATT_DATASET=True, x_test=x, attr=attr) # Set up tf session and initialize variables. config = tf.ConfigProto() config.gpu_options.allow_growth = True time_start = time.time() with tf.Session(config=config, graph=graph) as sess: saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=100) runs, task_labels_dataset = train_task_sequence(model, sess, saver, datasets, CUB_attr, classes_per_task, args.cross_validate_mode, args.train_single_epoch, args.do_sampling, args.is_herding, args.mem_size, args.train_iters, args.batch_size, args.num_runs, args.init_checkpoint, args.online_cross_val, args.random_seed) # Close the session sess.close() time_end = time.time() time_spent = time_end - time_start print('Time spent: {}'.format(time_spent)) # Clean up del model if args.cross_validate_mode: # If cross-validation flag is enabled, store the stuff in a text file cross_validate_dump_file = args.log_dir + '/' + 'SPLIT_CUB_%s_%s'%(imp_method, args.optim) + '.txt' with open(cross_validate_dump_file, 'a') as f: f.write('HERDING: {} \t ARCH: {} \t LR:{} \t LAMBDA: {} \t ACC: {}\n'.format(args.is_herding, args.arch, lr, synap_stgth, runs)) else: # Store all the results in one dictionary to process later exper_acc = dict(mean=runs) exper_labels = dict(labels=task_labels_dataset) # Store the experiment output to a file snapshot_experiment_eval(args.log_dir, experiment_id, exper_acc) snapshot_task_labels(args.log_dir, experiment_id, exper_labels) if __name__ == '__main__': main()
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import math import tensorflow as tf import numpy as np def vgg_conv_layer(x, kernel_size, out_channels, stride, var_list, pad="SAME", name="conv"): """ Define API for conv operation. This includes kernel declaration and conv operation both followed by relu. """ in_channels = x.get_shape().as_list()[-1] with tf.variable_scope(name): #n = kernel_size * kernel_size * out_channels n = kernel_size * in_channels stdv = 1.0 / math.sqrt(n) w = tf.get_variable('kernel_weights', [kernel_size, kernel_size, in_channels, out_channels], tf.float32, initializer=tf.random_uniform_initializer(-stdv, stdv)) b = tf.get_variable('kernel_biases', [out_channels], tf.float32, initializer=tf.random_uniform_initializer(-stdv, stdv)) # Append the variable to the trainable variables list var_list.append(w) var_list.append(b) # Do the convolution operation bias = tf.nn.bias_add(tf.nn.conv2d(x, w, [1, stride, stride, 1], padding=pad), b) relu = tf.nn.relu(bias) return relu def vgg_fc_layer(x, out_dim, var_list, apply_relu=True, name="fc"): """ Define API for the fully connected layer. This includes both the variable declaration and matmul operation. """ in_dim = x.get_shape().as_list()[1] stdv = 1.0 / math.sqrt(in_dim) with tf.variable_scope(name): # Define the weights and biases for this layer w = tf.get_variable('weights', [in_dim, out_dim], tf.float32, initializer=tf.random_uniform_initializer(-stdv, stdv)) b = tf.get_variable('biases', [out_dim], tf.float32, initializer=tf.random_uniform_initializer(-stdv, stdv)) # Append the variable to the trainable variables list var_list.append(w) var_list.append(b) # Do the FC operation output = tf.matmul(x, w) + b # Apply relu if needed if apply_relu: output = tf.nn.relu(output) return output
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from .data_utils import construct_permute_mnist, construct_split_mnist, construct_split_cifar, construct_split_cub, construct_split_imagenet from .data_utils import image_scaling, random_crop_and_pad_image, random_horizontal_flip from .utils import clone_variable_list, create_fc_layer, create_conv_layer, sample_from_dataset, update_episodic_memory, update_episodic_memory_with_less_data, concatenate_datasets from .utils import samples_for_each_class, sample_from_dataset_icarl, get_sample_weights, compute_fgt, load_task_specific_data, load_task_specific_data_in_proportion from .utils import average_acc_stats_across_runs, average_fgt_stats_across_runs, update_reservior from .vis_utils import plot_acc_multiple_runs, plot_histogram, snapshot_experiment_meta_data, snapshot_experiment_eval, snapshot_task_labels from .resnet_utils import _conv, _fc, _bn, _residual_block, _residual_block_first from .vgg_utils import vgg_conv_layer, vgg_fc_layer
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import math import tensorflow as tf import numpy as np def _conv(x, kernel_size, out_channels, stride, var_list, pad="SAME", name="conv"): """ Define API for conv operation. This includes kernel declaration and conv operation both. """ in_channels = x.get_shape().as_list()[-1] with tf.variable_scope(name): #n = kernel_size * kernel_size * out_channels n = kernel_size * in_channels stdv = 1.0 / math.sqrt(n) w = tf.get_variable('kernel', [kernel_size, kernel_size, in_channels, out_channels], tf.float32, initializer=tf.random_uniform_initializer(-stdv, stdv)) #initializer=tf.random_normal_initializer(stddev=np.sqrt(2.0/n))) # Append the variable to the trainable variables list var_list.append(w) # Do the convolution operation output = tf.nn.conv2d(x, w, [1, stride, stride, 1], padding=pad) return output def _fc(x, out_dim, var_list, name="fc", is_cifar=False): """ Define API for the fully connected layer. This includes both the variable declaration and matmul operation. """ in_dim = x.get_shape().as_list()[1] stdv = 1.0 / math.sqrt(in_dim) with tf.variable_scope(name): # Define the weights and biases for this layer w = tf.get_variable('weights', [in_dim, out_dim], tf.float32, initializer=tf.random_uniform_initializer(-stdv, stdv)) #initializer=tf.truncated_normal_initializer(stddev=0.1)) if is_cifar: b = tf.get_variable('biases', [out_dim], tf.float32, initializer=tf.random_uniform_initializer(-stdv, stdv)) else: b = tf.get_variable('biases', [out_dim], tf.float32, initializer=tf.constant_initializer(0)) # Append the variable to the trainable variables list var_list.append(w) var_list.append(b) # Do the FC operation output = tf.matmul(x, w) + b return output def _bn(x, var_list, train_phase, name='bn_'): """ Batch normalization on convolutional maps. Args: Return: """ n_out = x.get_shape().as_list()[3] with tf.variable_scope(name): beta = tf.get_variable('beta', shape=[n_out], dtype=tf.float32, initializer=tf.constant_initializer(0.0)) gamma = tf.get_variable('gamma', shape=[n_out], dtype=tf.float32, initializer=tf.constant_initializer(1.0)) var_list.append(beta) var_list.append(gamma) batch_mean, batch_var = tf.nn.moments(x, [0,1,2], name='moments') ema = tf.train.ExponentialMovingAverage(decay=0.9) def mean_var_with_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) mean, var = tf.cond(train_phase, mean_var_with_update, lambda: (ema.average(batch_mean), ema.average(batch_var))) normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3) return normed def _residual_block(x, trainable_vars, train_phase, apply_relu=True, name="unit"): """ ResNet block when the number of channels across the skip connections are the same """ in_channels = x.get_shape().as_list()[-1] with tf.variable_scope(name) as scope: shortcut = x x = _conv(x, 3, in_channels, 1, trainable_vars, name='conv_1') x = _bn(x, trainable_vars, train_phase, name="bn_1") x = tf.nn.relu(x) x = _conv(x, 3, in_channels, 1, trainable_vars, name='conv_2') x = _bn(x, trainable_vars, train_phase, name="bn_2") x = x + shortcut if apply_relu == True: x = tf.nn.relu(x) return x def _residual_block_first(x, out_channels, strides, trainable_vars, train_phase, apply_relu=True, name="unit", is_ATT_DATASET=False): """ A generic ResNet Block """ in_channels = x.get_shape().as_list()[-1] with tf.variable_scope(name) as scope: # Figure out the shortcut connection first if in_channels == out_channels: if strides == 1: shortcut = tf.identity(x) else: shortcut = tf.nn.max_pool(x, [1, strides, strides, 1], [1, strides, strides, 1], 'VALID') else: shortcut = _conv(x, 1, out_channels, strides, trainable_vars, name="shortcut") if not is_ATT_DATASET: shortcut = _bn(shortcut, trainable_vars, train_phase, name="bn_0") # Residual block x = _conv(x, 3, out_channels, strides, trainable_vars, name="conv_1") x = _bn(x, trainable_vars, train_phase, name="bn_1") x = tf.nn.relu(x) x = _conv(x, 3, out_channels, 1, trainable_vars, name="conv_2") x = _bn(x, trainable_vars, train_phase, name="bn_2") x = x + shortcut if apply_relu: x = tf.nn.relu(x) return x
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Define utility functions for manipulating datasets """ import os import numpy as np import sys from copy import deepcopy import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from six.moves.urllib.request import urlretrieve from six.moves import cPickle as pickle import tarfile import zipfile import random import cv2 #IMG_MEAN = np.array((104.00698793,116.66876762,122.67891434), dtype=np.float32) IMG_MEAN = np.array((103.94,116.78,123.68), dtype=np.float32) ############################################################ ### Data augmentation utils ################################ ############################################################ def image_scaling(images): """ Randomly scales the images between 0.5 to 1.5 times the original size. Args: images: Training images to scale. """ scale = tf.random_uniform([1], minval=0.5, maxval=1.5, dtype=tf.float32, seed=None) h_new = tf.to_int32(tf.multiply(tf.to_float(tf.shape(images)[1]), scale)) w_new = tf.to_int32(tf.multiply(tf.to_float(tf.shape(images)[2]), scale)) new_shape = tf.squeeze(tf.stack([h_new, w_new]), squeeze_dims=[1]) images = tf.image.resize_images(images, new_shape) result = tf.map_fn(lambda img: tf.image.random_flip_left_right(img), images) return result def random_crop_and_pad_image(images, crop_h, crop_w): """ Randomly crop and pads the input images. Args: images: Training i mages to crop/ pad. crop_h: Height of cropped segment. crop_w: Width of cropped segment. """ image_shape = tf.shape(images) image_pad = tf.image.pad_to_bounding_box(images, 0, 0, tf.maximum(crop_h, image_shape[1]), tf.maximum(crop_w, image_shape[2])) img_crop = tf.map_fn(lambda img: tf.random_crop(img, [crop_h,crop_w,3]), image_pad) return img_crop def random_horizontal_flip(x): """ Randomly flip a batch of images horizontally Args: x Tensor of shape B x H x W x C Returns: random_flipped Randomly flipped tensor of shape B x H x W x C """ # Define random horizontal flip flips = [(slice(None, None, None), slice(None, None, random.choice([-1, None])), slice(None, None, None)) for _ in xrange(x.shape[0])] random_flipped = np.array([img[flip] for img, flip in zip(x, flips)]) return random_flipped ############################################################ ### AWA dataset utils ##################################### ############################################################ def _AWA_read_img_from_file(data_dir, file_name, img_height, img_width): count = 0 imgs = [] labels = [] def dense_to_one_hot(labels_dense, num_classes=50): num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot with open(file_name) as f: for line in f: img_name, img_label = line.split() img_file = data_dir.rstrip('\/') + '/' + img_name img = cv2.imread(img_file).astype(np.float32) # HWC -> WHC, compatible with caffe weights #img = np.transpose(img, [1, 0, 2]) img = cv2.resize(img, (img_width, img_height)) # Convert RGB to BGR img_r, img_g, img_b = np.split(img, 3, axis=2) img = np.concatenate((img_b, img_g, img_r), axis=2) # Extract mean img -= IMG_MEAN imgs += [img] labels += [int(img_label)] count += 1 if count % 1000 == 0: print 'Finish reading {:07d}'.format(count) # Convert the labels to one-hot y = dense_to_one_hot(np.array(labels)) return np.array(imgs), y def _AWA_get_data(data_dir, train_list_file, val_list_file, test_list_file, img_height, img_width): """ Reads and parses examples from AWA dataset """ dataset = dict() dataset['train'] = [] dataset['validation'] = [] dataset['test'] = [] num_val_img = 0 # you can change the number of validation images here TODO: Pass this as argument train_img = [] train_label = [] validation_img = [] validation_label = [] test_img = [] test_label = [] # Read train, validation and test files train_img, train_label = _AWA_read_img_from_file(data_dir, train_list_file, img_height, img_width) #validation_img, validation_label = _AWA_read_img_from_file(data_dir, val_list_file, img_height, img_width) test_img, test_label = _AWA_read_img_from_file(data_dir, test_list_file, img_height, img_width) dataset['train'].append(train_img) dataset['train'].append(train_label) #dataset['validation'].append(validation_img) #dataset['validation'].append(validation_label) dataset['test'].append(test_img) dataset['test'].append(test_label) return dataset def construct_split_awa(task_labels, data_dir, train_list_file, val_list_file, test_list_file, img_height, img_width, attr_file=None): """ Construct Split AWA dataset Args: task_labels Labels of different tasks data_dir Data directory from where the AWA dataset will be read train_list_file File containing names of training images al_list_file File containing names of val images test_list_file File containing names of test images img_height Height of image img_width Width of image attr_file File from where to load the attributes """ # Get the awa dataset awa_data = _AWA_get_data(data_dir, train_list_file, val_list_file, test_list_file, img_height, img_width) # Get the attribute vector if attr_file: with open(attr_file, 'rb') as f: awa_attr = pickle.load(f) # Define a list for storing the data for different tasks datasets = [] # Data splits #sets = ["train", "validation", "test"] sets = ["train", "test"] for task in task_labels: for set_name in sets: this_set = awa_data[set_name] global_class_indices = np.column_stack(np.nonzero(this_set[1])) count = 0 for cls in task: if count == 0: class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])]) else: class_indices = np.append(class_indices, np.squeeze(global_class_indices[global_class_indices[:,1] ==\ cls][:,np.array([True, False])])) count += 1 class_indices = np.sort(class_indices, axis=None) if set_name == "train": train = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } elif set_name == "validation": validation = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } elif set_name == "test": test = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } awa = { 'train': train, #'validation': validation, 'test': test, } datasets.append(awa) if attr_file: return datasets, awa_attr else: return datasets ############################################################ ### CUB dataset utils ##################################### ############################################################ def _CUB_read_img_from_file(data_dir, file_name, img_height, img_width): count = 0 imgs = [] labels = [] def dense_to_one_hot(labels_dense, num_classes=200): num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot with open(file_name) as f: for line in f: img_name, img_label = line.split() img_file = data_dir.rstrip('\/') + '/' + img_name img = cv2.imread(img_file).astype(np.float32) # HWC -> WHC, compatible with caffe weights #img = np.transpose(img, [1, 0, 2]) img = cv2.resize(img, (img_width, img_height)) # Convert RGB to BGR img_r, img_g, img_b = np.split(img, 3, axis=2) img = np.concatenate((img_b, img_g, img_r), axis=2) # Extract mean img -= IMG_MEAN imgs += [img] labels += [int(img_label)] count += 1 if count % 1000 == 0: print 'Finish reading {:07d}'.format(count) # Convert the labels to one-hot y = dense_to_one_hot(np.array(labels)) return np.array(imgs), y def _CUB_get_data(data_dir, train_list_file, test_list_file, img_height, img_width): """ Reads and parses examples from CUB dataset """ dataset = dict() dataset['train'] = [] dataset['test'] = [] num_val_img = 0 # you can change the number of validation images here TODO: Pass this as argument train_img = [] train_label = [] test_img = [] test_label = [] # Read train and test files train_img, train_label = _CUB_read_img_from_file(data_dir, train_list_file, img_height, img_width) test_img, test_label = _CUB_read_img_from_file(data_dir, test_list_file, img_height, img_width) dataset['train'].append(train_img) dataset['train'].append(train_label) dataset['test'].append(test_img) dataset['test'].append(test_label) return dataset def construct_split_cub(task_labels, data_dir, train_list_file, test_list_file, img_height, img_width, attr_file=None): """ Construct Split CUB-200 dataset Args: task_labels Labels of different tasks data_dir Data directory from where the CUB-200 dataset will be read train_list_file File containing names of training images test_list_file File containing names of test images img_height Height of image img_width Width of image attr_fil File from where to load the attributes """ # Get the cub dataset cub_data = _CUB_get_data(data_dir, train_list_file, test_list_file, img_height, img_width) # Get the attribute vector if attr_file: with open(attr_file, 'rb') as f: cub_attr = pickle.load(f) # Define a list for storing the data for different tasks datasets = [] # Data splits sets = ["train", "test"] for task in task_labels: for set_name in sets: this_set = cub_data[set_name] global_class_indices = np.column_stack(np.nonzero(this_set[1])) count = 0 for cls in task: if count == 0: class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])]) else: class_indices = np.append(class_indices, np.squeeze(global_class_indices[global_class_indices[:,1] ==\ cls][:,np.array([True, False])])) count += 1 class_indices = np.sort(class_indices, axis=None) if set_name == "train": train = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } elif set_name == "test": test = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } cub = { 'train': train, 'test': test, } datasets.append(cub) if attr_file: return datasets, cub_attr else: return datasets ############################################################ ### CIFAR download utils ################################### ############################################################ CIFAR_10_URL = "http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" CIFAR_100_URL = "http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz" CIFAR_10_DIR = "/cifar_10" CIFAR_100_DIR = "/cifar_100" def construct_split_cifar(task_labels, is_cifar_100=True): """ Construct Split CIFAR-10 and CIFAR-100 datasets Args: task_labels Labels of different tasks data_dir Data directory where the CIFAR data will be saved """ data_dir = 'CIFAR_data' # Get the cifar dataset cifar_data = _get_cifar(data_dir, is_cifar_100) # Define a list for storing the data for different tasks datasets = [] # Data splits sets = ["train", "validation", "test"] for task in task_labels: for set_name in sets: this_set = cifar_data[set_name] global_class_indices = np.column_stack(np.nonzero(this_set[1])) count = 0 for cls in task: if count == 0: class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])]) else: class_indices = np.append(class_indices, np.squeeze(global_class_indices[global_class_indices[:,1] ==\ cls][:,np.array([True, False])])) count += 1 class_indices = np.sort(class_indices, axis=None) if set_name == "train": train = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } elif set_name == "validation": validation = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } elif set_name == "test": test = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } cifar = { 'train': train, 'validation': validation, 'test': test, } datasets.append(cifar) return datasets def _get_cifar(data_dir, is_cifar_100): """ Get the CIFAR-10 and CIFAR-100 datasets Args: data_dir Directory where the downloaded data will be stored """ x_train = None y_train = None x_validation = None y_validation = None x_test = None y_test = None l = None # Download the dataset if needed _cifar_maybe_download_and_extract(data_dir) # Dictionary to store the dataset dataset = dict() dataset['train'] = [] dataset['validation'] = [] dataset['test'] = [] def dense_to_one_hot(labels_dense, num_classes=100): num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot if is_cifar_100: # Load the training data of CIFAR-100 f = open(data_dir + CIFAR_100_DIR + '/train', 'rb') datadict = pickle.load(f) f.close() _X = datadict['data'] _Y = np.array(datadict['fine_labels']) _Y = dense_to_one_hot(_Y, num_classes=100) _X = np.array(_X, dtype=float) / 255.0 _X = _X.reshape([-1, 3, 32, 32]) _X = _X.transpose([0, 2, 3, 1]) # Compute the data mean for normalization x_train_mean = np.mean(_X, axis=0) x_train = _X[:40000] y_train = _Y[:40000] x_validation = _X[40000:] y_validation = _Y[40000:] else: # Load all the training batches of the CIFAR-10 for i in range(5): f = open(data_dir + CIFAR_10_DIR + '/data_batch_' + str(i + 1), 'rb') datadict = pickle.load(f) f.close() _X = datadict['data'] _Y = np.array(datadict['labels']) _Y = dense_to_one_hot(_Y, num_classes=10) _X = np.array(_X, dtype=float) / 255.0 _X = _X.reshape([-1, 3, 32, 32]) _X = _X.transpose([0, 2, 3, 1]) if x_train is None: x_train = _X y_train = _Y else: x_train = np.concatenate((x_train, _X), axis=0) y_train = np.concatenate((y_train, _Y), axis=0) # Compute the data mean for normalization x_train_mean = np.mean(x_train, axis=0) x_validation = x_train[:40000] # We don't use validation set with CIFAR-10 y_validation = y_train[40000:] # Normalize the train and validation sets x_train -= x_train_mean x_validation -= x_train_mean dataset['train'].append(x_train) dataset['train'].append(y_train) dataset['train'].append(l) dataset['validation'].append(x_validation) dataset['validation'].append(y_validation) dataset['validation'].append(l) if is_cifar_100: # Load the test batch of CIFAR-100 f = open(data_dir + CIFAR_100_DIR + '/test', 'rb') datadict = pickle.load(f) f.close() _X = datadict['data'] _Y = np.array(datadict['fine_labels']) _Y = dense_to_one_hot(_Y, num_classes=100) else: # Load the test batch of CIFAR-10 f = open(data_dir + CIFAR_10_DIR + '/test_batch', 'rb') datadict = pickle.load(f) f.close() _X = datadict["data"] _Y = np.array(datadict['labels']) _Y = dense_to_one_hot(_Y, num_classes=10) _X = np.array(_X, dtype=float) / 255.0 _X = _X.reshape([-1, 3, 32, 32]) _X = _X.transpose([0, 2, 3, 1]) x_test = _X y_test = _Y # Normalize the test set x_test -= x_train_mean dataset['test'].append(x_test) dataset['test'].append(y_test) dataset['test'].append(l) return dataset def _print_download_progress(count, block_size, total_size): """ Show the download progress of the cifar data """ pct_complete = float(count * block_size) / total_size msg = "\r- Download progress: {0:.1%}".format(pct_complete) sys.stdout.write(msg) sys.stdout.flush() def _cifar_maybe_download_and_extract(data_dir): """ Routine to download and extract the cifar dataset Args: data_dir Directory where the downloaded data will be stored """ cifar_10_directory = data_dir + CIFAR_10_DIR cifar_100_directory = data_dir + CIFAR_100_DIR # If the data_dir does not exist, create the directory and download # the data if not os.path.exists(data_dir): os.makedirs(data_dir) url = CIFAR_10_URL filename = url.split('/')[-1] file_path = os.path.join(data_dir, filename) zip_cifar_10 = file_path file_path, _ = urlretrieve(url=url, filename=file_path, reporthook=_print_download_progress) print() print("Download finished. Extracting files.") if file_path.endswith(".zip"): zipfile.ZipFile(file=file_path, mode="r").extractall(data_dir) elif file_path.endswith((".tar.gz", ".tgz")): tarfile.open(name=file_path, mode="r:gz").extractall(data_dir) print("Done.") url = CIFAR_100_URL filename = url.split('/')[-1] file_path = os.path.join(data_dir, filename) zip_cifar_100 = file_path file_path, _ = urlretrieve(url=url, filename=file_path, reporthook=_print_download_progress) print() print("Download finished. Extracting files.") if file_path.endswith(".zip"): zipfile.ZipFile(file=file_path, mode="r").extractall(data_dir) elif file_path.endswith((".tar.gz", ".tgz")): tarfile.open(name=file_path, mode="r:gz").extractall(data_dir) print("Done.") os.rename(data_dir + "/cifar-10-batches-py", cifar_10_directory) os.rename(data_dir + "/cifar-100-python", cifar_100_directory) os.remove(zip_cifar_10) os.remove(zip_cifar_100) ######################################### ## MNIST Utils ########################## ######################################### def reformat_mnist(datasets): """ Routine to Reformat the mnist dataset into a 3d tensor """ image_size = 28 # Height of MNIST dataset num_channels = 1 # Gray scale for i in range(len(datasets)): sets = ["train", "validation", "test"] for set_name in sets: datasets[i]['%s'%set_name]['images'] = datasets[i]['%s'%set_name]['images'].reshape\ ((-1, image_size, image_size, num_channels)).astype(np.float32) return datasets def construct_permute_mnist(num_tasks): """ Construct a dataset of permutted mnist images Args: num_tasks Number of tasks Returns dataset A permutted mnist dataset """ # Download and store mnist dataset mnist = input_data.read_data_sets('MNIST_data', one_hot=True) datasets = [] for i in range(num_tasks): perm_inds = range(mnist.train.images.shape[1]) np.random.shuffle(perm_inds) copied_mnist = deepcopy(mnist) sets = ["train", "validation", "test"] for set_name in sets: this_set = getattr(copied_mnist, set_name) # shallow copy this_set._images = np.transpose(np.array([this_set.images[:,c] for c in perm_inds])) if set_name == "train": train = { 'images':this_set._images, 'labels':this_set.labels, } elif set_name == "validation": validation = { 'images':this_set._images, 'labels':this_set.labels, } elif set_name == "test": test = { 'images':this_set._images, 'labels':this_set.labels, } dataset = { 'train': train, 'validation': validation, 'test': test, } datasets.append(dataset) return datasets def construct_split_mnist(task_labels): """ Construct a split mnist dataset Args: task_labels List of split labels Returns: dataset A list of split datasets """ # Download and store mnist dataset mnist = input_data.read_data_sets('MNIST_data', one_hot=True) datasets = [] sets = ["train", "validation", "test"] for task in task_labels: for set_name in sets: this_set = getattr(mnist, set_name) global_class_indices = np.column_stack(np.nonzero(this_set.labels)) count = 0 for cls in task: if count == 0: class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] ==\ cls][:,np.array([True, False])]) else: class_indices = np.append(class_indices, np.squeeze(global_class_indices[global_class_indices[:,1] ==\ cls][:,np.array([True, False])])) count += 1 class_indices = np.sort(class_indices, axis=None) if set_name == "train": train = { 'images':deepcopy(mnist.train.images[class_indices, :]), 'labels':deepcopy(mnist.train.labels[class_indices, :]), } elif set_name == "validation": validation = { 'images':deepcopy(mnist.validation.images[class_indices, :]), 'labels':deepcopy(mnist.validation.labels[class_indices, :]), } elif set_name == "test": test = { 'images':deepcopy(mnist.test.images[class_indices, :]), 'labels':deepcopy(mnist.test.labels[class_indices, :]), } mnist2 = { 'train': train, 'validation': validation, 'test': test, } datasets.append(mnist2) return datasets ################################################### ###### ImageNet Utils ############################# ################################################### def construct_split_imagenet(task_labels, data_dir): """ Construct Split ImageNet dataset Args: task_labels Labels of different tasks data_dir Data directory from where to load the imagenet data """ # Load the imagenet dataset imagenet_data = _load_imagenet(data_dir) # Define a list for storing the data for different tasks datasets = [] # Data splits sets = ["train", "test"] for task in task_labels: for set_name in sets: this_set = imagenet_data[set_name] global_class_indices = np.column_stack(np.nonzero(this_set[1])) count = 0 for cls in task: if count == 0: class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])]) else: class_indices = np.append(class_indices, np.squeeze(global_class_indices[global_class_indices[:,1] ==\ cls][:,np.array([True, False])])) count += 1 class_indices = np.sort(class_indices, axis=None) if set_name == "train": train = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } elif set_name == "test": test = { 'images':deepcopy(this_set[0][class_indices, :]), 'labels':deepcopy(this_set[1][class_indices, :]), } imagenet = { 'train': train, 'test': test, } datasets.append(imagenet) return datasets def _load_imagenet(data_dir): """ Load the ImageNet data Args: data_dir Directory where the pickle files have been dumped """ x_train = None y_train = None x_test = None y_test = None # Dictionary to store the dataset dataset = dict() dataset['train'] = [] dataset['test'] = [] def dense_to_one_hot(labels_dense, num_classes=100): num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot # Load the training batches for i in range(4): f = open(data_dir + '/train_batch_' + str(i), 'rb') datadict = pickle.load(f) f.close() _X = datadict['data'] _Y = np.array(datadict['labels']) # Convert the lables to one-hot _Y = dense_to_one_hot(_Y) # Normalize the images _X = np.array(_X, dtype=float)/ 255.0 _X = _X.reshape([-1, 224, 224, 3]) if x_train is None: x_train = _X y_train = _Y else: x_train = np.concatenate((x_train, _X), axis=0) y_train = np.concatenate((y_train, _Y), axis=0) dataset['train'].append(x_train) dataset['train'].append(y_train) # Load test batches for i in range(4): f = open(data_dir + '/test_batch_' + str(i), 'rb') datadict = pickle.load(f) f.close() _X = datadict['data'] _Y = np.array(datadict['labels']) # Convert the lables to one-hot _Y = dense_to_one_hot(_Y) # Normalize the images _X = np.array(_X, dtype=float)/ 255.0 _X = _X.reshape([-1, 224, 224, 3]) if x_test is None: x_test = _X y_test = _Y else: x_test = np.concatenate((x_test, _X), axis=0) y_test = np.concatenate((y_test, _Y), axis=0) dataset['test'].append(x_test) dataset['test'].append(y_test) return dataset
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Define some utility functions """ import numpy as np import tensorflow as tf def clone_variable_list(variable_list): """ Clone the variable list """ return [tf.identity(var) for var in variable_list] def create_fc_layer(input, w, b, apply_relu=True): """ Construct a Fully Connected layer Args: w Weights b Biases apply_relu Apply relu (T/F)? Returns: Output of an FC layer """ with tf.name_scope('fc_layer'): output = tf.matmul(input, w) + b # Apply relu if apply_relu: output = tf.nn.relu(output) return output def create_conv_layer(input, w, b, stride=1, apply_relu=True): """ Construct a convolutional layer Args: w Weights b Biases pre_activations List where the pre_activations will be stored apply_relu Apply relu (T/F)? Returns: Output of a conv layer """ with tf.name_scope('conv_layer'): # Do the convolution operation output = tf.nn.conv2d(input, w, [1, stride, stride, 1], padding='SAME') + b # Apply relu if apply_relu: output = tf.nn.relu(output) return output def load_task_specific_data_in_proportion(datasets, task_labels, classes_appearing_in_tasks, class_seen_already): """ Loads task specific data from the datasets proportionate to classes appearing in different tasks """ global_class_indices = np.column_stack(np.nonzero(datasets['labels'])) count = 0 for cls in task_labels: if count == 0: class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])]) total_class_instances = class_indices.size num_instances_to_choose = total_class_instances // classes_appearing_in_tasks[cls] offset = (class_seen_already[cls] - 1) * num_instances_to_choose final_class_indices = class_indices[offset: offset+num_instances_to_choose] else: current_class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])]) total_class_instances = current_class_indices.size num_instances_to_choose = total_class_instances // classes_appearing_in_tasks[cls] offset = (class_seen_already[cls] - 1) * num_instances_to_choose final_class_indices = np.append(final_class_indices, current_class_indices[offset: offset+num_instances_to_choose]) count += 1 final_class_indices = np.sort(final_class_indices, axis=None) return datasets['images'][final_class_indices, :], datasets['labels'][final_class_indices, :] def load_task_specific_data(datasets, task_labels): """ Loads task specific data from the datasets """ global_class_indices = np.column_stack(np.nonzero(datasets['labels'])) count = 0 for cls in task_labels: if count == 0: class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])]) else: class_indices = np.append(class_indices, np.squeeze(global_class_indices[global_class_indices[:,1] == cls][:,np.array([True, False])])) count += 1 class_indices = np.sort(class_indices, axis=None) return datasets['images'][class_indices, :], datasets['labels'][class_indices, :] def samples_for_each_class(dataset_labels, task): """ Numbers of samples for each class in the task Args: dataset_labels Labels to count samples from task Labels with in a task Returns """ num_samples = np.zeros([len(task)], dtype=np.float32) i = 0 for label in task: global_class_indices = np.column_stack(np.nonzero(dataset_labels)) class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == label][:,np.array([True, False])]) class_indices = np.sort(class_indices, axis=None) num_samples[i] = len(class_indices) i += 1 return num_samples def get_sample_weights(labels, tasks): weights = np.zeros([labels.shape[0]], dtype=np.float32) for label in tasks: global_class_indices = np.column_stack(np.nonzero(labels)) class_indices = np.array(np.squeeze(global_class_indices[global_class_indices[:,1] == label][:,np.array([True, False])])) total_class_samples = class_indices.shape[0] weights[class_indices] = 1.0/ total_class_samples # Rescale the weights such that min is 1. This will make the weights of less observed # examples 1. weights /= weights.min() return weights def update_episodic_memory_with_less_data(task_dataset, importance_array, total_mem_size, task, episodic_images, episodic_labels, task_labels=None, is_herding=False): """ Update the episodic memory when the task data is less than the memory size Args: Returns: """ num_examples_in_task = task_dataset['images'].shape[0] # Empty spaces in the episodic memory empty_spaces = np.sum(np.sum(episodic_labels, axis=1) == 0) if empty_spaces >= num_examples_in_task: # Find where the empty spaces are in order empty_indices = np.where(np.sum(episodic_labels, axis=1) == 0)[0] # Store the whole task data in the episodic memory episodic_images[empty_indices[:num_examples_in_task]] = task_dataset['images'] episodic_labels[empty_indices[:num_examples_in_task]] = task_dataset['labels'] elif empty_spaces == 0: # Compute the amount of space in the episodic memory for the new task space_for_new_task = total_mem_size// (task + 1) # task 0, 1, ... # Get the indices to update in the episodic memory eps_mem_indices = np.random.choice(total_mem_size, space_for_new_task, replace=False) # Sample without replacement # Get the indices of important samples from the task dataset label_importance = importance_array + 1e-32 label_importance /= np.sum(label_importance) # Convert to a probability distribution task_mem_indices = np.random.choice(num_examples_in_task, space_for_new_task, p=label_importance, replace=False) # Sample without replacement # Update the episodic memory episodic_images[eps_mem_indices] = task_dataset['images'][task_mem_indices] episodic_labels[eps_mem_indices] = task_dataset['labels'][task_mem_indices] else: # When there is some free space but not enough to store the whole task # Find where the empty spaces are in order empty_indices = np.where(np.sum(episodic_labels, axis=1) == 0)[0] # Store some of the examples from task in the memory episodic_images[empty_indices] = task_dataset['images'][:len(empty_indices)] episodic_labels[empty_indices] = task_dataset['labels'][:len(empty_indices)] # Adjust the remanining samples in the episodic memory space_for_new_task = (total_mem_size // (task + 1)) - len(empty_indices) # task 0, 1, ... # Get the indices to update in the episodic memory eps_mem_indices = np.random.choice((total_mem_size - len(empty_indices)), space_for_new_task, replace=False) # Sample without replacement # Get the indices of important samples from the task dataset label_importance = importance_array[len(empty_indices):] + 1e-32 label_importance /= np.sum(label_importance) # Convert to a probability distribution updated_num_examples_in_task = num_examples_in_task - len(empty_indices) task_mem_indices = np.random.choice(updated_num_examples_in_task, space_for_new_task, p=label_importance, replace=False) # Sample without replacement task_mem_indices += len(empty_indices) # Add the offset # Update the episodic memory episodic_images[eps_mem_indices] = task_dataset['images'][task_mem_indices] episodic_labels[eps_mem_indices] = task_dataset['labels'][task_mem_indices] def update_episodic_memory(task_dataset, importance_array, total_mem_size, task, episodic_images, episodic_labels, task_labels=None, is_herding=False): """ Update the episodic memory with new task data Args: Reruns: """ num_examples_in_task = task_dataset['images'].shape[0] # Compute the amount of space in the episodic memory for the new task space_for_new_task = total_mem_size// (task + 1) # task 0, 1, ... # Get the indices to update in the episodic memory eps_mem_indices = np.random.choice(total_mem_size, space_for_new_task, replace=False) # Sample without replacement if is_herding and task_labels is not None: # Get the samples based on herding imp_images, imp_labels = sample_from_dataset_icarl(task_dataset, importance_array, task_labels, space_for_new_task//len(task_labels)) episodic_images[eps_mem_indices[np.arange(imp_images.shape[0])]] = imp_images episodic_labels[eps_mem_indices[np.arange(imp_images.shape[0])]] = imp_labels else: # Get the indices of important samples from the task dataset label_importance = importance_array + 1e-32 label_importance /= np.sum(label_importance) # Convert to a probability distribution task_mem_indices = np.random.choice(num_examples_in_task, space_for_new_task, p=label_importance, replace=False) # Sample without replacement # Update the episodic memory episodic_images[eps_mem_indices] = task_dataset['images'][task_mem_indices] episodic_labels[eps_mem_indices] = task_dataset['labels'][task_mem_indices] def sample_from_dataset(dataset, importance_array, task, samples_count, preds=None): """ Samples from a dataset based on a probability distribution Args: dataset Dataset to sample from importance_array Importance scores (not necessarily have to be a prob distribution) task Labels with in a task samples_count Number of samples to return Return: images Important images labels Important labels """ count = 0 # For each label in the task extract the important samples for label in task: global_class_indices = np.column_stack(np.nonzero(dataset['labels'])) class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == label][:,np.array([True, False])]) class_indices = np.sort(class_indices, axis=None) if (preds is not None): # Find the indices where prediction match the correct label pred_indices = np.where(preds == label)[0] # Find the correct prediction indices correct_pred_indices = np.intersect1d(pred_indices, class_indices) else: correct_pred_indices = class_indices # Extract the importance for the label label_importance = importance_array[correct_pred_indices] + 1e-32 label_importance /= np.sum(label_importance) actual_samples_count = min(samples_count, np.count_nonzero(label_importance)) #print('Storing {} samples from {} class'.format(actual_samples_count, label)) # If no samples are correctly classified then skip saving the samples if (actual_samples_count != 0): # Extract the important indices imp_indices = np.random.choice(correct_pred_indices, actual_samples_count, p=label_importance, replace=False) if count == 0: images = dataset['images'][imp_indices] labels = dataset['labels'][imp_indices] else: images = np.vstack((images, dataset['images'][imp_indices])) labels = np.vstack((labels, dataset['labels'][imp_indices])) count += 1 if count != 0: return images, labels else: return None, None def concatenate_datasets(current_images, current_labels, prev_images, prev_labels): """ Concatnates current dataset with the previous one. This will be used for adding important samples from the previous datasets Args: current_images Images of current dataset current_labels Labels of current dataset prev_images List containing images of previous datasets prev_labels List containing labels of previous datasets Returns: images Concatenated images labels Concatenated labels """ """ images = current_images labels = current_labels for i in range(len(prev_images)): images = np.vstack((images, prev_images[i])) labels = np.vstack((labels, prev_labels[i])) """ images = np.concatenate((current_images, prev_images), axis=0) labels = np.concatenate((current_labels, prev_labels), axis=0) return images, labels def sample_from_dataset_icarl(dataset, features, task, samples_count, preds=None): """ Samples from a dataset based on a icarl - mean of features Args: dataset Dataset to sample from features Features - activation before the last layer task Labels with in a task samples_count Number of samples to return Return: images Important images labels Important labels """ print('Herding based sampling!') #samples_count = min(samples_count, dataset['images'].shape[0]) count = 0 # For each label in the task extract the important samples for label in task: global_class_indices = np.column_stack(np.nonzero(dataset['labels'])) class_indices = np.squeeze(global_class_indices[global_class_indices[:,1] == label][:,np.array([True, False])]) class_indices = np.sort(class_indices, axis=None) if (preds is not None): # Find the indices where prediction match the correct label pred_indices = np.where(preds == label)[0] # Find the correct prediction indices correct_pred_indices = np.intersect1d(pred_indices, class_indices) else: correct_pred_indices = class_indices mean_feature = np.mean(features[correct_pred_indices, :], axis=0) actual_samples_count = min(samples_count, len(correct_pred_indices)) # If no samples are correctly classified then skip saving the samples imp_indices = np.zeros(actual_samples_count, dtype=np.int32) sample_sum= np.zeros(mean_feature.shape) if (actual_samples_count != 0): # Extract the important indices for i in range(actual_samples_count): sample_mean = (features[correct_pred_indices, :] + np.tile(sample_sum, [len(correct_pred_indices),1]))/ float(i + 1) norm_distance = np.linalg.norm((np.tile(mean_feature, [len(correct_pred_indices),1]) - sample_mean), ord=2, axis=1) imp_indices[i] = correct_pred_indices[np.argmin(norm_distance)] sample_sum = sample_sum + features[imp_indices[i], :] if count == 0: images = dataset['images'][imp_indices] labels = dataset['labels'][imp_indices] else: images = np.vstack((images, dataset['images'][imp_indices])) labels = np.vstack((labels, dataset['labels'][imp_indices])) count += 1 if count != 0: return images, labels else: return None, None def average_acc_stats_across_runs(data, key): """ Compute the average accuracy statistics (mean and std) across runs """ num_runs = data.shape[0] avg_acc = np.zeros(num_runs) for i in range(num_runs): avg_acc[i] = np.mean(data[i][-1]) return avg_acc.mean()*100, avg_acc.std()*100 def average_fgt_stats_across_runs(data, key): """ Compute the forgetting statistics (mean and std) across runs """ num_runs = data.shape[0] fgt = np.zeros(num_runs) wst_fgt = np.zeros(num_runs) for i in range(num_runs): fgt[i] = compute_fgt(data[i]) return fgt.mean(), fgt.std() def compute_fgt(data): """ Given a TxT data matrix, compute average forgetting at T-th task """ num_tasks = data.shape[0] T = num_tasks - 1 fgt = 0.0 for i in range(T): fgt += np.max(data[:T,i]) - data[T, i] avg_fgt = fgt/ float(num_tasks - 1) return avg_fgt def update_reservior(current_image, current_label, episodic_images, episodic_labels, M, N): """ Update the episodic memory with current example using the reservior sampling """ if M > N: episodic_images[N] = current_image episodic_labels[N] = current_label else: j = np.random.randint(0, N) if j < M: episodic_images[j] = current_image episodic_labels[j] = current_label
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Define some utility functions """ import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.colors as colors import matplotlib.cm as cmx import matplotlib.pyplot as plt import matplotlib.figure as figure from six.moves import cPickle as pickle def snapshot_experiment_eval(logdir, experiment_id, data): """ Store the output of the experiment in a file """ snapshot_file = logdir + '/' + experiment_id + '.pickle' with open(snapshot_file, 'wb') as f: pickle.dump(data, f) print('Experimental Eval has been snapshotted to %s!'%(snapshot_file)) def snapshot_task_labels(logdir, experiment_id, data): """ Store the output of the experiment in a file """ snapshot_file = logdir + '/' + experiment_id + '_task_labels.pickle' with open(snapshot_file, 'wb') as f: pickle.dump(data, f) print('Experimental Eval has been snapshotted to %s!'%(snapshot_file)) def snapshot_experiment_meta_data(logdir, experiment_id, exper_meta_data): """ Store the meta-data of the experiment in a file """ meta_file = logdir + '/' + experiment_id + '.txt' with open(meta_file, 'wb') as f: for key in exper_meta_data: print('{}: {}'.format(key, exper_meta_data[key])) f.write('{}:{} \n'.format(key, exper_meta_data[key])) print('Experimental meta-data has been snapshotted to %s!'%(meta_file)) def plot_acc_multiple_runs(data, task_labels, valid_measures, n_stats, plot_name=None): """ Plots the accuracies Args: task_labels List of tasks n_stats Number of runs plot_name Name of the file where the plot will be saved Returns: """ n_tasks = len(task_labels) plt.figure(figsize=(14, 3)) axs = [plt.subplot(1,n_tasks+1,1)] for i in range(1, n_tasks + 1): axs.append(plt.subplot(1, n_tasks+1, i+1, sharex=axs[0], sharey=axs[0])) fmt_chars = ['o', 's', 'd'] fmts = [] for i in range(len(valid_measures)): fmts.append(fmt_chars[i%len(fmt_chars)]) plot_keys = sorted(data['mean'].keys()) for k, cval in enumerate(plot_keys): label = "c=%g"%cval mean_vals = data['mean'][cval] std_vals = data['std'][cval] for j in range(n_tasks+1): plt.sca(axs[j]) errorbar_kwargs = dict(fmt="%s-"%fmts[k], markersize=5) if j < n_tasks: norm= np.sqrt(n_stats) # np.sqrt(n_stats) for SEM or 1 for STDEV axs[j].errorbar(np.arange(n_tasks)+1, mean_vals[:, j], yerr=std_vals[:, j]/norm, label=label, **errorbar_kwargs) else: mean_stuff = [] std_stuff = [] for i in range(len(data['mean'][cval])): mean_stuff.append(data['mean'][cval][i][:i+1].mean()) std_stuff.append(np.sqrt((data['std'][cval][i][:i+1]**2).sum())/(n_stats*np.sqrt(n_stats))) plt.errorbar(range(1,n_tasks+1), mean_stuff, yerr=std_stuff, label="%s"%valid_measures[k], **errorbar_kwargs) plt.xticks(np.arange(n_tasks)+1) plt.xlim((1.0,5.5)) """ # Uncomment this if clutter along y-axis needs to be removed if j == 0: axs[j].set_yticks([0.5,1]) else: plt.setp(axs[j].get_yticklabels(), visible=False) plt.ylim((0.45,1.1)) """ for i, ax in enumerate(axs): if i < n_tasks: ax.set_title((['Task %d (%d to %d)'%(j+1,task_labels[j][0], task_labels[j][-1])\ for j in range(n_tasks)] + ['average'])[i], fontsize=8) else: ax.set_title("Average", fontsize=8) ax.axhline(0.5, color='k', linestyle=':', label="chance", zorder=0) handles, labels = axs[-1].get_legend_handles_labels() # Reorder legend so chance is last axs[-1].legend([handles[j] for j in [i for i in range(len(valid_measures)+1)]], [labels[j] for j in [i for i in range(len(valid_measures)+1)]], loc='best', fontsize=6) axs[0].set_xlabel("Tasks") axs[0].set_ylabel("Accuracy") plt.gcf().tight_layout() plt.grid('on') if plot_name == None: plt.show() else: plt.savefig(plot_name) def plot_histogram(data, n_bins=10, plot_name='my_hist'): plt.hist(data, bins=n_bins) plt.savefig(plot_name) plt.close()
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from .model import Model
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Model defintion """ import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from IPython import display from utils import clone_variable_list, create_fc_layer, create_conv_layer from utils.resnet_utils import _conv, _fc, _bn, _residual_block, _residual_block_first from utils.vgg_utils import vgg_conv_layer, vgg_fc_layer PARAM_XI_STEP = 1e-3 NEG_INF = -1e32 EPSILON = 1e-32 HYBRID_ALPHA = 0.5 TRAIN_ENTROPY_BASED_SUM = False def weight_variable(shape, name='fc', init_type='default'): """ Define weight variables Args: shape Shape of the bias variable tensor Returns: A tensor of size shape initialized from a random normal """ with tf.variable_scope(name): if init_type == 'default': weights = tf.get_variable('weights', shape, tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1)) #weights = tf.Variable(tf.truncated_normal(shape, stddev=0.1), name='weights') elif init_type == 'zero': weights = tf.get_variable('weights', shape, tf.float32, initializer=tf.constant_initializer(0.1)) #weights = tf.Variable(tf.constant(0.1, shape=shape, dtype=np.float32), name='weights') return weights def bias_variable(shape, name='fc'): """ Define bias variables Args: shape Shape of the bias variable tensor Returns: A tensor of size shape initialized from a constant """ with tf.variable_scope(name): biases = tf.get_variable('biases', shape, initializer=tf.constant_initializer(0.1)) return biases #return tf.Variable(tf.constant(0.1, shape=shape, dtype=np.float32), name='biases') #TODO: Should we initialize it from 0 class Model: """ A class defining the model """ def __init__(self, x_train, y_, num_tasks, opt, imp_method, synap_stgth, fisher_update_after, fisher_ema_decay, network_arch='FC-S', is_ATT_DATASET=False, x_test=None, attr=None): """ Instantiate the model """ # Define some placeholders which are used to feed the data to the model self.y_ = y_ if imp_method == 'PNN': self.train_phase = [] self.total_classes = int(self.y_[0].get_shape()[1]) self.train_phase = [tf.placeholder(tf.bool, name='train_phase_%d'%(i)) for i in range(num_tasks)] self.output_mask = [tf.placeholder(dtype=tf.float32, shape=[self.total_classes]) for i in range(num_tasks)] else: self.total_classes = int(self.y_.get_shape()[1]) self.train_phase = tf.placeholder(tf.bool, name='train_phase') if (imp_method == 'A-GEM' or imp_method == 'ER') and 'FC-' not in network_arch: # Only for Split-X setups self.output_mask = [tf.placeholder(dtype=tf.float32, shape=[self.total_classes]) for i in range(num_tasks)] self.mem_batch_size = tf.placeholder(dtype=tf.float32, shape=()) else: self.output_mask = tf.placeholder(dtype=tf.float32, shape=[self.total_classes]) self.sample_weights = tf.placeholder(tf.float32, shape=[None]) self.task_id = tf.placeholder(dtype=tf.int32, shape=()) self.store_grad_batches = tf.placeholder(dtype=tf.float32, shape=()) self.keep_prob = tf.placeholder(dtype=tf.float32, shape=()) self.train_samples = tf.placeholder(dtype=tf.float32, shape=()) self.training_iters = tf.placeholder(dtype=tf.float32, shape=()) self.train_step = tf.placeholder(dtype=tf.float32, shape=()) self.violation_count = tf.Variable(0, dtype=tf.float32, trainable=False) self.is_ATT_DATASET = is_ATT_DATASET # To use a different (standard one) ResNet-18 for CUB if x_test is not None: # If CUB datatset then use augmented x (x_train) for training and non-augmented x (x_test) for testing self.x = tf.cond(self.train_phase, lambda: tf.identity(x_train), lambda: tf.identity(x_test)) train_shape = x_train.get_shape().as_list() x = tf.reshape(self.x, [-1, train_shape[1], train_shape[2], train_shape[3]]) else: # We don't use data augmentation for other datasets self.x = x_train x = self.x # Class attributes for zero shot transfer self.class_attr = attr if self.class_attr is not None: self.attr_dims = int(self.class_attr.get_shape()[1]) # Save the arguments passed from the main script self.opt = opt self.num_tasks = num_tasks self.imp_method = imp_method self.fisher_update_after = fisher_update_after self.fisher_ema_decay = fisher_ema_decay self.network_arch = network_arch # A scalar variable for previous syanpse strength self.synap_stgth = tf.constant(synap_stgth, shape=[1], dtype=tf.float32) self.triplet_loss_scale = 2.1 # Define different variables self.weights_old = [] self.star_vars = [] self.small_omega_vars = [] self.big_omega_vars = [] self.big_omega_riemann_vars = [] self.fisher_diagonal_at_minima = [] self.hebbian_score_vars = [] self.running_fisher_vars = [] self.tmp_fisher_vars = [] self.max_fisher_vars = [] self.min_fisher_vars = [] self.max_score_vars = [] self.min_score_vars = [] self.normalized_score_vars = [] self.score_vars = [] self.normalized_fisher_at_minima_vars = [] self.weights_delta_old_vars = [] self.ref_grads = [] self.projected_gradients_list = [] if self.class_attr is not None: self.loss_and_train_ops_for_attr_vector(x, self.y_) else: self.loss_and_train_ops_for_one_hot_vector(x, self.y_) # Set the operations to reset the optimier when needed self.reset_optimizer_ops() #################################################################################### #### Internal APIs of the class. These should not be called/ exposed externally #### #################################################################################### def loss_and_train_ops_for_one_hot_vector(self, x, y_): """ Loss and training operations for the training of one-hot vector based classification model """ # Define approproate network if self.network_arch == 'FC-S': input_dim = int(x.get_shape()[1]) layer_dims = [input_dim, 256, 256, self.total_classes] if self.imp_method == 'PNN': self.task_logits = [] self.task_pruned_logits = [] self.unweighted_entropy = [] for i in range(self.num_tasks): if i == 0: self.task_logits.append(self.init_fc_column_progNN(layer_dims, x)) self.task_pruned_logits.append(tf.where(tf.tile(tf.equal(self.output_mask[i][None,:], 1.0), [tf.shape(self.task_logits[i])[0], 1]), self.task_logits[i], NEG_INF*tf.ones_like(self.task_logits[i]))) self.unweighted_entropy.append(tf.squeeze(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_[i], logits=self.task_pruned_logits[i])))) # mult by mean(y_[i]) puts unwaranted loss to 0 else: self.task_logits.append(self.extensible_fc_column_progNN(layer_dims, x, i)) self.task_pruned_logits.append(tf.where(tf.tile(tf.equal(self.output_mask[i][None,:], 1.0), [tf.shape(self.task_logits[i])[0], 1]), self.task_logits[i], NEG_INF*tf.ones_like(self.task_logits[i]))) self.unweighted_entropy.append(tf.squeeze(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_[i], logits=self.task_pruned_logits[i])))) # mult by mean(y_[i]) puts unwaranted loss to 0 else: self.fc_variables(layer_dims) logits = self.fc_feedforward(x, self.weights, self.biases) elif self.network_arch == 'FC-B': input_dim = int(x.get_shape()[1]) layer_dims = [input_dim, 2000, 2000, self.total_classes] self.fc_variables(layer_dims) logits = self.fc_feedforward(x, self.weights, self.biases) elif self.network_arch == 'CNN': num_channels = int(x.get_shape()[-1]) self.image_size = int(x.get_shape()[1]) kernels = [3, 3, 3, 3, 3] depth = [num_channels, 32, 32, 64, 64, 512] self.conv_variables(kernels, depth) logits = self.conv_feedforward(x, self.weights, self.biases, apply_dropout=True) elif self.network_arch == 'VGG': # VGG-16 logits = self.vgg_16_conv_feedforward(x) elif 'RESNET-' in self.network_arch: if self.network_arch == 'RESNET-S': # Same resnet-18 as used in GEM paper kernels = [3, 3, 3, 3, 3] filters = [20, 20, 40, 80, 160] strides = [1, 0, 2, 2, 2] elif self.network_arch == 'RESNET-B': # Standard ResNet-18 kernels = [7, 3, 3, 3, 3] filters = [64, 64, 128, 256, 512] strides = [2, 0, 2, 2, 2] if self.imp_method == 'PNN': self.task_logits = [] self.task_pruned_logits = [] self.unweighted_entropy = [] for i in range(self.num_tasks): if i == 0: self.task_logits.append(self.init_resent_column_progNN(x, kernels, filters, strides)) else: self.task_logits.append(self.extensible_resnet_column_progNN(x, kernels, filters, strides, i)) self.task_pruned_logits.append(tf.where(tf.tile(tf.equal(self.output_mask[i][None,:], 1.0), [tf.shape(self.task_logits[i])[0], 1]), self.task_logits[i], NEG_INF*tf.ones_like(self.task_logits[i]))) self.unweighted_entropy.append(tf.squeeze(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_[i], logits=self.task_pruned_logits[i])))) elif self.imp_method == 'A-GEM' or self.imp_method == 'ER': logits = self.resnet18_conv_feedforward(x, kernels, filters, strides) self.task_pruned_logits = [] self.unweighted_entropy = [] for i in range(self.num_tasks): self.task_pruned_logits.append(tf.where(tf.tile(tf.equal(self.output_mask[i][None,:], 1.0), [tf.shape(logits)[0], 1]), logits, NEG_INF*tf.ones_like(logits))) cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=self.task_pruned_logits[i]) adjusted_entropy = tf.reduce_sum(tf.cast(tf.tile(tf.equal(self.output_mask[i][None,:], 1.0), [tf.shape(y_)[0], 1]), dtype=tf.float32) * y_, axis=1) * cross_entropy self.unweighted_entropy.append(tf.reduce_sum(adjusted_entropy)) # We will average it later on else: logits = self.resnet18_conv_feedforward(x, kernels, filters, strides) # Prune the predictions to only include the classes for which # the training data is present if (self.imp_method != 'PNN') and ((self.imp_method != 'A-GEM' and self.imp_method != 'ER') or 'FC-' in self.network_arch): self.pruned_logits = tf.where(tf.tile(tf.equal(self.output_mask[None,:], 1.0), [tf.shape(logits)[0], 1]), logits, NEG_INF*tf.ones_like(logits)) # Create list of variables for storing different measures # Note: This method has to be called before calculating fisher # or any other importance measure self.init_vars() # Different entropy measures/ loss definitions if (self.imp_method != 'PNN') and ((self.imp_method != 'A-GEM' and self.imp_method != 'ER') or 'FC-' in self.network_arch): self.mse = 2.0*tf.nn.l2_loss(self.pruned_logits) # tf.nn.l2_loss computes sum(T**2)/ 2 self.weighted_entropy = tf.reduce_mean(tf.losses.softmax_cross_entropy(y_, self.pruned_logits, self.sample_weights, reduction=tf.losses.Reduction.NONE)) self.unweighted_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=self.pruned_logits)) # Create operations for loss and gradient calculation self.loss_and_gradients(self.imp_method) if self.imp_method != 'PNN': # Store the current weights before doing a train step self.get_current_weights() # For GEM variants train ops will be defined later if 'GEM' not in self.imp_method: # Define the training operation here as Pathint ops depend on the train ops self.train_op() # Create operations to compute importance depending on the importance methods if self.imp_method == 'EWC': self.create_fisher_ops() elif self.imp_method == 'M-EWC': self.create_fisher_ops() self.create_pathint_ops() self.combined_fisher_pathint_ops() elif self.imp_method == 'PI': self.create_pathint_ops() elif self.imp_method == 'RWALK': self.create_fisher_ops() self.create_pathint_ops() elif self.imp_method == 'MAS': self.create_hebbian_ops() elif self.imp_method == 'A-GEM' or self.imp_method == 'S-GEM': self.create_stochastic_gem_ops() if self.imp_method != 'PNN': # Create weight save and store ops self.weights_store_ops() # Summary operations for visualization tf.summary.scalar("unweighted_entropy", self.unweighted_entropy) for v in self.trainable_vars: tf.summary.histogram(v.name.replace(":", "_"), v) self.merged_summary = tf.summary.merge_all() # Accuracy measure if (self.imp_method == 'PNN') or ((self.imp_method == 'A-GEM' or self.imp_method == 'ER') and 'FC-' not in self.network_arch): self.correct_predictions = [] self.accuracy = [] for i in range(self.num_tasks): if self.imp_method == 'PNN': self.correct_predictions.append(tf.equal(tf.argmax(self.task_pruned_logits[i], 1), tf.argmax(y_[i], 1))) else: self.correct_predictions.append(tf.equal(tf.argmax(self.task_pruned_logits[i], 1), tf.argmax(y_, 1))) self.accuracy.append(tf.reduce_mean(tf.cast(self.correct_predictions[i], tf.float32))) else: self.correct_predictions = tf.equal(tf.argmax(self.pruned_logits, 1), tf.argmax(y_, 1)) self.accuracy = tf.reduce_mean(tf.cast(self.correct_predictions, tf.float32)) def loss_and_train_ops_for_attr_vector(self, x, y_): """ Loss and training operations for the training of joined embedding model """ # Define approproate network if self.network_arch == 'FC-S': input_dim = int(x.get_shape()[1]) layer_dims = [input_dim, 256, 256, self.total_classes] self.fc_variables(layer_dims) logits = self.fc_feedforward(x, self.weights, self.biases) elif self.network_arch == 'FC-B': input_dim = int(x.get_shape()[1]) layer_dims = [input_dim, 2000, 2000, self.total_classes] self.fc_variables(layer_dims) logits = self.fc_feedforward(x, self.weights, self.biases) elif self.network_arch == 'CNN': num_channels = int(x.get_shape()[-1]) self.image_size = int(x.get_shape()[1]) kernels = [3, 3, 3, 3, 3] depth = [num_channels, 32, 32, 64, 64, 512] self.conv_variables(kernels, depth) logits = self.conv_feedforward(x, self.weights, self.biases, apply_dropout=True) elif self.network_arch == 'VGG': # VGG-16 phi_x = self.vgg_16_conv_feedforward(x) elif self.network_arch == 'RESNET-S': # Standard ResNet-18 kernels = [3, 3, 3, 3, 3] filters = [20, 20, 40, 80, 160] strides = [1, 0, 2, 2, 2] # Get the image features phi_x = self.resnet18_conv_feedforward(x, kernels, filters, strides) elif self.network_arch == 'RESNET-B': # Standard ResNet-18 kernels = [7, 3, 3, 3, 3] filters = [64, 64, 128, 256, 512] strides = [2, 0, 2, 2, 2] # Get the image features phi_x = self.resnet18_conv_feedforward(x, kernels, filters, strides) # Get the attributes embedding attr_embed = self.get_attribute_embedding(self.class_attr) # Does not contain biases yet, Dimension: TOTAL_CLASSES x image_feature_dim # Add the biases now last_layer_biases = bias_variable([self.total_classes], name='attr_embed_b') self.trainable_vars.append(last_layer_biases) # Now that we have all the trainable variables, initialize the different book keeping variables # Note: This method has to be called before calculating fisher # or any other importance measure self.init_vars() # Compute the logits for the ZST case zst_logits = tf.matmul(phi_x, tf.transpose(attr_embed)) + last_layer_biases # Prune the predictions to only include the classes for which # the training data is present if self.imp_method == 'A-GEM': pruned_zst_logits = [] self.unweighted_entropy = [] for i in range(self.num_tasks): pruned_zst_logits.append(tf.where(tf.tile(tf.equal(self.output_mask[i][None,:], 1.0), [tf.shape(zst_logits)[0], 1]), zst_logits, NEG_INF*tf.ones_like(zst_logits))) cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=pruned_zst_logits[i]) adjusted_entropy = tf.reduce_sum(tf.cast(tf.tile(tf.equal(self.output_mask[i][None,:], 1.0), [tf.shape(y_)[0], 1]), dtype=tf.float32) * y_, axis=1) * cross_entropy self.unweighted_entropy.append(tf.reduce_sum(adjusted_entropy)) else: pruned_zst_logits = tf.where(tf.tile(tf.equal(self.output_mask[None,:], 1.0), [tf.shape(zst_logits)[0], 1]), zst_logits, NEG_INF*tf.ones_like(zst_logits)) self.unweighted_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=pruned_zst_logits)) self.mse = 2.0*tf.nn.l2_loss(pruned_zst_logits) # tf.nn.l2_loss computes sum(T**2)/ 2 # Create operations for loss and gradient calculation self.loss_and_gradients(self.imp_method) # Store the current weights before doing a train step self.get_current_weights() if 'GEM' not in self.imp_method: self.train_op() # Create operations to compute importance depending on the importance methods if self.imp_method == 'EWC': self.create_fisher_ops() elif self.imp_method == 'M-EWC': self.create_fisher_ops() self.create_pathint_ops() self.combined_fisher_pathint_ops() elif self.imp_method == 'PI': self.create_pathint_ops() elif self.imp_method == 'RWALK': self.create_fisher_ops() self.create_pathint_ops() elif self.imp_method == 'MAS': self.create_hebbian_ops() elif (self.imp_method == 'A-GEM') or (self.imp_method == 'S-GEM'): self.create_stochastic_gem_ops() # Create weight save and store ops self.weights_store_ops() # Summary operations for visualization tf.summary.scalar("triplet_loss", self.unweighted_entropy) for v in self.trainable_vars: tf.summary.histogram(v.name.replace(":", "_"), v) self.merged_summary = tf.summary.merge_all() # Accuracy measure if self.imp_method == 'A-GEM' and 'FC-' not in self.network_arch: self.correct_predictions = [] self.accuracy = [] for i in range(self.num_tasks): self.correct_predictions.append(tf.equal(tf.argmax(pruned_zst_logits[i], 1), tf.argmax(y_, 1))) self.accuracy.append(tf.reduce_mean(tf.cast(self.correct_predictions[i], tf.float32))) else: self.correct_predictions = tf.equal(tf.argmax(pruned_zst_logits, 1), tf.argmax(y_, 1)) self.accuracy = tf.reduce_mean(tf.cast(self.correct_predictions, tf.float32)) def init_fc_column_progNN(self, layer_dims, h, apply_dropout=False): """ Defines the first column of Progressive NN - FC Networks """ self.trainable_vars = [] self.h_pnn = [] self.trainable_vars.append([]) self.h_pnn.append([]) self.h_pnn[0].append(h) for i in range(len(layer_dims)-1): w = weight_variable([layer_dims[i], layer_dims[i+1]], name='fc_w_%d_t0'%(i)) b = bias_variable([layer_dims[i+1]], name='fc_b_%d_t0'%(i)) self.trainable_vars[0].append(w) self.trainable_vars[0].append(b) if i == len(layer_dims) - 2: # Last layer (logits) - don't apply the relu h = create_fc_layer(h, w, b, apply_relu=False) else: h = create_fc_layer(h, w, b) if apply_dropout: h = tf.nn.dropout(h, 1) self.h_pnn[0].append(h) return h def extensible_fc_column_progNN(self, layer_dims, h, task, apply_dropout=False): """ Define the subsequent columns of the progressive NN - FC Networks """ self.trainable_vars.append([]) self.h_pnn.append([]) self.h_pnn[task].append(h) for i in range(len(layer_dims)-1): w = weight_variable([layer_dims[i], layer_dims[i+1]], name='fc_w_%d_t%d'%(i, task)) b = bias_variable([layer_dims[i+1]], name='fc_b_%d_t%d'%(i, task)) self.trainable_vars[task].append(w) self.trainable_vars[task].append(b) preactivation = create_fc_layer(h, w, b, apply_relu=False) for tt in range(task): U_w = weight_variable([layer_dims[i], layer_dims[i+1]], name='fc_uw_%d_t%d_tt%d'%(i, task, tt)) U_b = bias_variable([layer_dims[i+1]], name='fc_ub_%d_t%d_tt%d'%(i, task, tt)) self.trainable_vars[task].append(U_w) self.trainable_vars[task].append(U_b) preactivation += create_fc_layer(self.h_pnn[tt][i], U_w, U_b, apply_relu=False) if i == len(layer_dims) - 2: # Last layer (logits) - don't apply the relu h = preactivation else: # layer < last layer, apply relu h = tf.nn.relu(preactivation) if apply_dropout: h = tf.nn.dropout(h) self.h_pnn[task].append(h) return h def init_resent_column_progNN(self, x, kernels, filters, strides): """ Defines the first column of Progressive NN - ResNet-18 """ self.trainable_vars = [] self.h_pnn = [] self.trainable_vars.append([]) self.h_pnn.append([]) self.h_pnn[0].append(x) # Conv1 h = _conv(x, kernels[0], filters[0], strides[0], self.trainable_vars[0], name='conv_1_t0') h = _bn(h, self.trainable_vars[0], self.train_phase[0], name='bn_1_t0') h = tf.nn.relu(h) self.h_pnn[0].append(h) # Conv2_x h = _residual_block(h, self.trainable_vars[0], self.train_phase[0], name='conv2_1_t0') h = _residual_block(h, self.trainable_vars[0], self.train_phase[0], name='conv2_2_t0') self.h_pnn[0].append(h) # Conv3_x h = _residual_block_first(h, filters[2], strides[2], self.trainable_vars[0], self.train_phase[0], name='conv3_1_t0', is_ATT_DATASET=self.is_ATT_DATASET) h = _residual_block(h, self.trainable_vars[0], self.train_phase[0], name='conv3_2_t0') self.h_pnn[0].append(h) # Conv4_x h = _residual_block_first(h, filters[3], strides[3], self.trainable_vars[0], self.train_phase[0], name='conv4_1_t0', is_ATT_DATASET=self.is_ATT_DATASET) h = _residual_block(h, self.trainable_vars[0], self.train_phase[0], name='conv4_2_t0') self.h_pnn[0].append(h) # Conv5_x h = _residual_block_first(h, filters[4], strides[4], self.trainable_vars[0], self.train_phase[0], name='conv5_1_t0', is_ATT_DATASET=self.is_ATT_DATASET) h = _residual_block(h, self.trainable_vars[0], self.train_phase[0], name='conv5_2_t0') self.h_pnn[0].append(h) # Apply average pooling h = tf.reduce_mean(h, [1, 2]) if self.network_arch == 'RESNET-S': logits = _fc(h, self.total_classes, self.trainable_vars[0], name='fc_1_t0', is_cifar=True) else: logits = _fc(h, self.total_classes, self.trainable_vars[0], name='fc_1_t0') self.h_pnn[0].append(logits) return logits def extensible_resnet_column_progNN(self, x, kernels, filters, strides, task): """ Define the subsequent columns of the progressive NN - ResNet-18 """ self.trainable_vars.append([]) self.h_pnn.append([]) self.h_pnn[task].append(x) # Conv1 h = _conv(x, kernels[0], filters[0], strides[0], self.trainable_vars[task], name='conv_1_t%d'%(task)) h = _bn(h, self.trainable_vars[task], self.train_phase[task], name='bn_1_t%d'%(task)) # Add lateral connections for tt in range(task): U_w = weight_variable([1, 1, self.h_pnn[tt][0].get_shape().as_list()[-1], h.get_shape().as_list()[-1]], name='conv_1_w_t%d_tt%d'%(task, tt)) U_b = bias_variable([h.get_shape().as_list()[-1]], name='conv_1_b_t%d_tt%d'%(task, tt)) self.trainable_vars[task].append(U_w) self.trainable_vars[task].append(U_b) h += create_conv_layer(self.h_pnn[tt][0], U_w, U_b, apply_relu=False) h = tf.nn.relu(h) self.h_pnn[task].append(h) # Conv2_x h = _residual_block(h, self.trainable_vars[task], self.train_phase[task], name='conv2_1_t%d'%(task)) h = _residual_block(h, self.trainable_vars[task], self.train_phase[task], apply_relu=False, name='conv2_2_t%d'%(task)) # Add lateral connections for tt in range(task): U_w = weight_variable([1, 1, self.h_pnn[tt][1].get_shape().as_list()[-1], h.get_shape().as_list()[-1]], name='conv_2_w_t%d_tt%d'%(task, tt)) U_b = bias_variable([h.get_shape().as_list()[-1]], name='conv_2_b_t%d_tt%d'%(task, tt)) self.trainable_vars[task].append(U_w) self.trainable_vars[task].append(U_b) h += create_conv_layer(self.h_pnn[tt][1], U_w, U_b, apply_relu=False) h = tf.nn.relu(h) self.h_pnn[task].append(h) # Conv3_x h = _residual_block_first(h, filters[2], strides[2], self.trainable_vars[task], self.train_phase[task], name='conv3_1_t%d'%(task), is_ATT_DATASET=self.is_ATT_DATASET) h = _residual_block(h, self.trainable_vars[task], self.train_phase[task], apply_relu=False, name='conv3_2_t%d'%(task)) # Add lateral connections for tt in range(task): U_w = weight_variable([1, 1, self.h_pnn[tt][2].get_shape().as_list()[-1], h.get_shape().as_list()[-1]], name='conv_3_w_t%d_tt%d'%(task, tt)) U_b = bias_variable([h.get_shape().as_list()[-1]], name='conv_3_b_t%d_tt%d'%(task, tt)) self.trainable_vars[task].append(U_w) self.trainable_vars[task].append(U_b) h += create_conv_layer(self.h_pnn[tt][2], U_w, U_b, stride=strides[2], apply_relu=False) h = tf.nn.relu(h) self.h_pnn[task].append(h) # Conv4_x h = _residual_block_first(h, filters[3], strides[3], self.trainable_vars[task], self.train_phase[task], name='conv4_1_t%d'%(task), is_ATT_DATASET=self.is_ATT_DATASET) h = _residual_block(h, self.trainable_vars[task], self.train_phase[task], apply_relu=False, name='conv4_2_t%d'%(task)) # Add lateral connections for tt in range(task): U_w = weight_variable([1, 1, self.h_pnn[tt][3].get_shape().as_list()[-1], h.get_shape().as_list()[-1]], name='conv_4_w_t%d_tt%d'%(task, tt)) U_b = bias_variable([h.get_shape().as_list()[-1]], name='conv_4_b_t%d_tt%d'%(task, tt)) self.trainable_vars[task].append(U_w) self.trainable_vars[task].append(U_b) h += create_conv_layer(self.h_pnn[tt][3], U_w, U_b, stride=strides[3], apply_relu=False) h = tf.nn.relu(h) self.h_pnn[task].append(h) # Conv5_x h = _residual_block_first(h, filters[4], strides[4], self.trainable_vars[task], self.train_phase[task], name='conv5_1_t%d'%(task), is_ATT_DATASET=self.is_ATT_DATASET) h = _residual_block(h, self.trainable_vars[task], self.train_phase[task], apply_relu=False, name='conv5_2_t%d'%(task)) # Add lateral connections for tt in range(task): U_w = weight_variable([1, 1, self.h_pnn[tt][4].get_shape().as_list()[-1], h.get_shape().as_list()[-1]], name='conv_5_w_t%d_tt%d'%(task, tt)) U_b = bias_variable([h.get_shape().as_list()[-1]], name='conv_5_b_t%d_tt%d'%(task, tt)) self.trainable_vars[task].append(U_w) self.trainable_vars[task].append(U_b) h += create_conv_layer(self.h_pnn[tt][4], U_w, U_b, stride=strides[4], apply_relu=False) h = tf.nn.relu(h) self.h_pnn[task].append(h) # Apply average pooling h = tf.reduce_mean(h, [1, 2]) if self.network_arch == 'RESNET-S': logits = _fc(h, self.total_classes, self.trainable_vars[task], name='fc_1_t%d'%(task), is_cifar=True) else: logits = _fc(h, self.total_classes, self.trainable_vars[task], name='fc_1_t%d'%(task)) for tt in range(task): h_tt = tf.reduce_mean(self.h_pnn[tt][5], [1, 2]) U_w = weight_variable([h_tt.get_shape().as_list()[1], self.total_classes], name='fc_uw_1_t%d_tt%d'%(task, tt)) U_b = bias_variable([self.total_classes], name='fc_ub_1_t%d_tt%d'%(task, tt)) self.trainable_vars[task].append(U_w) self.trainable_vars[task].append(U_b) logits += create_fc_layer(h_tt, U_w, U_b, apply_relu=False) self.h_pnn[task].append(logits) return logits def fc_variables(self, layer_dims): """ Defines variables for a 3-layer fc network Args: Returns: """ self.weights = [] self.biases = [] self.trainable_vars = [] for i in range(len(layer_dims)-1): w = weight_variable([layer_dims[i], layer_dims[i+1]], name='fc_%d'%(i)) b = bias_variable([layer_dims[i+1]], name='fc_%d'%(i)) self.weights.append(w) self.biases.append(b) self.trainable_vars.append(w) self.trainable_vars.append(b) def fc_feedforward(self, h, weights, biases, apply_dropout=False): """ Forward pass through a fc network Args: h Input image (tensor) weights List of weights for a fc network biases List of biases for a fc network apply_dropout Whether to apply droupout (True/ False) Returns: Logits of a fc network """ if apply_dropout: h = tf.nn.dropout(h, 1) # Apply dropout on Input? for (w, b) in list(zip(weights, biases))[:-1]: h = create_fc_layer(h, w, b) if apply_dropout: h = tf.nn.dropout(h, 1) # Apply dropout on hidden layers? # Store image features self.features = h self.image_feature_dim = h.get_shape().as_list()[-1] return create_fc_layer(h, weights[-1], biases[-1], apply_relu=False) def conv_variables(self, kernel, depth): """ Defines variables of a 5xconv-1xFC convolutional network Args: Returns: """ self.weights = [] self.biases = [] self.trainable_vars = [] div_factor = 1 for i in range(len(kernel)): w = weight_variable([kernel[i], kernel[i], depth[i], depth[i+1]], name='conv_%d'%(i)) b = bias_variable([depth[i+1]], name='conv_%d'%(i)) self.weights.append(w) self.biases.append(b) self.trainable_vars.append(w) self.trainable_vars.append(b) # Since we maxpool after every two conv layers if ((i+1) % 2 == 0): div_factor *= 2 flat_units = (self.image_size // div_factor) * (self.image_size // div_factor) * depth[-1] w = weight_variable([flat_units, self.total_classes], name='fc_%d'%(i)) b = bias_variable([self.total_classes], name='fc_%d'%(i)) self.weights.append(w) self.biases.append(b) self.trainable_vars.append(w) self.trainable_vars.append(b) def conv_feedforward(self, h, weights, biases, apply_dropout=True): """ Forward pass through a convolutional network Args: h Input image (tensor) weights List of weights for a conv network biases List of biases for a conv network apply_dropout Whether to apply droupout (True/ False) Returns: Logits of a conv network """ for i, (w, b) in enumerate(list(zip(weights, biases))[:-1]): # Apply conv operation till the second last layer, which is a FC layer h = create_conv_layer(h, w, b) if ((i+1) % 2 == 0): # Apply max pool after every two conv layers h = tf.nn.max_pool(h, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # Apply dropout if apply_dropout: h = tf.nn.dropout(h, self.keep_prob) # Construct FC layers shape = h.get_shape().as_list() h = tf.reshape(h, [-1, shape[1] * shape[2] * shape[3]]) # Store image features self.features = h self.image_feature_dim = h.get_shape().as_list()[-1] return create_fc_layer(h, weights[-1], biases[-1], apply_relu=False) def vgg_16_conv_feedforward(self, h): """ Forward pass through a VGG 16 network Return: Logits of a VGG 16 network """ self.trainable_vars = [] # Conv1 h = vgg_conv_layer(h, 3, 64, 1, self.trainable_vars, name='conv1_1') h = vgg_conv_layer(h, 3, 64, 1, self.trainable_vars, name='conv1_2') h = tf.nn.max_pool(h, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool1') # Conv2 h = vgg_conv_layer(h, 3, 128, 1, self.trainable_vars, name='conv2_1') h = vgg_conv_layer(h, 3, 128, 1, self.trainable_vars, name='conv2_2') h = tf.nn.max_pool(h, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool2') # Conv3 h = vgg_conv_layer(h, 3, 256, 1, self.trainable_vars, name='conv3_1') h = vgg_conv_layer(h, 3, 256, 1, self.trainable_vars, name='conv3_2') h = vgg_conv_layer(h, 3, 256, 1, self.trainable_vars, name='conv3_3') h = tf.nn.max_pool(h, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool3') # Conv4 h = vgg_conv_layer(h, 3, 512, 1, self.trainable_vars, name='conv4_1') h = vgg_conv_layer(h, 3, 512, 1, self.trainable_vars, name='conv4_2') h = vgg_conv_layer(h, 3, 512, 1, self.trainable_vars, name='conv4_3') h = tf.nn.max_pool(h, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool4') # Conv5 h = vgg_conv_layer(h, 3, 512, 1, self.trainable_vars, name='conv5_1') h = vgg_conv_layer(h, 3, 512, 1, self.trainable_vars, name='conv5_2') h = vgg_conv_layer(h, 3, 512, 1, self.trainable_vars, name='conv5_3') h = tf.nn.max_pool(h, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool5') # FC layers shape = h.get_shape().as_list() h = tf.reshape(h, [-1, shape[1] * shape[2] * shape[3]]) # fc6 h = vgg_fc_layer(h, 4096, self.trainable_vars, apply_relu=True, name='fc6') # fc7 h = vgg_fc_layer(h, 4096, self.trainable_vars, apply_relu=True, name='fc7') # Store image features self.features = h self.image_feature_dim = h.get_shape().as_list()[-1] # fc8 if self.class_attr is not None: # Return the image features return h else: logits = vgg_fc_layer(h, self.total_classes, self.trainable_vars, apply_relu=False, name='fc8') return logits def resnet18_conv_feedforward(self, h, kernels, filters, strides): """ Forward pass through a ResNet-18 network Returns: Logits of a resnet-18 conv network """ self.trainable_vars = [] # Conv1 h = _conv(h, kernels[0], filters[0], strides[0], self.trainable_vars, name='conv_1') h = _bn(h, self.trainable_vars, self.train_phase, name='bn_1') h = tf.nn.relu(h) # Conv2_x h = _residual_block(h, self.trainable_vars, self.train_phase, name='conv2_1') h = _residual_block(h, self.trainable_vars, self.train_phase, name='conv2_2') # Conv3_x h = _residual_block_first(h, filters[2], strides[2], self.trainable_vars, self.train_phase, name='conv3_1', is_ATT_DATASET=self.is_ATT_DATASET) h = _residual_block(h, self.trainable_vars, self.train_phase, name='conv3_2') # Conv4_x h = _residual_block_first(h, filters[3], strides[3], self.trainable_vars, self.train_phase, name='conv4_1', is_ATT_DATASET=self.is_ATT_DATASET) h = _residual_block(h, self.trainable_vars, self.train_phase, name='conv4_2') # Conv5_x h = _residual_block_first(h, filters[4], strides[4], self.trainable_vars, self.train_phase, name='conv5_1', is_ATT_DATASET=self.is_ATT_DATASET) h = _residual_block(h, self.trainable_vars, self.train_phase, name='conv5_2') # Apply average pooling h = tf.reduce_mean(h, [1, 2]) # Store the feature mappings self.features = h self.image_feature_dim = h.get_shape().as_list()[-1] if self.class_attr is not None: # Return the image features return h else: if self.network_arch == 'RESNET-S': logits = _fc(h, self.total_classes, self.trainable_vars, name='fc_1', is_cifar=True) else: logits = _fc(h, self.total_classes, self.trainable_vars, name='fc_1') return logits def get_attribute_embedding(self, attr): """ Get attribute embedding using a simple FC network Returns: Embedding vector of k x ATTR_DIMS """ w = weight_variable([self.attr_dims, self.image_feature_dim], name='attr_embed_w') self.trainable_vars.append(w) # Return the inner product of attribute matrix and weight vector. return tf.matmul(attr, w) # Dimension should be TOTAL_CLASSES x image_feature_dim def loss_and_gradients(self, imp_method): """ Defines task based and surrogate losses and their gradients Args: Returns: """ reg = 0.0 if imp_method == 'VAN' or imp_method == 'PNN' or imp_method == 'ER' or 'GEM' in imp_method: pass elif imp_method == 'EWC' or imp_method == 'M-EWC': reg = tf.add_n([tf.reduce_sum(tf.square(w - w_star) * f) for w, w_star, f in zip(self.trainable_vars, self.star_vars, self.normalized_fisher_at_minima_vars)]) elif imp_method == 'PI': reg = tf.add_n([tf.reduce_sum(tf.square(w - w_star) * f) for w, w_star, f in zip(self.trainable_vars, self.star_vars, self.big_omega_vars)]) elif imp_method == 'MAS': reg = tf.add_n([tf.reduce_sum(tf.square(w - w_star) * f) for w, w_star, f in zip(self.trainable_vars, self.star_vars, self.hebbian_score_vars)]) elif imp_method == 'RWALK': reg = tf.add_n([tf.reduce_sum(tf.square(w - w_star) * (f + scr)) for w, w_star, f, scr in zip(self.trainable_vars, self.star_vars, self.normalized_fisher_at_minima_vars, self.normalized_score_vars)]) """ # ***** DON't USE THIS WITH MULTI-HEAD SETTING SINCE THIS WILL UPDATE ALL THE WEIGHTS ***** # If CNN arch, then use the weight decay if self.is_ATT_DATASET: self.unweighted_entropy += tf.add_n([0.0005 * tf.nn.l2_loss(v) for v in self.trainable_vars if 'weights' in v.name or 'kernel' in v.name]) """ if imp_method == 'PNN': # Compute the gradients of regularized loss self.reg_gradients_vars = [] for i in range(self.num_tasks): self.reg_gradients_vars.append([]) self.reg_gradients_vars[i] = self.opt.compute_gradients(self.unweighted_entropy[i], var_list=self.trainable_vars[i]) elif imp_method != 'A-GEM': # For A-GEM we will define the losses and gradients later on if imp_method == 'ER' and 'FC-' not in self.network_arch: self.reg_loss = tf.add_n([self.unweighted_entropy[i] for i in range(self.num_tasks)])/ self.mem_batch_size else: # Regularized training loss self.reg_loss = tf.squeeze(self.unweighted_entropy + self.synap_stgth * reg) # Compute the gradients of the vanilla loss self.vanilla_gradients_vars = self.opt.compute_gradients(self.unweighted_entropy, var_list=self.trainable_vars) # Compute the gradients of regularized loss self.reg_gradients_vars = self.opt.compute_gradients(self.reg_loss, var_list=self.trainable_vars) def train_op(self): """ Defines the training operation (a single step during training) Args: Returns: """ if self.imp_method == 'VAN' or self.imp_method == 'ER': # Define training operation self.train = self.opt.apply_gradients(self.reg_gradients_vars) elif self.imp_method == 'PNN': # Define training operation self.train = [self.opt.apply_gradients(self.reg_gradients_vars[i]) for i in range(self.num_tasks)] elif self.imp_method == 'FTR_EXT': # Define a training operation for the first and subsequent tasks self.train = self.opt.apply_gradients(self.reg_gradients_vars) self.train_classifier = self.opt.apply_gradients(self.reg_gradients_vars[-2:]) else: # Get the value of old weights first with tf.control_dependencies([self.weights_old_ops_grouped]): # Define a training operation self.train = self.opt.apply_gradients(self.reg_gradients_vars) def init_vars(self): """ Defines different variables that will be used for the weight consolidation Args: Returns: """ if self.imp_method == 'PNN': return for v in range(len(self.trainable_vars)): # List of variables for weight updates self.weights_old.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) self.weights_delta_old_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) self.star_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False, name=self.trainable_vars[v].name.rsplit(':')[0]+'_star')) # List of variables for pathint method self.small_omega_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) self.big_omega_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) self.big_omega_riemann_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) # List of variables to store fisher information self.fisher_diagonal_at_minima.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) self.normalized_fisher_at_minima_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False, dtype=tf.float32)) self.tmp_fisher_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) self.running_fisher_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) self.score_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) # New variables for conv setting for fisher and score normalization self.max_fisher_vars.append(tf.Variable(tf.zeros(1), dtype=tf.float32, trainable=False)) self.min_fisher_vars.append(tf.Variable(tf.zeros(1), dtype=tf.float32, trainable=False)) self.max_score_vars.append(tf.Variable(tf.zeros(1), dtype=tf.float32, trainable=False)) self.min_score_vars.append(tf.Variable(tf.zeros(1), dtype=tf.float32, trainable=False)) self.normalized_score_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) if self.imp_method == 'MAS': # List of variables to store hebbian information self.hebbian_score_vars.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) elif self.imp_method == 'A-GEM' or self.imp_method == 'S-GEM': self.ref_grads.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) self.projected_gradients_list.append(tf.Variable(tf.zeros(self.trainable_vars[v].get_shape()), trainable=False)) def get_current_weights(self): """ Get the values of current weights Note: These weights are different from star_vars as those store the weights after training for the last task. Args: Returns: """ weights_old_ops = [] weights_delta_old_ops = [] for v in range(len(self.trainable_vars)): weights_old_ops.append(tf.assign(self.weights_old[v], self.trainable_vars[v])) weights_delta_old_ops.append(tf.assign(self.weights_delta_old_vars[v], self.trainable_vars[v])) self.weights_old_ops_grouped = tf.group(*weights_old_ops) self.weights_delta_old_grouped = tf.group(*weights_delta_old_ops) def weights_store_ops(self): """ Defines weight restoration operations Args: Returns: """ restore_weights_ops = [] set_star_vars_ops = [] for v in range(len(self.trainable_vars)): restore_weights_ops.append(tf.assign(self.trainable_vars[v], self.star_vars[v])) set_star_vars_ops.append(tf.assign(self.star_vars[v], self.trainable_vars[v])) self.restore_weights = tf.group(*restore_weights_ops) self.set_star_vars = tf.group(*set_star_vars_ops) def reset_optimizer_ops(self): """ Defines operations to reset the optimizer Args: Returns: """ # Set the operation for resetting the optimizer self.optimizer_slots = [self.opt.get_slot(var, name) for name in self.opt.get_slot_names()\ for var in tf.global_variables() if self.opt.get_slot(var, name) is not None] self.slot_names = self.opt.get_slot_names() self.opt_init_op = tf.variables_initializer(self.optimizer_slots) def create_pathint_ops(self): """ Defines operations for path integral-based importance Args: Returns: """ reset_small_omega_ops = [] update_small_omega_ops = [] update_big_omega_ops = [] update_big_omega_riemann_ops = [] for v in range(len(self.trainable_vars)): # Make sure that the variables are updated before calculating delta(theta) with tf.control_dependencies([self.train]): update_small_omega_ops.append(tf.assign_add(self.small_omega_vars[v], -(self.vanilla_gradients_vars[v][0] * (self.trainable_vars[v] - self.weights_old[v])))) # Ops to reset the small omega reset_small_omega_ops.append(tf.assign(self.small_omega_vars[v], self.small_omega_vars[v]*0.0)) if self.imp_method == 'PI': # Update the big omegas at the end of the task using the Eucldeian distance update_big_omega_ops.append(tf.assign_add(self.big_omega_vars[v], tf.nn.relu(tf.div(self.small_omega_vars[v], (PARAM_XI_STEP + tf.square(self.trainable_vars[v] - self.star_vars[v])))))) elif self.imp_method == 'RWALK': # Update the big omegas after small intervals using distance in riemannian manifold (KL-divergence) update_big_omega_riemann_ops.append(tf.assign_add(self.big_omega_riemann_vars[v], tf.nn.relu(tf.div(self.small_omega_vars[v], (PARAM_XI_STEP + self.running_fisher_vars[v] * tf.square(self.trainable_vars[v] - self.weights_delta_old_vars[v])))))) self.update_small_omega = tf.group(*update_small_omega_ops) self.reset_small_omega = tf.group(*reset_small_omega_ops) if self.imp_method == 'PI': self.update_big_omega = tf.group(*update_big_omega_ops) elif self.imp_method == 'RWALK': self.update_big_omega_riemann = tf.group(*update_big_omega_riemann_ops) self.big_omega_riemann_reset = [tf.assign(tensor, tf.zeros_like(tensor)) for tensor in self.big_omega_riemann_vars] if self.imp_method == 'RWALK': # For the first task, scale the scores so that division does not have an effect self.scale_score = [tf.assign(s, s*2.0) for s in self.big_omega_riemann_vars] # To reduce the rigidity after each task the importance scores are averaged self.update_score = [tf.assign_add(scr, tf.div(tf.add(scr, riemm_omega), 2.0)) for scr, riemm_omega in zip(self.score_vars, self.big_omega_riemann_vars)] # Get the min and max in each layer of the scores self.get_max_score_vars = [tf.assign(var, tf.expand_dims(tf.squeeze(tf.reduce_max(scr, keepdims=True)), axis=0)) for var, scr in zip(self.max_score_vars, self.score_vars)] self.get_min_score_vars = [tf.assign(var, tf.expand_dims(tf.squeeze(tf.reduce_min(scr, keepdims=True)), axis=0)) for var, scr in zip(self.min_score_vars, self.score_vars)] self.max_score = tf.reduce_max(tf.convert_to_tensor(self.max_score_vars)) self.min_score = tf.reduce_min(tf.convert_to_tensor(self.min_score_vars)) with tf.control_dependencies([self.max_score, self.min_score]): self.normalize_scores = [tf.assign(tgt, (var - self.min_score)/ (self.max_score - self.min_score + EPSILON)) for tgt, var in zip(self.normalized_score_vars, self.score_vars)] # Sparsify all the layers except last layer sparsify_score_ops = [] for v in range(len(self.normalized_score_vars) - 2): sparsify_score_ops.append(tf.assign(self.normalized_score_vars[v], tf.nn.dropout(self.normalized_score_vars[v], self.keep_prob))) self.sparsify_scores = tf.group(*sparsify_score_ops) def create_fisher_ops(self): """ Defines the operations to compute online update of Fisher Args: Returns: """ ders = tf.gradients(self.unweighted_entropy, self.trainable_vars) fisher_ema_at_step_ops = [] fisher_accumulate_at_step_ops = [] # ops for running fisher self.set_tmp_fisher = [tf.assign_add(f, tf.square(d)) for f, d in zip(self.tmp_fisher_vars, ders)] # Initialize the running fisher to non-zero value self.set_initial_running_fisher = [tf.assign(r_f, s_f) for r_f, s_f in zip(self.running_fisher_vars, self.tmp_fisher_vars)] self.set_running_fisher = [tf.assign(f, (1 - self.fisher_ema_decay) * f + (1.0/ self.fisher_update_after) * self.fisher_ema_decay * tmp) for f, tmp in zip(self.running_fisher_vars, self.tmp_fisher_vars)] self.get_fisher_at_minima = [tf.assign(var, f) for var, f in zip(self.fisher_diagonal_at_minima, self.running_fisher_vars)] self.reset_tmp_fisher = [tf.assign(tensor, tf.zeros_like(tensor)) for tensor in self.tmp_fisher_vars] # Get the min and max in each layer of the Fisher self.get_max_fisher_vars = [tf.assign(var, tf.expand_dims(tf.squeeze(tf.reduce_max(scr, keepdims=True)), axis=0)) for var, scr in zip(self.max_fisher_vars, self.fisher_diagonal_at_minima)] self.get_min_fisher_vars = [tf.assign(var, tf.expand_dims(tf.squeeze(tf.reduce_min(scr, keepdims=True)), axis=0)) for var, scr in zip(self.min_fisher_vars, self.fisher_diagonal_at_minima)] self.max_fisher = tf.reduce_max(tf.convert_to_tensor(self.max_fisher_vars)) self.min_fisher = tf.reduce_min(tf.convert_to_tensor(self.min_fisher_vars)) with tf.control_dependencies([self.max_fisher, self.min_fisher]): self.normalize_fisher_at_minima = [tf.assign(tgt, (var - self.min_fisher)/ (self.max_fisher - self.min_fisher + EPSILON)) for tgt, var in zip(self.normalized_fisher_at_minima_vars, self.fisher_diagonal_at_minima)] self.clear_attr_embed_reg = tf.assign(self.normalized_fisher_at_minima_vars[-2], tf.zeros_like(self.normalized_fisher_at_minima_vars[-2])) # Sparsify all the layers except last layer sparsify_fisher_ops = [] for v in range(len(self.normalized_fisher_at_minima_vars) - 2): sparsify_fisher_ops.append(tf.assign(self.normalized_fisher_at_minima_vars[v], tf.nn.dropout(self.normalized_fisher_at_minima_vars[v], self.keep_prob))) self.sparsify_fisher = tf.group(*sparsify_fisher_ops) def combined_fisher_pathint_ops(self): """ Define the operations to refine Fisher information based on parameters convergence Args: Returns: """ #self.refine_fisher_at_minima = [tf.assign(f, f*(1.0/(s+1e-12))) for f, s in zip(self.fisher_diagonal_at_minima, self.small_omega_vars)] self.refine_fisher_at_minima = [tf.assign(f, f*tf.exp(-100.0*s)) for f, s in zip(self.fisher_diagonal_at_minima, self.small_omega_vars)] def create_hebbian_ops(self): """ Define operations for hebbian measure of importance (MAS) """ # Compute the gradients of mse loss self.mse_gradients = tf.gradients(self.mse, self.trainable_vars) #with tf.control_dependencies([self.mse_gradients]): # Keep on adding gradients to the omega self.accumulate_hebbian_scores = [tf.assign_add(omega, tf.abs(grad)) for omega, grad in zip(self.hebbian_score_vars, self.mse_gradients)] # Average across the total images self.average_hebbian_scores = [tf.assign(omega, omega*(1.0/self.train_samples)) for omega in self.hebbian_score_vars] # Reset the hebbian importance variables self.reset_hebbian_scores = [tf.assign(omega, tf.zeros_like(omega)) for omega in self.hebbian_score_vars] def create_stochastic_gem_ops(self): """ Define operations for Stochastic GEM """ if 'FC-' in self.network_arch or self.imp_method == 'S-GEM': self.agem_loss = self.unweighted_entropy else: self.agem_loss = tf.add_n([self.unweighted_entropy[i] for i in range(self.num_tasks)])/ self.mem_batch_size ref_grads = tf.gradients(self.agem_loss, self.trainable_vars) # Reference gradient for previous tasks self.store_ref_grads = [tf.assign(ref, grad) for ref, grad in zip(self.ref_grads, ref_grads)] flat_ref_grads = tf.concat([tf.reshape(grad, [-1]) for grad in self.ref_grads], 0) # Grandient on the current task task_grads = tf.gradients(self.agem_loss, self.trainable_vars) flat_task_grads = tf.concat([tf.reshape(grad, [-1]) for grad in task_grads], 0) with tf.control_dependencies([flat_task_grads]): dotp = tf.reduce_sum(tf.multiply(flat_task_grads, flat_ref_grads)) ref_mag = tf.reduce_sum(tf.multiply(flat_ref_grads, flat_ref_grads)) proj = flat_task_grads - ((dotp/ ref_mag) * flat_ref_grads) self.reset_violation_count = self.violation_count.assign(0) def increment_violation_count(): with tf.control_dependencies([tf.assign_add(self.violation_count, 1)]): return tf.identity(self.violation_count) self.violation_count = tf.cond(tf.greater_equal(dotp, 0), lambda: tf.identity(self.violation_count), increment_violation_count) projected_gradients = tf.cond(tf.greater_equal(dotp, 0), lambda: tf.identity(flat_task_grads), lambda: tf.identity(proj)) # Convert the flat projected gradient vector into a list offset = 0 store_proj_grad_ops = [] for v in self.projected_gradients_list: shape = v.get_shape() v_params = 1 for dim in shape: v_params *= dim.value store_proj_grad_ops.append(tf.assign(v, tf.reshape(projected_gradients[offset:offset+v_params], shape))) offset += v_params self.store_proj_grads = tf.group(*store_proj_grad_ops) # Define training operations for the tasks > 1 with tf.control_dependencies([self.store_proj_grads]): self.train_subseq_tasks = self.opt.apply_gradients(zip(self.projected_gradients_list, self.trainable_vars)) # Define training operations for the first task self.first_task_gradients_vars = self.opt.compute_gradients(self.agem_loss, var_list=self.trainable_vars) self.train_first_task = self.opt.apply_gradients(self.first_task_gradients_vars) ################################################################################# #### External APIs of the class. These will be called/ exposed externally ####### ################################################################################# def reset_optimizer(self, sess): """ Resets the optimizer state Args: sess TF session Returns: """ # Call the reset optimizer op sess.run(self.opt_init_op) def set_active_outputs(self, sess, labels): """ Set the mask for the labels seen so far Args: sess TF session labels Mask labels Returns: """ new_mask = np.zeros(self.total_classes) new_mask[labels] = 1.0 """ for l in labels: new_mask[l] = 1.0 """ sess.run(self.output_mask.assign(new_mask)) def init_updates(self, sess): """ Initialization updates Args: sess TF session Returns: """ # Set the star values to the initial weights, so that we can calculate # big_omegas reliably if self.imp_method != 'PNN': sess.run(self.set_star_vars) def task_updates(self, sess, task, train_x, train_labels, num_classes_per_task=10, class_attr=None, online_cross_val=False): """ Updates different variables when a task is completed Args: sess TF session task Task ID train_x Training images for the task train_labels Labels in the task class_attr Class attributes (only needed for ZST transfer) Returns: """ if self.imp_method == 'VAN' or self.imp_method == 'PNN': # We'll store the current parameters at the end of this function pass elif self.imp_method == 'EWC': # Get the fisher at the end of a task sess.run(self.get_fisher_at_minima) # Normalize the fisher sess.run([self.get_max_fisher_vars, self.get_min_fisher_vars]) sess.run([self.min_fisher, self.max_fisher, self.normalize_fisher_at_minima]) # Don't regularize over the attribute-embedding vectors #sess.run(self.clear_attr_embed_reg) # Reset the tmp fisher vars sess.run(self.reset_tmp_fisher) elif self.imp_method == 'M-EWC': # Get the fisher at the end of a task sess.run(self.get_fisher_at_minima) # Refine Fisher based on the convergence info sess.run(self.refine_fisher_at_minima) # Normalize the fisher sess.run([self.get_max_fisher_vars, self.get_min_fisher_vars]) sess.run([self.min_fisher, self.max_fisher, self.normalize_fisher_at_minima]) # Reset the tmp fisher vars sess.run(self.reset_tmp_fisher) # Reset the small_omega_vars sess.run(self.reset_small_omega) elif self.imp_method == 'PI': # Update big omega variables sess.run(self.update_big_omega) # Reset the small_omega_vars because big_omega_vars are updated before it sess.run(self.reset_small_omega) elif self.imp_method == 'RWALK': if task == 0: # If first task then scale by a factor of 2, so that subsequent averaging does not hurt sess.run(self.scale_score) # Get the updated importance score sess.run(self.update_score) # Normalize the scores sess.run([self.get_max_score_vars, self.get_min_score_vars]) sess.run([self.min_score, self.max_score, self.normalize_scores]) # Sparsify scores """ # TODO: Tmp remove this? kp = 0.8 + (task*0.5) if (kp > 1): kp = 1.0 """ #sess.run(self.sparsify_scores, feed_dict={self.keep_prob: kp}) # Get the fisher at the end of a task sess.run(self.get_fisher_at_minima) # Normalize fisher sess.run([self.get_max_fisher_vars, self.get_min_fisher_vars]) sess.run([self.min_fisher, self.max_fisher, self.normalize_fisher_at_minima]) # Sparsify fisher #sess.run(self.sparsify_fisher, feed_dict={self.keep_prob: kp}) # Store the weights sess.run(self.weights_delta_old_grouped) # Reset the small_omega_vars because big_omega_vars are updated before it sess.run(self.reset_small_omega) # Reset the big_omega_riemann because importance score is stored in the scores array sess.run(self.big_omega_riemann_reset) # Reset the tmp fisher vars sess.run(self.reset_tmp_fisher) elif self.imp_method == 'MAS': # zero out any previous values sess.run(self.reset_hebbian_scores) if self.class_attr is not None: # Define mask based on the class attributes masked_class_attrs = np.zeros_like(class_attr) masked_class_attrs[train_labels] = class_attr[train_labels] # Logits mask logit_mask = np.zeros(self.total_classes) logit_mask[train_labels] = 1.0 # Loop over the entire training dataset to compute the parameter importance batch_size = 10 num_samples = train_x.shape[0] for iters in range(num_samples// batch_size): offset = iters * batch_size if self.class_attr is not None: sess.run(self.accumulate_hebbian_scores, feed_dict={self.x: train_x[offset:offset+batch_size], self.keep_prob: 1.0, self.class_attr: masked_class_attrs, self.output_mask: logit_mask, self.train_phase: False}) else: sess.run(self.accumulate_hebbian_scores, feed_dict={self.x: train_x[offset:offset+batch_size], self.keep_prob: 1.0, self.output_mask: logit_mask, self.train_phase: False}) # Average the hebbian scores across the training examples sess.run(self.average_hebbian_scores, feed_dict={self.train_samples: num_samples}) # Store current weights self.init_updates(sess) def restore(self, sess): """ Restore the weights from the star variables Args: sess TF session Returns: """ sess.run(self.restore_weights)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os from setuptools import find_packages, setup REQUIRES = [ "matplotlib", "torch", "scipy", "SQLAlchemy==1.4.46", "dill", "pandas", "aepsych_client==0.3.0", "statsmodels", "ax-platform==0.3.1", "botorch==0.8.3", ] BENCHMARK_REQUIRES = ["tqdm", "pathos", "multiprocess"] DEV_REQUIRES = BENCHMARK_REQUIRES + [ "coverage", "flake8", "black", "numpy>=1.20", "sqlalchemy-stubs", # for mypy stubs "mypy", "parameterized", "scikit-learn", # used in unit tests ] VISUALIZER_REQUIRES = [ "voila==0.3.6", "ipywidgets==7.6.5", ] with open("README.md", "r") as fh: long_description = fh.read() with open(os.path.join("aepsych", "version.py"), "r") as fh: for line in fh.readlines(): if line.startswith("__version__"): version = line.split('"')[1] setup( name="aepsych", version=version, python_requires=">=3.8", packages=find_packages(), description="Adaptive experimetation for psychophysics", long_description=long_description, long_description_content_type="text/markdown", install_requires=REQUIRES, extras_require={ "dev": DEV_REQUIRES, "benchmark": BENCHMARK_REQUIRES, "visualizer": VISUALIZER_REQUIRES, }, entry_points={ "console_scripts": [ "aepsych_server = aepsych.server.server:main", "aepsych_database = aepsych.server.utils:main", ], }, )
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from os import path from setuptools import find_packages, setup this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, "Readme.md"), encoding="utf-8") as f: long_description = f.read() setup( name="aepsych_client", version="0.3.0", packages=find_packages(), long_description=long_description, long_description_content_type="text/markdown", )
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import json import unittest import uuid from unittest.mock import MagicMock, patch import torch from aepsych.acquisition import MCPosteriorVariance from aepsych.generators import OptimizeAcqfGenerator, SobolGenerator from aepsych.models import GPClassificationModel from aepsych.server import AEPsychServer from aepsych_client import AEPsychClient from torch import tensor class MockStrategy: def gen(self, num_points): self._count = self._count + num_points return torch.tensor([[0.0]]) class RemoteServerTestCase(unittest.TestCase): def setUp(self): database_path = "./{}.db".format(str(uuid.uuid4().hex)) self.s = AEPsychServer(database_path=database_path) self.client = AEPsychClient(connect=False) self.client._send_recv = MagicMock( wraps=lambda x: json.dumps(self.s.handle_request(x)) ) def tearDown(self): self.s.cleanup() # cleanup the db if self.s.db is not None: self.s.db.delete_db() @patch( "aepsych.strategy.Strategy.gen", new=MockStrategy.gen, ) def test_client(self): config_str = """ [common] lb = [0] ub = [1] parnames = [x] stimuli_per_trial = 1 outcome_types = [binary] strategy_names = [init_strat, opt_strat] acqf = MCPosteriorVariance model = GPClassificationModel [init_strat] min_asks = 1 generator = SobolGenerator min_total_outcome_occurrences = 0 [opt_strat] min_asks = 1 generator = OptimizeAcqfGenerator min_total_outcome_occurrences = 0 """ self.client.configure(config_str=config_str, config_name="first_config") self.assertEqual(self.s.strat_id, 0) self.assertEqual(self.s.strat.strat_list[0].min_asks, 1) self.assertEqual(self.s.strat.strat_list[1].min_asks, 1) self.assertIsInstance(self.s.strat.strat_list[0].generator, SobolGenerator) self.assertIsInstance( self.s.strat.strat_list[1].generator, OptimizeAcqfGenerator ) self.assertIsInstance(self.s.strat.strat_list[1].model, GPClassificationModel) self.assertEqual(self.s.strat.strat_list[1].generator.acqf, MCPosteriorVariance) response = self.client.ask() self.assertSetEqual(set(response["config"].keys()), {"x"}) self.assertEqual(len(response["config"]["x"]), 1) self.assertTrue(0 <= response["config"]["x"][0] <= 1) self.assertFalse(response["is_finished"]) self.assertEqual(self.s.strat._count, 1) self.client.tell(config={"x": [0]}, outcome=1) self.assertEqual(self.s._strats[0].x, tensor([[0.0]])) self.assertEqual(self.s._strats[0].y, tensor([[1.0]])) self.client.tell(config={"x": [0]}, outcome=1, model_data=False) self.assertEqual(self.s._strats[0].x, tensor([[0.0]])) self.assertEqual(self.s._strats[0].y, tensor([[1.0]])) response = self.client.ask() self.assertTrue(response["is_finished"]) self.client.configure(config_str=config_str, config_name="second_config") self.assertEqual(self.s.strat._count, 0) self.assertEqual(self.s.strat_id, 1) self.client.resume(config_name="first_config") self.assertEqual(self.s.strat_id, 0) self.client.resume(config_name="second_config") self.assertEqual(self.s.strat_id, 1) self.client.finalize() class LocalServerTestCase(RemoteServerTestCase): def setUp(self): database_path = "./{}.db".format(str(uuid.uuid4().hex)) self.s = AEPsychServer(database_path=database_path) self.client = AEPsychClient(server=self.s) def test_warns_ignored_args(self): with self.assertWarns(UserWarning): AEPsychClient(ip="0.0.0.0", port=5555, server=self.s) if __name__ == "__main__": unittest.main()
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import json import socket import warnings from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union if TYPE_CHECKING: from aepsych.server import AEPsychServer class ServerError(RuntimeError): pass class AEPsychClient: def __init__( self, ip: Optional[str] = None, port: Optional[int] = None, connect: bool = True, server: "AEPsychServer" = None, ) -> None: """Python client for AEPsych using built-in python sockets. By default it connects to a localhost server matching AEPsych defaults. Args: ip (str, optional): IP to connect to (default: localhost). port (str, optional): Port to connect on (default: 5555). connect (bool): Connect as part of init? Defaults to True. server (AEPsychServer, optional): An in-memory AEPsychServer object to connect to. If this is not None, the other arguments will be ignored. """ self.configs = [] self.config_names = {} self.server = server if server is not None and (ip is not None or port is not None): warnings.warn( "AEPsychClient will ignore ip and port since it was given a server object!", UserWarning, ) if server is None: ip = ip or "0.0.0.0" port = port or 5555 self.socket = socket.socket() if connect: self.connect(ip, port) def load_config_index(self) -> None: """Loads the config index when server is not None""" self.configs = [] for i in range(self.server.n_strats): self.configs.append(i) def connect(self, ip: str, port: int) -> None: """Connect to the server. Args: ip (str): IP to connect to. port (str): Port to connect on. """ addr = (ip, port) self.socket.connect(addr) def finalize(self) -> None: """Let the server know experiment is complete.""" request = {"message": "", "type": "exit"} self._send_recv(request) def _send_recv(self, message) -> str: if self.server is not None: return self.server.handle_request(message) message = bytes(json.dumps(message), encoding="utf-8") self.socket.send(message) response = self.socket.recv(4096).decode("utf-8") # TODO this is hacky but we don't consistencly return json # from the server so we can't check for a status if response[:12] == "server_error": error_message = response[13:] raise ServerError(error_message) return response def ask( self, num_points: int = 1 ) -> Union[Dict[str, List[float]], Dict[int, Dict[str, Any]]]: """Get next configuration from server. Args: num_points[int]: Number of points to return. Returns: Dict[int, Dict[str, Any]]: Next configuration(s) to evaluate. If using the legacy backend, this is formatted as a dictionary where keys are parameter names and values are lists of parameter values. If using the Ax backend, this is formatted as a dictionary of dictionaries where the outer keys are trial indices, the inner keys are parameter names, and the values are parameter values. """ request = {"message": {"num_points": num_points}, "type": "ask"} response = self._send_recv(request) if isinstance(response, str): response = json.loads(response) return response def tell_trial_by_index( self, trial_index: int, outcome: int, model_data: bool = True, **metadata: Dict[str, Any], ) -> None: """Update the server on a trial that already has a trial index, as provided by `ask`. Args: outcome (int): Outcome that was obtained. model_data (bool): If True, the data will be recorded in the db and included in the server's model. If False, the data will be recorded in the db, but will not be used by the model. Defaults to True. trial_index (int): The associated trial index of the config. metadata (optional kwargs) is passed to the extra_info field on the server. Raises: AssertionError if server failed to acknowledge the tell. """ request = { "type": "tell", "message": { "outcome": outcome, "model_data": model_data, "trial_index": trial_index, }, "extra_info": metadata, } self._send_recv(request) def tell( self, config: Dict[str, List[Any]], outcome: int, model_data: bool = True, **metadata: Dict[str, Any], ) -> None: """Update the server on a configuration that was executed. Use this method when using the legacy backend or for manually-generated trials without an associated trial_index when uding the Ax backend. Args: config (Dict[str, str]): Config that was evaluated. outcome (int): Outcome that was obtained. metadata (optional kwargs) is passed to the extra_info field on the server. model_data (bool): If True, the data will be recorded in the db and included in the server's model. If False, the data will be recorded in the db, but will not be used by the model. Defaults to True. Raises: AssertionError if server failed to acknowledge the tell. """ request = { "type": "tell", "message": { "config": config, "outcome": outcome, "model_data": model_data, }, "extra_info": metadata, } self._send_recv(request) def configure( self, config_path: str = None, config_str: str = None, config_name: str = None ) -> None: """Configure the server and prepare for data collection. Note that either config_path or config_str must be passed. Args: config_path (str, optional): Path to a config.ini. Defaults to None. config_str (str, optional): Config.ini encoded as a string. Defaults to None. config_name (str, optional): A name to assign to this config internally for convenience. Raises: AssertionError if neither config path nor config_str is passed. """ if config_path is not None: assert config_str is None, "if config_path is passed, don't pass config_str" with open(config_path, "r") as f: config_str = f.read() elif config_str is not None: assert ( config_path is None ), "if config_str is passed, don't pass config_path" request = { "type": "setup", "message": {"config_str": config_str}, } idx = int(self._send_recv(request)) self.configs.append(idx) if config_name is not None: self.config_names[config_name] = idx def resume(self, config_id: int = None, config_name: str = None): """Resume a previous config from this session. To access available configs, use client.configs or client.config_names Args: config_id (int, optional): ID of config to resume. config_name (str, optional): Name config to resume. Raises: AssertionError if name or ID does not exist, or if both name and ID are passed. """ if config_id is not None: assert config_name is None, "if config_id is passed, don't pass config_name" assert ( config_id in self.configs ), f"No strat with index {config_id} was created!" elif config_name is not None: assert config_id is None, "if config_name is passed, don't pass config_id" assert ( config_name in self.config_names.keys() ), f"{config_name} not known, know {self.config_names.keys()}!" config_id = self.config_names[config_name] request = { "type": "resume", "message": {"strat_id": config_id}, } self._send_recv(request) def __del___(self): self.finalize()
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from .client import AEPsychClient __all__ = ["AEPsychClient"]
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import abc import ast import configparser import json import warnings from types import ModuleType from typing import Any, ClassVar, Dict, List, Mapping, Optional, Sequence, TypeVar import botorch import gpytorch import numpy as np import torch from aepsych.version import __version__ _T = TypeVar("_T") class Config(configparser.ConfigParser): # names in these packages can be referred to by string name registered_names: ClassVar[Dict[str, object]] = {} def __init__( self, config_dict: Optional[Mapping[str, Any]] = None, config_fnames: Optional[Sequence[str]] = None, config_str: Optional[str] = None, ): """Initialize the AEPsych config object. This can be used to instantiate most objects in AEPsych by calling object.from_config(config). Args: config_dict (Mapping[str, str], optional): Mapping to build configuration from. Keys are section names, values are dictionaries with keys and values that should be present in the section. Defaults to None. config_fnames (Sequence[str], optional): List of INI filenames to load configuration from. Defaults to None. config_str (str, optional): String formatted as an INI file to load configuration from. Defaults to None. """ super().__init__( inline_comment_prefixes=("#"), empty_lines_in_values=False, default_section="common", interpolation=configparser.ExtendedInterpolation(), converters={ "list": self._str_to_list, "tensor": self._str_to_tensor, "obj": self._str_to_obj, "array": self._str_to_array, }, allow_no_value=True, ) self.update( config_dict=config_dict, config_fnames=config_fnames, config_str=config_str, ) def _get( self, section, conv, option, *, raw=False, vars=None, fallback=configparser._UNSET, **kwargs, ): """ Override configparser to: 1. Return from common if a section doesn't exist. This comes up any time we have a module fully configured from the common/default section. 2. Pass extra **kwargs to the converter. """ try: return conv( self.get( section=section, option=option, raw=raw, vars=vars, fallback=fallback, ), **kwargs, ) except configparser.NoSectionError: return conv( self.get( section="common", option=option, raw=raw, vars=vars, fallback=fallback, ), **kwargs, ) # Convert config into a dictionary (eliminate duplicates from defaulted 'common' section.) def to_dict(self, deduplicate=True): _dict = {} for section in self: _dict[section] = {} for setting in self[section]: if deduplicate and section != "common" and setting in self["common"]: continue _dict[section][setting] = self[section][setting] return _dict # Turn the metadata section into JSON. def jsonifyMetadata(self) -> str: configdict = self.to_dict() return json.dumps(configdict["metadata"]) # Turn the entire config into JSON format. def jsonifyAll(self) -> str: configdict = self.to_dict() return json.dumps(configdict) def update( self, config_dict: Mapping[str, str] = None, config_fnames: Sequence[str] = None, config_str: str = None, ): """Update this object with a new configuration. Args: config_dict (Mapping[str, str], optional): Mapping to build configuration from. Keys are section names, values are dictionaries with keys and values that should be present in the section. Defaults to None. config_fnames (Sequence[str], optional): List of INI filenames to load configuration from. Defaults to None. config_str (str, optional): String formatted as an INI file to load configuration from. Defaults to None. """ if config_dict is not None: self.read_dict(config_dict) if config_fnames is not None: read_ok = self.read(config_fnames) if len(read_ok) < 1: raise FileNotFoundError if config_str is not None: self.read_string(config_str) # Deprecation warning for "experiment" section if "experiment" in self: for i in self["experiment"]: self["common"][i] = self["experiment"][i] del self["experiment"] def _str_to_list(self, v: str, element_type: _T = float) -> List[_T]: if v[0] == "[" and v[-1] == "]": if v == "[]": # empty list return [] else: return [element_type(i.strip()) for i in v[1:-1].split(",")] else: return [v.strip()] def _str_to_array(self, v: str) -> np.ndarray: v = ast.literal_eval(v) return np.array(v, dtype=float) def _str_to_tensor(self, v: str) -> torch.Tensor: return torch.Tensor(self._str_to_list(v)) def _str_to_obj(self, v: str, fallback_type: _T = str, warn: bool = True) -> object: try: return self.registered_names[v] except KeyError: if warn: warnings.warn(f'No known object "{v}"!') return fallback_type(v) def __repr__(self): return f"Config at {hex(id(self))}: \n {str(self)}" @classmethod def register_module(cls: _T, module: ModuleType): """Register a module with Config so that objects in it can be referred to by their string name in config files. Args: module (ModuleType): Module to register. """ cls.registered_names.update( { name: getattr(module, name) for name in module.__all__ if not isinstance(getattr(module, name), ModuleType) } ) @classmethod def register_object(cls: _T, obj: object): """Register an object with Config so that it can be referred to by its string name in config files. Args: obj (object): Object to register. """ if obj.__name__ in cls.registered_names.keys(): warnings.warn( f"Registering {obj.__name__} but already" + f"have {cls.registered_names[obj.__name__]}" + "registered under that name!" ) cls.registered_names.update({obj.__name__: obj}) def get_section(self, section): sec = {} for setting in self[section]: if section != "common" and setting in self["common"]: continue sec[setting] = self[section][setting] return sec def __str__(self): _str = "" for section in self: sec = self.get_section(section) _str += f"[{section}]\n" for setting in sec: _str += f"{setting} = {self[section][setting]}\n" return _str def convert_to_latest(self): self.convert(self.version, __version__) def convert(self, from_version: str, to_version: str) -> None: """Converts a config from an older version to a newer version. Args: from_version (str): The version of the config to be converted. to_version (str): The version the config should be converted to. """ if from_version == "0.0": self["common"]["strategy_names"] = "[init_strat, opt_strat]" if "experiment" in self: for i in self["experiment"]: self["common"][i] = self["experiment"][i] bridge = self["common"]["modelbridge_cls"] n_sobol = self["SobolStrategy"]["n_trials"] n_opt = self["ModelWrapperStrategy"]["n_trials"] if bridge == "PairwiseProbitModelbridge": self["init_strat"] = { "generator": "PairwiseSobolGenerator", "min_asks": n_sobol, } self["opt_strat"] = { "generator": "PairwiseOptimizeAcqfGenerator", "model": "PairwiseProbitModel", "min_asks": n_opt, } if "PairwiseProbitModelbridge" in self: self["PairwiseOptimizeAcqfGenerator"] = self[ "PairwiseProbitModelbridge" ] if "PairwiseGP" in self: self["PairwiseProbitModel"] = self["PairwiseGP"] elif bridge == "MonotonicSingleProbitModelbridge": self["init_strat"] = { "generator": "SobolGenerator", "min_asks": n_sobol, } self["opt_strat"] = { "generator": "MonotonicRejectionGenerator", "model": "MonotonicRejectionGP", "min_asks": n_opt, } if "MonotonicSingleProbitModelbridge" in self: self["MonotonicRejectionGenerator"] = self[ "MonotonicSingleProbitModelbridge" ] elif bridge == "SingleProbitModelbridge": self["init_strat"] = { "generator": "SobolGenerator", "min_asks": n_sobol, } self["opt_strat"] = { "generator": "OptimizeAcqfGenerator", "model": "GPClassificationModel", "min_asks": n_opt, } if "SingleProbitModelbridge" in self: self["OptimizeAcqfGenerator"] = self["SingleProbitModelbridge"] else: raise NotImplementedError( f"Refactor for {bridge} has not been implemented!" ) if "ModelWrapperStrategy" in self: if "refit_every" in self["ModelWrapperStrategy"]: self["opt_strat"]["refit_every"] = self["ModelWrapperStrategy"][ "refit_every" ] del self["common"]["model"] if to_version == __version__: if self["common"]["outcome_type"] == "single_probit": self["common"]["stimuli_per_trial"] = "1" self["common"]["outcome_types"] = "[binary]" if self["common"]["outcome_type"] == "single_continuous": self["common"]["stimuli_per_trial"] = "1" self["common"]["outcome_types"] = "[continuous]" if self["common"]["outcome_type"] == "pairwise_probit": self["common"]["stimuli_per_trial"] = "2" self["common"]["outcome_types"] = "[binary]" del self["common"]["outcome_type"] @property def version(self) -> str: """Returns the version number of the config.""" # TODO: implement an explicit versioning system # Try to infer the version if "stimuli_per_trial" in self["common"] and "outcome_types" in self["common"]: return __version__ if "common" in self and "strategy_names" in self["common"]: return "0.1" elif ( "SobolStrategy" in self or "ModelWrapperStrategy" in self or "EpsilonGreedyModelWrapperStrategy" in self ): return "0.0" else: raise RuntimeError("Unrecognized config format!") class ConfigurableMixin(abc.ABC): @abc.abstractclassmethod def get_config_options(cls, config: Config, name: str) -> Dict[str, Any]: # noqa raise NotImplementedError( f"get_config_options hasn't been defined for {cls.__name__}!" ) @classmethod def from_config(cls, config: Config, name: Optional[str] = None): return cls(**cls.get_config_options(config, name)) Config.register_module(gpytorch.likelihoods) Config.register_module(gpytorch.kernels) Config.register_module(botorch.acquisition) Config.registered_names["None"] = None
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. __version__ = "0.4.0"
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import warnings from typing import Callable, Iterable, List, Optional, Union import matplotlib.pyplot as plt import numpy as np from aepsych.strategy import Strategy from aepsych.utils import get_lse_contour, get_lse_interval, make_scaled_sobol from scipy.stats import norm def plot_strat( strat: Strategy, ax: Optional[plt.Axes] = None, true_testfun: Optional[Callable] = None, cred_level: float = 0.95, target_level: Optional[float] = 0.75, xlabel: Optional[str] = None, ylabel: Optional[str] = None, yes_label: str = "Yes trial", no_label: str = "No trial", flipx: bool = False, logx: bool = False, gridsize: int = 30, title: str = "", save_path: Optional[str] = None, show: bool = True, include_legend: bool = True, include_colorbar: bool = True, ) -> None: """Creates a plot of a strategy, showing participants responses on each trial, the estimated response function and threshold, and optionally a ground truth response threshold. Args: strat (Strategy): Strategy object to be plotted. Must have a dimensionality of 2 or less. ax (plt.Axes, optional): Matplotlib axis to plot on (if None, creates a new axis). Default: None. true_testfun (Callable, optional): Ground truth response function. Should take a n_samples x n_parameters tensor as input and produce the response probability at each sample as output. Default: None. cred_level (float): Percentage of posterior mass around the mean to be shaded. Default: 0.95. target_level (float): Response probability to estimate the threshold of. Default: 0.75. xlabel (str): Label of the x-axis. Default: "Context (abstract)". ylabel (str): Label of the y-axis (if None, defaults to "Response Probability" for 1-d plots or "Intensity (Abstract)" for 2-d plots). Default: None. yes_label (str): Label of trials with response of 1. Default: "Yes trial". no_label (str): Label of trials with response of 0. Default: "No trial". flipx (bool): Whether the values of the x-axis should be flipped such that the min becomes the max and vice versa. (Only valid for 2-d plots.) Default: False. logx (bool): Whether the x-axis should be log-transformed. (Only valid for 2-d plots.) Default: False. gridsize (int): The number of points to sample each dimension at. Default: 30. title (str): Title of the plot. Default: ''. save_path (str, optional): File name to save the plot to. Default: None. show (bool): Whether the plot should be shown in an interactive window. Default: True. include_legend (bool): Whether to include the legend in the figure. Default: True. include_colorbar (bool): Whether to include the colorbar indicating the probability of "Yes" trials. Default: True. """ assert ( "binary" in strat.outcome_types ), f"Plotting not supported for outcome_type {strat.outcome_types[0]}" if target_level is not None and not hasattr(strat.model, "monotonic_idxs"): warnings.warn( "Threshold estimation may not be accurate for non-monotonic models." ) if ax is None: _, ax = plt.subplots() if xlabel is None: xlabel = "Context (abstract)" dim = strat.dim if dim == 1: if ylabel is None: ylabel = "Response Probability" _plot_strat_1d( strat, ax, true_testfun, cred_level, target_level, xlabel, ylabel, yes_label, no_label, gridsize, ) elif dim == 2: if ylabel is None: ylabel = "Intensity (abstract)" _plot_strat_2d( strat, ax, true_testfun, cred_level, target_level, xlabel, ylabel, yes_label, no_label, flipx, logx, gridsize, include_colorbar, ) elif dim == 3: raise RuntimeError("Use plot_strat_3d for 3d plots!") else: raise NotImplementedError("No plots for >3d!") ax.set_title(title) if include_legend: anchor = (1.4, 0.5) if include_colorbar and dim > 1 else (1, 0.5) plt.legend(loc="center left", bbox_to_anchor=anchor) if save_path is not None: plt.savefig(save_path, bbox_inches="tight") if show: plt.tight_layout() if include_legend or (include_colorbar and dim > 1): plt.subplots_adjust(left=0.1, bottom=0.25, top=0.75) plt.show() def _plot_strat_1d( strat: Strategy, ax: plt.Axes, true_testfun: Optional[Callable], cred_level: float, target_level: Optional[float], xlabel: str, ylabel: str, yes_label: str, no_label: str, gridsize: int, ): """Helper function for creating 1-d plots. See plot_strat for an explanation of the arguments.""" x, y = strat.x, strat.y assert x is not None and y is not None, "No data to plot!" grid = strat.model.dim_grid(gridsize=gridsize) samps = norm.cdf(strat.model.sample(grid, num_samples=10000).detach()) phimean = samps.mean(0) ax.plot(np.squeeze(grid), phimean) if cred_level is not None: upper = np.quantile(samps, cred_level, axis=0) lower = np.quantile(samps, 1 - cred_level, axis=0) ax.fill_between( np.squeeze(grid), lower, upper, alpha=0.3, hatch="///", edgecolor="gray", label=f"{cred_level*100:.0f}% posterior mass", ) if target_level is not None: from aepsych.utils import interpolate_monotonic threshold_samps = [ interpolate_monotonic( grid.squeeze().numpy(), s, target_level, strat.lb[0], strat.ub[0] ) for s in samps ] thresh_med = np.mean(threshold_samps) thresh_lower = np.quantile(threshold_samps, q=1 - cred_level) thresh_upper = np.quantile(threshold_samps, q=cred_level) ax.errorbar( thresh_med, target_level, xerr=np.r_[thresh_med - thresh_lower, thresh_upper - thresh_med][:, None], capsize=5, elinewidth=1, label=f"Est. {target_level*100:.0f}% threshold \n(with {cred_level*100:.0f}% posterior \nmass marked)", ) if true_testfun is not None: true_f = true_testfun(grid) ax.plot(grid, true_f.squeeze(), label="True function") if target_level is not None: true_thresh = interpolate_monotonic( grid.squeeze().numpy(), true_f.squeeze(), target_level, strat.lb[0], strat.ub[0], ) ax.plot( true_thresh, target_level, "o", label=f"True {target_level*100:.0f}% threshold", ) ax.scatter( x[y == 0, 0], np.zeros_like(x[y == 0, 0]), marker=3, color="r", label=no_label, ) ax.scatter( x[y == 1, 0], np.zeros_like(x[y == 1, 0]), marker=3, color="b", label=yes_label, ) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) return ax def _plot_strat_2d( strat: Strategy, ax: plt.Axes, true_testfun: Optional[Callable], cred_level: float, target_level: Optional[float], xlabel: str, ylabel: str, yes_label: str, no_label: str, flipx: bool, logx: bool, gridsize: int, include_colorbar: bool, ): """Helper function for creating 2-d plots. See plot_strat for an explanation of the arguments.""" x, y = strat.x, strat.y assert x is not None and y is not None, "No data to plot!" # make sure the model is fit well if we've been limiting fit time strat.model.fit(train_x=x, train_y=y, max_fit_time=None) grid = strat.model.dim_grid(gridsize=gridsize) fmean, _ = strat.model.predict(grid) phimean = norm.cdf(fmean.reshape(gridsize, gridsize).detach().numpy()).T extent = np.r_[strat.lb[0], strat.ub[0], strat.lb[1], strat.ub[1]] colormap = ax.imshow( phimean, aspect="auto", origin="lower", extent=extent, alpha=0.5 ) if flipx: extent = np.r_[strat.lb[0], strat.ub[0], strat.ub[1], strat.lb[1]] colormap = ax.imshow( phimean, aspect="auto", origin="upper", extent=extent, alpha=0.5 ) else: extent = np.r_[strat.lb[0], strat.ub[0], strat.lb[1], strat.ub[1]] colormap = ax.imshow( phimean, aspect="auto", origin="lower", extent=extent, alpha=0.5 ) # hacky relabel to be in logspace if logx: locs = np.arange(strat.lb[0], strat.ub[0]) ax.set_xticks(ticks=locs) ax.set_xticklabels(2.0**locs) ax.plot(x[y == 0, 0], x[y == 0, 1], "ro", alpha=0.7, label=no_label) ax.plot(x[y == 1, 0], x[y == 1, 1], "bo", alpha=0.7, label=yes_label) if target_level is not None: # plot threshold mono_grid = np.linspace(strat.lb[1], strat.ub[1], num=gridsize) context_grid = np.linspace(strat.lb[0], strat.ub[0], num=gridsize) thresh_75, lower, upper = get_lse_interval( model=strat.model, mono_grid=mono_grid, target_level=target_level, cred_level=cred_level, mono_dim=1, lb=mono_grid.min(), ub=mono_grid.max(), gridsize=gridsize, ) ax.plot( context_grid, thresh_75, label=f"Est. {target_level*100:.0f}% threshold \n(with {cred_level*100:.0f}% posterior \nmass shaded)", ) ax.fill_between( context_grid, lower, upper, alpha=0.3, hatch="///", edgecolor="gray" ) if true_testfun is not None: true_f = true_testfun(grid).reshape(gridsize, gridsize) true_thresh = get_lse_contour( true_f, mono_grid, level=target_level, lb=strat.lb[-1], ub=strat.ub[-1] ) ax.plot(context_grid, true_thresh, label="Ground truth threshold") ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if include_colorbar: colorbar = plt.colorbar(colormap, ax=ax) colorbar.set_label(f"Probability of {yes_label}") def plot_strat_3d( strat: Strategy, parnames: Optional[List[str]] = None, outcome_label: str = "Yes Trial", slice_dim: int = 0, slice_vals: Union[List[float], int] = 5, contour_levels: Optional[Union[Iterable[float], bool]] = None, probability_space: bool = False, gridsize: int = 30, extent_multiplier: Optional[List[float]] = None, save_path: Optional[str] = None, show: bool = True, ): """Creates a plot of a 2d slice of a 3D strategy, showing the estimated model or probability response and contours Args: strat (Strategy): Strategy object to be plotted. Must have a dimensionality of 3. parnames (str list): list of the parameter names outcome_label (str): The label of the outcome variable slice_dim (int): dimension to slice on dim_vals (list of floats or int): values to take slices; OR number of values to take even slices from contour_levels (iterable of floats or bool, optional): List contour values to plot. Default: None. If true, all integer levels. probability_space (bool): Whether to plot probability. Default: False gridsize (int): The number of points to sample each dimension at. Default: 30. extent_multiplier (list, optional): multipliers for each of the dimensions when plotting. Default:None save_path (str, optional): File name to save the plot to. Default: None. show (bool): Whether the plot should be shown in an interactive window. Default: True. """ assert strat.model is not None, "Cannot plot without a model!" contour_levels_list = contour_levels or [] if parnames is None: parnames = ["x1", "x2", "x3"] # Get global min/max for all slices if probability_space: vmax = 1 vmin = 0 if contour_levels is True: contour_levels_list = [0.75] else: d = make_scaled_sobol(strat.lb, strat.ub, 2000) post = strat.model.posterior(d) fmean = post.mean.squeeze().detach().numpy() vmax = np.max(fmean) vmin = np.min(fmean) if contour_levels is True: contour_levels_list = np.arange(np.ceil(vmin), vmax + 1) # slice_vals is either a list of values or an integer number of values to slice on if type(slice_vals) is int: slices = np.linspace(strat.lb[slice_dim], strat.ub[slice_dim], slice_vals) slices = np.around(slices, 4) elif type(slice_vals) is not list: raise TypeError("slice_vals must be either an integer or a list of values") else: slices = np.array(slice_vals) _, axs = plt.subplots(1, len(slices), constrained_layout=True, figsize=(20, 3)) for _i, dim_val in enumerate(slices): img = plot_slice( axs[_i], strat, parnames, slice_dim, dim_val, vmin, vmax, gridsize, contour_levels_list, probability_space, extent_multiplier, ) plt_parnames = np.delete(parnames, slice_dim) axs[0].set_ylabel(plt_parnames[1]) cbar = plt.colorbar(img, ax=axs[-1]) if probability_space: cbar.ax.set_ylabel(f"Probability of {outcome_label}") else: cbar.ax.set_ylabel(outcome_label) for clevel in contour_levels_list: # type: ignore cbar.ax.axhline(y=clevel, c="w") if save_path is not None: plt.savefig(save_path) if show: plt.show() def plot_slice( ax, strat, parnames, slice_dim, slice_val, vmin, vmax, gridsize=30, contour_levels=None, lse=False, extent_multiplier=None, ): """Creates a plot of a 2d slice of a 3D strategy, showing the estimated model or probability response and contours Args: strat (Strategy): Strategy object to be plotted. Must have a dimensionality of 3. ax (plt.Axes): Matplotlib axis to plot on parnames (str list): list of the parameter names slice_dim (int): dimension to slice on slice_vals (float): value to take the slice along that dimension vmin (float): global model minimum to use for plotting vmax (float): global model maximum to use for plotting gridsize (int): The number of points to sample each dimension at. Default: 30. contour_levels (int list): Contours to plot. Default: None lse (bool): Whether to plot probability. Default: False extent_multiplier (list, optional): multipliers for each of the dimensions when plotting. Default:None """ extent = np.c_[strat.lb, strat.ub].reshape(-1) x = strat.model.dim_grid(gridsize=gridsize, slice_dims={slice_dim: slice_val}) if lse: fmean, fvar = strat.predict(x) fmean = fmean.detach().numpy().reshape(gridsize, gridsize) fmean = norm.cdf(fmean) else: post = strat.model.posterior(x) fmean = post.mean.squeeze().detach().numpy().reshape(gridsize, gridsize) # optionally rescale extents to correct values if extent_multiplier is not None: extent_scaled = extent * np.repeat(extent_multiplier, 2) dim_val_scaled = slice_val * extent_multiplier[slice_dim] else: extent_scaled = extent dim_val_scaled = slice_val plt_extents = np.delete(extent_scaled, [slice_dim * 2, slice_dim * 2 + 1]) plt_parnames = np.delete(parnames, slice_dim) img = ax.imshow( fmean.T, extent=plt_extents, origin="lower", aspect="auto", vmin=vmin, vmax=vmax ) ax.set_title(parnames[slice_dim] + "=" + str(dim_val_scaled)) ax.set_xlabel(plt_parnames[0]) if len(contour_levels) > 0: ax.contour( fmean.T, contour_levels, colors="w", extent=plt_extents, origin="lower", aspect="auto", ) return img
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import sys from gpytorch.likelihoods import BernoulliLikelihood, GaussianLikelihood from . import acquisition, config, factory, generators, models, strategy, utils from .config import Config from .likelihoods import BernoulliObjectiveLikelihood from .models import GPClassificationModel from .strategy import SequentialStrategy, Strategy __all__ = [ # modules "acquisition", "config", "factory", "models", "strategy", "utils", "generators", # classes "GPClassificationModel", "Strategy", "SequentialStrategy", "BernoulliObjectiveLikelihood", "BernoulliLikelihood", "GaussianLikelihood", ] try: from . import benchmark __all__ += ["benchmark"] except ImportError: pass Config.register_module(sys.modules[__name__])
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import time import warnings from copy import copy from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union import numpy as np import torch from aepsych.config import Config, ConfigurableMixin from aepsych.generators.base import AEPsychGenerationStep, AEPsychGenerator from aepsych.generators.sobol_generator import AxSobolGenerator, SobolGenerator from aepsych.models.base import ModelProtocol from aepsych.utils import ( _process_bounds, get_objectives, get_parameters, make_scaled_sobol, ) from aepsych.utils_logging import getLogger from ax.core.base_trial import TrialStatus from ax.modelbridge.generation_strategy import GenerationStrategy from ax.plot.contour import interact_contour from ax.plot.slice import plot_slice from ax.service.ax_client import AxClient from ax.utils.notebook.plotting import render from botorch.exceptions.errors import ModelFittingError logger = getLogger() def ensure_model_is_fresh(f): def wrapper(self, *args, **kwargs): if self.can_fit and not self._model_is_fresh: starttime = time.time() if self._count % self.refit_every == 0 or self.refit_every == 1: logger.info("Starting fitting (no warm start)...") # don't warm start self.fit() else: logger.info("Starting fitting (warm start)...") # warm start self.update() logger.info(f"Fitting done, took {time.time()-starttime}") self._model_is_fresh = True return f(self, *args, **kwargs) return wrapper class Strategy(object): """Object that combines models and generators to generate points to sample.""" _n_eval_points: int = 1000 def __init__( self, generator: AEPsychGenerator, lb: Union[np.ndarray, torch.Tensor], ub: Union[np.ndarray, torch.Tensor], stimuli_per_trial: int, outcome_types: Sequence[Type[str]], dim: Optional[int] = None, min_total_tells: int = 0, min_asks: int = 0, model: Optional[ModelProtocol] = None, refit_every: int = 1, min_total_outcome_occurrences: int = 1, max_asks: Optional[int] = None, keep_most_recent: Optional[int] = None, min_post_range: Optional[float] = None, name: str = "", run_indefinitely: bool = False, ): """Initialize the strategy object. Args: generator (AEPsychGenerator): The generator object that determines how points are sampled. lb (Union[numpy.ndarray, torch.Tensor]): Lower bounds of the parameters. ub (Union[numpy.ndarray, torch.Tensor]): Upper bounds of the parameters. dim (int, optional): The number of dimensions in the parameter space. If None, it is inferred from the size of lb and ub. min_total_tells (int): The minimum number of total observations needed to complete this strategy. min_asks (int): The minimum number of points that should be generated from this strategy. model (ModelProtocol, optional): The AEPsych model of the data. refit_every (int): How often to refit the model from scratch. min_total_outcome_occurrences (int): The minimum number of total observations needed for each outcome before the strategy will finish. Defaults to 1 (i.e., for binary outcomes, there must be at least one "yes" trial and one "no" trial). max_asks (int, optional): The maximum number of trials to generate using this strategy. If None, there is no upper bound (default). keep_most_recent (int, optional): Experimental. The number of most recent data points that the model will be fitted on. This may be useful for discarding noisy data from trials early in the experiment that are not as informative as data collected from later trials. When None, the model is fitted on all data. min_post_range (float, optional): Experimental. The required difference between the posterior's minimum and maximum value in probablity space before the strategy will finish. Ignored if None (default). name (str): The name of the strategy. Defaults to the empty string. run_indefinitely (bool): If true, the strategy will run indefinitely until finish() is explicitly called. Other stopping criteria will be ignored. Defaults to False. """ self.is_finished = False if run_indefinitely: warnings.warn( f"Strategy {name} will run indefinitely until finish() is explicitly called. Other stopping criteria will be ignored." ) elif min_total_tells > 0 and min_asks > 0: warnings.warn( "Specifying both min_total_tells and min_asks > 0 may lead to unintended behavior." ) if model is not None: assert ( len(outcome_types) == model._num_outputs ), f"Strategy has {len(outcome_types)} outcomes, but model {type(model).__name__} supports {model._num_outputs}!" assert ( stimuli_per_trial == model.stimuli_per_trial ), f"Strategy has {stimuli_per_trial} stimuli_per_trial, but model {type(model).__name__} supports {model.stimuli_per_trial}!" if isinstance(model.outcome_type, str): assert ( len(outcome_types) == 1 and outcome_types[0] == model.outcome_type ), f"Strategy outcome types is {outcome_types} but model outcome type is {model.outcome_type}!" else: assert set(outcome_types) == set( model.outcome_type ), f"Strategy outcome types is {outcome_types} but model outcome type is {model.outcome_type}!" self.run_indefinitely = run_indefinitely self.lb, self.ub, self.dim = _process_bounds(lb, ub, dim) self.min_total_outcome_occurrences = min_total_outcome_occurrences self.max_asks = max_asks self.keep_most_recent = keep_most_recent self.min_post_range = min_post_range if self.min_post_range is not None: assert model is not None, "min_post_range must be None if model is None!" self.eval_grid = make_scaled_sobol( lb=self.lb, ub=self.ub, size=self._n_eval_points ) self.x = None self.y = None self.n = 0 self.min_asks = min_asks self._count = 0 self.min_total_tells = min_total_tells self.stimuli_per_trial = stimuli_per_trial self.outcome_types = outcome_types if self.stimuli_per_trial == 1: self.event_shape: Tuple[int, ...] = (self.dim,) if self.stimuli_per_trial == 2: self.event_shape = (self.dim, self.stimuli_per_trial) self.model = model self.refit_every = refit_every self._model_is_fresh = False self.generator = generator self.has_model = self.model is not None if self.generator._requires_model: assert self.model is not None, f"{self.generator} requires a model!" if self.min_asks == self.min_total_tells == 0: warnings.warn( "strategy.min_asks == strategy.min_total_tells == 0. This strategy will not generate any points!", UserWarning, ) self.name = name def normalize_inputs(self, x, y): """converts inputs into normalized format for this strategy Args: x (np.ndarray): training inputs y (np.ndarray): training outputs Returns: x (np.ndarray): training inputs, normalized y (np.ndarray): training outputs, normalized n (int): number of observations """ assert ( x.shape == self.event_shape or x.shape[1:] == self.event_shape ), f"x shape should be {self.event_shape} or batch x {self.event_shape}, instead got {x.shape}" if x.shape == self.event_shape: x = x[None, :] if self.x is None: x = np.r_[x] else: x = np.r_[self.x, x] if self.y is None: y = np.r_[y] else: y = np.r_[self.y, y] n = y.shape[0] return torch.Tensor(x), torch.Tensor(y), n # TODO: allow user to pass in generator options @ensure_model_is_fresh def gen(self, num_points: int = 1): """Query next point(s) to run by optimizing the acquisition function. Args: num_points (int, optional): Number of points to query. Defaults to 1. Other arguments are forwared to underlying model. Returns: np.ndarray: Next set of point(s) to evaluate, [num_points x dim]. """ self._count = self._count + num_points return self.generator.gen(num_points, self.model) @ensure_model_is_fresh def get_max(self, constraints=None): constraints = constraints or {} return self.model.get_max(constraints) @ensure_model_is_fresh def get_min(self, constraints=None): constraints = constraints or {} return self.model.get_min(constraints) @ensure_model_is_fresh def inv_query(self, y, constraints=None, probability_space=False): constraints = constraints or {} return self.model.inv_query(y, constraints, probability_space) @ensure_model_is_fresh def predict(self, x, probability_space=False): return self.model.predict(x=x, probability_space=probability_space) @ensure_model_is_fresh def get_jnd(self, *args, **kwargs): return self.model.get_jnd(*args, **kwargs) @ensure_model_is_fresh def sample(self, x, num_samples=None): return self.model.sample(x, num_samples=num_samples) def finish(self): self.is_finished = True @property def finished(self): if self.is_finished: return True if self.run_indefinitely: return False if hasattr(self.generator, "finished"): # defer to generator if possible return self.generator.finished if self.y is None: # always need some data before switching strats return False if self.max_asks is not None and self._count >= self.max_asks: return True if "binary" in self.outcome_types: n_yes_trials = (self.y == 1).sum() n_no_trials = (self.y == 0).sum() sufficient_outcomes = ( n_yes_trials >= self.min_total_outcome_occurrences and n_no_trials >= self.min_total_outcome_occurrences ) else: sufficient_outcomes = True if self.min_post_range is not None: fmean, _ = self.model.predict(self.eval_grid, probability_space=True) meets_post_range = (fmean.max() - fmean.min()) >= self.min_post_range else: meets_post_range = True finished = ( self._count >= self.min_asks and self.n >= self.min_total_tells and sufficient_outcomes and meets_post_range ) return finished @property def can_fit(self): return self.has_model and self.x is not None and self.y is not None @property def n_trials(self): warnings.warn( "'n_trials' is deprecated and will be removed in a future release. Specify 'min_asks' instead.", DeprecationWarning, ) return self.min_asks def add_data(self, x, y): self.x, self.y, self.n = self.normalize_inputs(x, y) self._model_is_fresh = False def fit(self): if self.can_fit: if self.keep_most_recent is not None: try: self.model.fit( self.x[-self.keep_most_recent :], self.y[-self.keep_most_recent :], ) except (ModelFittingError): logger.warning( "Failed to fit model! Predictions may not be accurate!" ) else: try: self.model.fit(self.x, self.y) except (ModelFittingError): logger.warning( "Failed to fit model! Predictions may not be accurate!" ) else: warnings.warn("Cannot fit: no model has been initialized!", RuntimeWarning) def update(self): if self.can_fit: if self.keep_most_recent is not None: try: self.model.update( self.x[-self.keep_most_recent :], self.y[-self.keep_most_recent :], ) except (ModelFittingError): logger.warning( "Failed to fit model! Predictions may not be accurate!" ) else: try: self.model.update(self.x, self.y) except (ModelFittingError): logger.warning( "Failed to fit model! Predictions may not be accurate!" ) else: warnings.warn("Cannot fit: no model has been initialized!", RuntimeWarning) @classmethod def from_config(cls, config: Config, name: str): lb = config.gettensor(name, "lb") ub = config.gettensor(name, "ub") dim = config.getint(name, "dim", fallback=None) stimuli_per_trial = config.getint(name, "stimuli_per_trial", fallback=1) outcome_types = config.getlist(name, "outcome_types", element_type=str) gen_cls = config.getobj(name, "generator", fallback=SobolGenerator) generator = gen_cls.from_config(config) model_cls = config.getobj(name, "model", fallback=None) if model_cls is not None: model = model_cls.from_config(config) else: model = None acqf_cls = config.getobj(name, "acqf", fallback=None) if acqf_cls is not None and hasattr(generator, "acqf"): if generator.acqf is None: generator.acqf = acqf_cls generator.acqf_kwargs = generator._get_acqf_options(acqf_cls, config) min_asks = config.getint(name, "min_asks", fallback=0) min_total_tells = config.getint(name, "min_total_tells", fallback=0) refit_every = config.getint(name, "refit_every", fallback=1) if model is not None and not generator._requires_model: if refit_every < min_asks: warnings.warn( f"Strategy '{name}' has refit_every < min_asks even though its generator does not require a model. Consider making refit_every = min_asks to speed up point generation.", UserWarning, ) keep_most_recent = config.getint(name, "keep_most_recent", fallback=None) min_total_outcome_occurrences = config.getint( name, "min_total_outcome_occurrences", fallback=1 if "binary" in outcome_types else 0, ) min_post_range = config.getfloat(name, "min_post_range", fallback=None) keep_most_recent = config.getint(name, "keep_most_recent", fallback=None) n_trials = config.getint(name, "n_trials", fallback=None) if n_trials is not None: warnings.warn( "'n_trials' is deprecated and will be removed in a future release. Specify 'min_asks' instead.", DeprecationWarning, ) min_asks = n_trials return cls( lb=lb, ub=ub, stimuli_per_trial=stimuli_per_trial, outcome_types=outcome_types, dim=dim, model=model, generator=generator, min_asks=min_asks, refit_every=refit_every, min_total_outcome_occurrences=min_total_outcome_occurrences, min_post_range=min_post_range, keep_most_recent=keep_most_recent, min_total_tells=min_total_tells, name=name, ) class SequentialStrategy(object): """Runs a sequence of strategies defined by its config All getter methods defer to the current strat Args: strat_list (list[Strategy]): TODO make this nicely typed / doc'd """ def __init__(self, strat_list: List[Strategy]): self.strat_list = strat_list self._strat_idx = 0 self._suggest_count = 0 @property def _strat(self): return self.strat_list[self._strat_idx] def __getattr__(self, name: str): # return current strategy's attr if it's not a container attr if "strat_list" not in vars(self): raise AttributeError("Have no strategies in container, what happened?") return getattr(self._strat, name) def _make_next_strat(self): if (self._strat_idx + 1) >= len(self.strat_list): warnings.warn( "Ran out of generators, staying on final generator!", RuntimeWarning ) return # populate new model with final data from last model assert ( self.x is not None and self.y is not None ), "Cannot initialize next strategy; no data has been given!" self.strat_list[self._strat_idx + 1].add_data(self.x, self.y) self._suggest_count = 0 self._strat_idx = self._strat_idx + 1 def gen(self, num_points: int = 1, **kwargs): if self._strat.finished: self._make_next_strat() self._suggest_count = self._suggest_count + num_points return self._strat.gen(num_points=num_points, **kwargs) def finish(self): self._strat.finish() @property def finished(self): return self._strat_idx == (len(self.strat_list) - 1) and self._strat.finished def add_data(self, x, y): self._strat.add_data(x, y) @classmethod def from_config(cls, config: Config): strat_names = config.getlist("common", "strategy_names", element_type=str) # ensure strat_names are unique assert len(strat_names) == len( set(strat_names) ), f"Strategy names {strat_names} are not all unique!" strats = [] for name in strat_names: strat = Strategy.from_config(config, str(name)) strats.append(strat) return cls(strat_list=strats) class AEPsychStrategy(ConfigurableMixin): is_finished = False def __init__(self, ax_client: AxClient): self.ax_client = ax_client self.ax_client.experiment.num_asks = 0 @classmethod def get_config_options(cls, config: Config, name: Optional[str] = None) -> Dict: # TODO: Fix the mypy errors strat_names: List[str] = config.getlist("common", "strategy_names", element_type=str) # type: ignore steps = [] for name in strat_names: generator = config.getobj(name, "generator", fallback=AxSobolGenerator) # type: ignore opts = generator.get_config_options(config, name) step = AEPsychGenerationStep(**opts) steps.append(step) # Add an extra step at the end that we can `ask` endlessly. final_step = copy(step) final_step.completion_criteria = [] steps.append(final_step) parameters = get_parameters(config) parameter_constraints = config.getlist( "common", "par_constraints", element_type=str, fallback=None ) objectives = get_objectives(config) seed = config.getint("common", "random_seed", fallback=None) strat = GenerationStrategy(steps=steps) ax_client = AxClient(strat, random_seed=seed) ax_client.create_experiment( name="experiment", parameters=parameters, parameter_constraints=parameter_constraints, objectives=objectives, ) return {"ax_client": ax_client} @property def finished(self) -> bool: if self.is_finished: return True self.strat._maybe_move_to_next_step() return len(self.strat._steps) == (self.strat.current_step.index + 1) def finish(self): self.is_finished = True def gen(self, num_points: int = 1): x, _ = self.ax_client.get_next_trials(max_trials=num_points) self.strat.experiment.num_asks += num_points return x def complete_new_trial(self, config, outcome): _, trial_index = self.ax_client.attach_trial(config) self.complete_existing_trial(trial_index, outcome) def complete_existing_trial(self, trial_index, outcome): self.ax_client.complete_trial(trial_index, outcome) @property def experiment(self): return self.ax_client.experiment @property def strat(self): return self.ax_client.generation_strategy @property def can_fit(self): return ( self.strat.model is not None and len(self.experiment.trial_indices_by_status[TrialStatus.COMPLETED]) > 0 ) def _warn_on_outcome_mismatch(self): ax_model = self.ax_client.generation_strategy.model aepsych_model = ax_model.model.surrogate.model if ( hasattr(aepsych_model, "outcome_type") and aepsych_model.outcome_type != "continuous" ): warnings.warn( "Cannot directly plot non-continuous outcomes. Plotting the latent function instead." ) def plot_contours( self, density: int = 50, slice_values: Optional[Dict[str, Any]] = None ): """Plot predictions for a 2-d slice of the parameter space. Args: density: Number of points along each parameter to evaluate predictions. slice_values: A dictionary {name: val} for the fixed values of the other parameters. If not provided, then the mean of numeric parameters or the mode of choice parameters will be used. """ assert ( len(self.experiment.parameters) > 1 ), "plot_contours requires at least 2 parameters! Use 'plot_slice' instead." ax_model = self.ax_client.generation_strategy.model self._warn_on_outcome_mismatch() render( interact_contour( model=ax_model, metric_name="objective", density=density, slice_values=slice_values, ) ) def plot_slice( self, param_name: str, density: int = 50, slice_values: Optional[Dict[str, Any]] = None, ): """Plot predictions for a 1-d slice of the parameter space. Args: param_name: Name of parameter that will be sliced density: Number of points along slice to evaluate predictions. slice_values: A dictionary {name: val} for the fixed values of the other parameters. If not provided, then the mean of numeric parameters or the mode of choice parameters will be used. """ self._warn_on_outcome_mismatch() ax_model = self.ax_client.generation_strategy.model render( plot_slice( model=ax_model, param_name=param_name, metric_name="objective", density=density, slice_values=slice_values, ) ) def get_pareto_optimal_parameters(self): return self.ax_client.get_pareto_optimal_parameters()
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import logging import logging.config import os logger = logging.getLogger() def getLogger(level=logging.INFO, log_path="logs") -> logging.Logger: my_format = "%(asctime)-15s [%(levelname)-7s] %(message)s" os.makedirs(log_path, exist_ok=True) logging_config = { "version": 1, "disable_existing_loggers": True, "formatters": {"standard": {"format": my_format}}, "handlers": { "default": { "level": level, "class": "logging.StreamHandler", "formatter": "standard", }, "file": { "class": "logging.FileHandler", "level": logging.DEBUG, "filename": f"{log_path}/bayes_opt_server.log", "formatter": "standard", }, }, "loggers": { "": {"handlers": ["default", "file"], "level": level, "propagate": False}, }, } logging.config.dictConfig(logging_config) return logger
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from collections.abc import Iterable from configparser import NoOptionError from typing import Dict, List, Mapping, Optional, Tuple import numpy as np import torch from ax.service.utils.instantiation import ObjectiveProperties from scipy.stats import norm from torch.quasirandom import SobolEngine def make_scaled_sobol(lb, ub, size, seed=None): lb, ub, ndim = _process_bounds(lb, ub, None) grid = SobolEngine(dimension=ndim, scramble=True, seed=seed).draw(size) # rescale from [0,1] to [lb, ub] grid = lb + (ub - lb) * grid return grid def promote_0d(x): if not isinstance(x, Iterable): return [x] return x def dim_grid( lower: torch.Tensor, upper: torch.Tensor, dim: int, gridsize: int = 30, slice_dims: Optional[Mapping[int, float]] = None, ) -> torch.Tensor: """Create a grid Create a grid based on lower, upper, and dim. Parameters ---------- - lower ('int') - lower bound - upper ('int') - upper bound - dim ('int) - dimension - gridsize ('int') - size for grid - slice_dims (Optional, dict) - values to use for slicing axes, as an {index:value} dict Returns ---------- grid : torch.FloatTensor Tensor """ slice_dims = slice_dims or {} lower, upper, _ = _process_bounds(lower, upper, None) mesh_vals = [] for i in range(dim): if i in slice_dims.keys(): mesh_vals.append(slice(slice_dims[i] - 1e-10, slice_dims[i] + 1e-10, 1)) else: mesh_vals.append(slice(lower[i].item(), upper[i].item(), gridsize * 1j)) return torch.Tensor(np.mgrid[mesh_vals].reshape(dim, -1).T) def _process_bounds(lb, ub, dim) -> Tuple[torch.Tensor, torch.Tensor, int]: """Helper function for ensuring bounds are correct shape and type.""" lb = promote_0d(lb) ub = promote_0d(ub) if not isinstance(lb, torch.Tensor): lb = torch.tensor(lb) if not isinstance(ub, torch.Tensor): ub = torch.tensor(ub) lb = lb.float() ub = ub.float() assert lb.shape[0] == ub.shape[0], "bounds should be of equal shape!" if dim is not None: if lb.shape[0] == 1: lb = lb.repeat(dim) ub = ub.repeat(dim) else: assert lb.shape[0] == dim, "dim does not match shape of bounds!" else: dim = lb.shape[0] for i, (l, u) in enumerate(zip(lb, ub)): assert ( l <= u ), f"Lower bound {l} is not less than or equal to upper bound {u} on dimension {i}!" return lb, ub, dim def interpolate_monotonic(x, y, z, min_x=-np.inf, max_x=np.inf): # Ben Letham's 1d interpolation code, assuming monotonicity. # basic idea is find the nearest two points to the LSE and # linearly interpolate between them (I think this is bisection # root-finding) idx = np.searchsorted(y, z) if idx == len(y): return float(max_x) elif idx == 0: return float(min_x) x0 = x[idx - 1] x1 = x[idx] y0 = y[idx - 1] y1 = y[idx] x_star = x0 + (x1 - x0) * (z - y0) / (y1 - y0) return x_star def get_lse_interval( model, mono_grid, target_level, cred_level=None, mono_dim=-1, n_samps=500, lb=-np.inf, ub=np.inf, gridsize=30, **kwargs, ): xgrid = torch.Tensor( np.mgrid[ [ slice(model.lb[i].item(), model.ub[i].item(), gridsize * 1j) for i in range(model.dim) ] ] .reshape(model.dim, -1) .T ) samps = model.sample(xgrid, num_samples=n_samps, **kwargs) samps = [s.reshape((gridsize,) * model.dim) for s in samps.detach().numpy()] contours = np.stack( [ get_lse_contour(norm.cdf(s), mono_grid, target_level, mono_dim, lb, ub) for s in samps ] ) if cred_level is None: return np.mean(contours, 0.5, axis=0) else: alpha = 1 - cred_level qlower = alpha / 2 qupper = 1 - alpha / 2 upper = np.quantile(contours, qupper, axis=0) lower = np.quantile(contours, qlower, axis=0) median = np.quantile(contours, 0.5, axis=0) return median, lower, upper def get_lse_contour(post_mean, mono_grid, level, mono_dim=-1, lb=-np.inf, ub=np.inf): return np.apply_along_axis( lambda p: interpolate_monotonic(mono_grid, p, level, lb, ub), mono_dim, post_mean, ) def get_jnd_1d(post_mean, mono_grid, df=1, mono_dim=-1, lb=-np.inf, ub=np.inf): interpolate_to = post_mean + df return ( np.array( [interpolate_monotonic(mono_grid, post_mean, ito) for ito in interpolate_to] ) - mono_grid ) def get_jnd_multid(post_mean, mono_grid, df=1, mono_dim=-1, lb=-np.inf, ub=np.inf): return np.apply_along_axis( lambda p: get_jnd_1d(p, mono_grid, df=df, mono_dim=mono_dim, lb=lb, ub=ub), mono_dim, post_mean, ) def _get_ax_parameters(config): range_parnames = config.getlist("common", "parnames", element_type=str, fallback=[]) lb = config.getlist("common", "lb", element_type=float, fallback=[]) ub = config.getlist("common", "ub", element_type=float, fallback=[]) assert ( len(range_parnames) == len(lb) == len(ub) ), f"Length of parnames ({range_parnames}), lb ({lb}), and ub ({ub}) don't match!" range_params = [ { "name": parname, "type": "range", "value_type": config.get(parname, "value_type", fallback="float"), "log_scale": config.getboolean(parname, "log_scale", fallback=False), "bounds": [l, u], } for parname, l, u in zip(range_parnames, lb, ub) ] choice_parnames = config.getlist( "common", "choice_parnames", element_type=str, fallback=[] ) choices = [ config.getlist(parname, "choices", element_type=str, fallback=["True", "False"]) for parname in choice_parnames ] choice_params = [ { "name": parname, "type": "choice", "value_type": config.get(parname, "value_type", fallback="str"), "is_ordered": config.getboolean(parname, "is_ordered", fallback=False), "values": choice, } for parname, choice in zip(choice_parnames, choices) ] fixed_parnames = config.getlist( "common", "fixed_parnames", element_type=str, fallback=[] ) values = [] for parname in fixed_parnames: try: try: value = config.getfloat(parname, "value") except ValueError: value = config.get(parname, "value") values.append(value) except NoOptionError: raise RuntimeError(f"Missing value for fixed parameter {parname}!") fixed_params = [ { "name": parname, "type": "fixed", "value": value, } for parname, value in zip(fixed_parnames, values) ] return range_params, choice_params, fixed_params def get_parameters(config) -> List[Dict]: range_params, choice_params, fixed_params = _get_ax_parameters(config) return range_params + choice_params + fixed_params def get_dim(config) -> int: range_params, choice_params, _ = _get_ax_parameters(config) # Need to sum dimensions added by both range and choice parameters dim = len(range_params) # 1 dim per range parameter for par in choice_params: if par["is_ordered"]: dim += 1 # Ordered choice params are encoded like continuous parameters elif len(par["values"]) > 2: dim += len( par["values"] ) # Choice parameter is one-hot encoded such that they add 1 dim for every choice else: dim += ( len(par["values"]) - 1 ) # Choice parameters with n_choices < 3 add n_choices - 1 dims return dim def get_objectives(config) -> Dict: outcome_types: List[str] = config.getlist( "common", "outcome_types", element_type=str ) if len(outcome_types) > 1: for out_type in outcome_types: assert ( out_type == "continuous" ), "Multiple outcomes is only currently supported for continuous outcomes!" outcome_names: List[str] = config.getlist( "common", "outcome_names", element_type=str, fallback=None ) if outcome_names is None: outcome_names = [f"outcome_{i+1}" for i in range(len(outcome_types))] objectives = {} for out_name in outcome_names: minimize = config.getboolean(out_name, "minimize", fallback=False) threshold = config.getfloat(out_name, "threshold", fallback=None) objectives[out_name] = ObjectiveProperties( minimize=minimize, threshold=threshold ) return objectives
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import itertools import time from random import shuffle from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union import numpy as np import pandas as pd import torch from aepsych.config import Config from aepsych.strategy import ensure_model_is_fresh, SequentialStrategy from tqdm.contrib.itertools import product as tproduct from .problem import Problem class Benchmark: """ Benchmark base class. This class wraps standard functionality for benchmarking models including generating cartesian products of run configurations, running the simulated experiment loop, and logging results. TODO make a benchmarking tutorial and link/refer to it here. """ def __init__( self, problems: List[Problem], configs: Mapping[str, Union[str, list]], seed: Optional[int] = None, n_reps: int = 1, log_every: Optional[int] = 10, ) -> None: """Initialize benchmark. Args: problems (List[Problem]): Problem objects containing the test function to evaluate. configs (Mapping[str, Union[str, list]]): Dictionary of configs to run. Lists at leaves are used to construct a cartesian product of configurations. seed (int, optional): Random seed to use for reproducible benchmarks. Defaults to randomized seeds. n_reps (int, optional): Number of repetitions to run of each configuration. Defaults to 1. log_every (int, optional): Logging interval during an experiment. Defaults to logging every 10 trials. """ self.problems = problems self.n_reps = n_reps self.combinations = self.make_benchmark_list(**configs) self._log: List[Dict[str, object]] = [] self.log_every = log_every # shuffle combinations so that intermediate results have a bit of everything shuffle(self.combinations) if seed is None: # explicit cast because int and np.int_ are different types self.seed = int(np.random.randint(0, 200)) else: self.seed = seed def make_benchmark_list(self, **bench_config) -> List[Dict[str, float]]: """Generate a list of benchmarks to run from configuration. This constructs a cartesian product of config dicts using lists at the leaves of the base config Returns: List[dict[str, float]]: List of dictionaries, each of which can be passed to aepsych.config.Config. """ # This could be a generator but then we couldn't # know how many params we have, tqdm wouldn't work, etc, # so we materialize the full list. def gen_combinations(d): keys, values = d.keys(), d.values() # only go cartesian on list leaves values = [v if type(v) == list else [v] for v in values] combinations = itertools.product(*values) return [dict(zip(keys, c)) for c in combinations] keys, values = bench_config.keys(), bench_config.values() return [ dict(zip(keys, c)) for c in itertools.product(*(gen_combinations(v) for v in values)) ] def materialize_config(self, config_dict): materialized_config = {} for key, value in config_dict.items(): materialized_config[key] = { k: v._evaluate(config_dict) if isinstance(v, DerivedValue) else v for k, v in value.items() } return materialized_config @property def num_benchmarks(self) -> int: """Return the total number of runs in this benchmark. Returns: int: Total number of runs in this benchmark. """ return len(self.problems) * len(self.combinations) * self.n_reps def make_strat_and_flatconfig( self, config_dict: Mapping[str, str] ) -> Tuple[SequentialStrategy, Dict[str, str]]: """From a config dict, generate a strategy (for running) and flattened config (for logging) Args: config_dict (Mapping[str, str]): A run configuration dictionary. Returns: Tuple[SequentialStrategy, Dict[str,str]]: A tuple containing a strategy object and a flat config. """ config = Config() config.update(config_dict=config_dict) strat = SequentialStrategy.from_config(config) flatconfig = self.flatten_config(config) return strat, flatconfig def run_experiment( self, problem: Problem, config_dict: Dict[str, Any], seed: int, rep: int, ) -> Tuple[List[Dict[str, Any]], Union[SequentialStrategy, None]]: """Run one simulated experiment. Args: config_dict (Dict[str, str]): AEPsych configuration to use. seed (int): Random seed for this run. rep (int): Index of this repetition. Returns: Tuple[List[Dict[str, object]], SequentialStrategy]: A tuple containing a log of the results and the strategy as of the end of the simulated experiment. This is ignored in large-scale benchmarks but useful for one-off visualization. """ torch.manual_seed(seed) np.random.seed(seed) config_dict["common"]["lb"] = str(problem.lb.tolist()) config_dict["common"]["ub"] = str(problem.ub.tolist()) config_dict["problem"] = problem.metadata materialized_config = self.materialize_config(config_dict) # no-op config is_invalid = materialized_config["common"].get("invalid_config", False) if is_invalid: return [{}], None strat, flatconfig = self.make_strat_and_flatconfig(materialized_config) problem_metadata = { f"problem_{key}": value for key, value in problem.metadata.items() } total_gentime = 0.0 total_fittime = 0.0 i = 0 results = [] while not strat.finished: starttime = time.time() next_x = strat.gen() gentime = time.time() - starttime total_gentime += gentime next_y = [problem.sample_y(next_x)] strat.add_data(next_x, next_y) # strat usually defers model fitting until it is needed # (e.g. for gen or predict) so that we don't refit # unnecessarily. But for benchmarking we want to time # fit and gen separately, so we force a strat update # so we can time fit vs gen. TODO make this less awkward starttime = time.time() ensure_model_is_fresh(lambda x: None)(strat._strat) fittime = time.time() - starttime total_fittime += fittime if (self.log_at(i) or strat.finished) and strat.has_model: metrics = problem.evaluate(strat) result = { "fit_time": fittime, "cum_fit_time": total_fittime, "gen_time": gentime, "cum_gen_time": total_gentime, "trial_id": i, "rep": rep, "seed": seed, "final": strat.finished, "strat_idx": strat._strat_idx, } result.update(problem_metadata) result.update(flatconfig) result.update(metrics) results.append(result) i = i + 1 return results, strat def run_benchmarks(self): """Run all the benchmarks, sequentially.""" for i, (rep, config, problem) in enumerate( tproduct(range(self.n_reps), self.combinations, self.problems) ): local_seed = i + self.seed results, _ = self.run_experiment(problem, config, seed=local_seed, rep=rep) if results != [{}]: self._log.extend(results) def flatten_config(self, config: Config) -> Dict[str, str]: """Flatten a config object for logging. Args: config (Config): AEPsych config object. Returns: Dict[str,str]: A flat dictionary (that can be used to build a flat pandas data frame). """ flatconfig = {} for s in config.sections(): flatconfig.update({f"{s}_{k}": v for k, v in config[s].items()}) return flatconfig def log_at(self, i: int) -> bool: """Check if we should log on this trial index. Args: i (int): Trial index to (maybe) log at. Returns: bool: True if this trial should be logged. """ if self.log_every is not None: return i % self.log_every == 0 else: return False def pandas(self) -> pd.DataFrame: return pd.DataFrame(self._log) class DerivedValue(object): """ A class for dynamically generating config values from other config values during benchmarking. """ def __init__(self, args: List[Tuple[str, str]], func: Callable) -> None: """Initialize DerivedValue. Args: args (List[Tuple[str]]): Each tuple in this list is a pair of strings that refer to keys in a nested dictionary. func (Callable): A function that accepts args as input. For example, consider the following: benchmark_config = { "common": { "model": ["GPClassificationModel", "FancyNewModelToBenchmark"], "acqf": "MCLevelSetEstimation" }, "init_strat": { "min_asks": [10, 20], "generator": "SobolGenerator" }, "opt_strat": { "generator": "OptimizeAcqfGenerator", "min_asks": DerivedValue( [("init_strat", "min_asks"), ("common", "model")], lambda x,y : 100 - x if y == "GPClassificationModel" else 50 - x) } } Four separate benchmarks would be generated from benchmark_config: 1. model = GPClassificationModel; init trials = 10; opt trials = 90 2. model = GPClassificationModel; init trials = 20; opt trials = 80 3. model = FancyNewModelToBenchmark; init trials = 10; opt trials = 40 4. model = FancyNewModelToBenchmark; init trials = 20; opt trials = 30 Note that if you can also access problem names into func by including ("problem", "name") in args. """ self.args = args self.func = func def _evaluate(self, benchmark_config: Dict) -> Any: """Fetches values of self.args from benchmark_config and evaluates self.func on them.""" _args = [benchmark_config[outer][inner] for outer, inner in self.args] return self.func(*_args)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import itertools import logging import time import traceback from copy import deepcopy from pathlib import Path from random import shuffle from typing import Any, Dict, List, Mapping, Optional, Tuple, Union import aepsych.utils_logging as utils_logging import multiprocess.context as ctx import numpy as np import pathos import torch from aepsych.benchmark import Benchmark from aepsych.benchmark.problem import Problem from aepsych.strategy import SequentialStrategy ctx._force_start_method("spawn") # fixes problems with CUDA and fork logger = utils_logging.getLogger(logging.INFO) class PathosBenchmark(Benchmark): """Benchmarking class for parallelized benchmarks using pathos""" def __init__(self, nproc: int = 1, *args, **kwargs): """Initialize pathos benchmark. Args: nproc (int, optional): Number of cores to use. Defaults to 1. """ super().__init__(*args, **kwargs) # parallelize over jobs, so each job should be 1 thread only num_threads = torch.get_num_threads() num_interopt_threads = torch.get_num_interop_threads() if num_threads > 1 or num_interopt_threads > 1: raise RuntimeError( "PathosBenchmark parallelizes over threads," + "and as such is incompatible with torch being threaded. " + "Please call `torch.set_num_threads(1)` and " + "`torch.set_num_interop_threads(1)` before using PathosBenchmark!" ) cores_available = pathos.multiprocessing.cpu_count() if nproc >= cores_available: raise RuntimeError( f"Requesting a benchmark with {nproc} cores but " + f"machine has {cores_available} cores! It is highly " "recommended to leave at least 1-2 cores open for OS tasks." ) self.pool = pathos.pools.ProcessPool(nodes=nproc) def __del__(self): # destroy the pool (for when we're testing or running # multiple benchmarks in one script) but if the GC already # cleared the underlying multiprocessing object (usually on # the final call), don't do anything. if hasattr(self, "pool") and self.pool is not None: try: self.pool.close() self.pool.join() self.pool.clear() except TypeError: pass def run_experiment( self, problem: Problem, config_dict: Dict[str, Any], seed: int, rep: int, ) -> Tuple[List[Dict[str, Any]], Union[SequentialStrategy, None]]: """Run one simulated experiment. Args: config_dict (Dict[str, Any]): AEPsych configuration to use. seed (int): Random seed for this run. rep (int): Index of this repetition. Returns: Tuple[List[Dict[str, Any]], SequentialStrategy]: A tuple containing a log of the results and the strategy as of the end of the simulated experiment. This is ignored in large-scale benchmarks but useful for one-off visualization. """ # copy things that we mutate local_config = deepcopy(config_dict) try: return super().run_experiment(problem, local_config, seed, rep) except Exception as e: logging.error( f"Error on config {config_dict}: {e}!" + f"Traceback follows:\n{traceback.format_exc()}" ) return [], SequentialStrategy([]) def __getstate__(self): self_dict = self.__dict__.copy() if "pool" in self_dict.keys(): del self_dict["pool"] if "futures" in self_dict.keys(): del self_dict["futures"] return self_dict def run_benchmarks(self): """Run all the benchmarks, Note that this blocks while waiting for benchmarks to complete. If you would like to start benchmarks and periodically collect partial results, use start_benchmarks and then call collate_benchmarks(wait=False) on some interval. """ self.start_benchmarks() self.collate_benchmarks(wait=True) def start_benchmarks(self): """Start benchmark run. This does not block: after running it, self.futures holds the status of benchmarks running in parallel. """ def run_discard_strat(*conf): logger, _ = self.run_experiment(*conf) return logger self.all_sim_configs = [ (problem, config_dict, self.seed + seed, rep) for seed, (problem, config_dict, rep) in enumerate( itertools.product(self.problems, self.combinations, range(self.n_reps)) ) ] shuffle(self.all_sim_configs) self.futures = [ self.pool.apipe(run_discard_strat, *conf) for conf in self.all_sim_configs ] @property def is_done(self) -> bool: """Check if the benchmark is done. Returns: bool: True if all futures are cleared and benchmark is done. """ return len(self.futures) == 0 def collate_benchmarks(self, wait: bool = False) -> None: """Collect benchmark results from completed futures. Args: wait (bool, optional): If true, this method blocks and waits on all futures to complete. Defaults to False. """ newfutures = [] while self.futures: item = self.futures.pop() if wait or item.ready(): results = item.get() # filter out empty results from invalid configs results = [r for r in results if r != {}] if isinstance(results, list): self._log.extend(results) else: newfutures.append(item) self.futures = newfutures def run_benchmarks_with_checkpoints( out_path: str, benchmark_name: str, problems: List[Problem], configs: Mapping[str, Union[str, list]], global_seed: Optional[int] = None, n_chunks: int = 1, n_reps_per_chunk: int = 1, log_every: Optional[int] = None, checkpoint_every: int = 60, n_proc: int = 1, serial_debug: bool = False, ) -> None: """Runs a series of benchmarks, saving both final and intermediate results to .csv files. Benchmarks are run in sequential chunks, each of which runs all combinations of problems/configs/reps in parallel. This function should always be used using the "if __name__ == '__main__': ..." idiom. Args: out_path (str): The path to save the results to. benchmark_name (str): A name give to this set of benchmarks. Results will be saved in files named like "out_path/benchmark_name_chunk{chunk_number}_out.csv" problems (List[Problem]): Problem objects containing the test function to evaluate. configs (Mapping[str, Union[str, list]]): Dictionary of configs to run. Lists at leaves are used to construct a cartesian product of configurations. global_seed (int, optional): Global seed to use for reproducible benchmarks. Defaults to randomized seeds. n_chunks (int): The number of chunks to break the results into. Each chunk will contain at least 1 run of every combination of problem and config. n_reps_per_chunk (int, optional): Number of repetitions to run each problem/config in each chunk. log_every (int, optional): Logging interval during an experiment. Defaults to only logging at the end. checkpoint_every (int): Save intermediate results every checkpoint_every seconds. n_proc (int): Number of processors to use. serial_debug: debug serially? """ Path(out_path).mkdir( parents=True, exist_ok=True ) # make an output folder if not exist if serial_debug: out_fname = Path(f"{out_path}/{benchmark_name}_out.csv") print(f"Starting {benchmark_name} benchmark (serial debug mode)...") bench = Benchmark( problems=problems, configs=configs, seed=global_seed, n_reps=n_reps_per_chunk * n_chunks, log_every=log_every, ) bench.run_benchmarks() final_results = bench.pandas() final_results.to_csv(out_fname) else: for chunk in range(n_chunks): out_fname = Path(f"{out_path}/{benchmark_name}_chunk{chunk}_out.csv") intermediate_fname = Path( f"{out_path}/{benchmark_name}_chunk{chunk}_checkpoint.csv" ) print(f"Starting {benchmark_name} benchmark... chunk {chunk} ") bench = PathosBenchmark( nproc=n_proc, problems=problems, configs=configs, seed=None, n_reps=n_reps_per_chunk, log_every=log_every, ) if global_seed is None: global_seed = int(np.random.randint(0, 200)) bench.seed = ( global_seed + chunk * bench.num_benchmarks ) # HACK. TODO: make num_benchmarks a property of bench configs bench.start_benchmarks() while not bench.is_done: time.sleep(checkpoint_every) collate_start = time.time() print( f"Checkpointing {benchmark_name} chunk {chunk}..., {len(bench.futures)}/{bench.num_benchmarks} alive" ) bench.collate_benchmarks(wait=False) temp_results = bench.pandas() if len(temp_results) > 0: temp_results["rep"] = temp_results["rep"] + n_reps_per_chunk * chunk temp_results.to_csv(intermediate_fname) print( f"Collate done in {time.time()-collate_start} seconds, {len(bench.futures)}/{bench.num_benchmarks} left" ) print(f"{benchmark_name} chunk {chunk} fully done!") final_results = bench.pandas() final_results["rep"] = final_results["rep"] + n_reps_per_chunk * chunk final_results.to_csv(out_fname)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from .benchmark import Benchmark, DerivedValue from .pathos_benchmark import PathosBenchmark, run_benchmarks_with_checkpoints from .problem import LSEProblem, Problem from .test_functions import ( discrim_highdim, make_songetal_testfun, modified_hartmann6, novel_detection_testfun, novel_discrimination_testfun, ) __all__ = [ "Benchmark", "DerivedValue", "PathosBenchmark", "PathosBenchmark", "Problem", "LSEProblem", "make_songetal_testfun", "novel_detection_testfun", "novel_discrimination_testfun", "modified_hartmann6", "discrim_highdim", "run_benchmarks_with_checkpoints", ]
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from functools import cached_property from typing import Any, Dict, Union import aepsych import numpy as np import torch from aepsych.strategy import SequentialStrategy, Strategy from aepsych.utils import make_scaled_sobol from scipy.stats import bernoulli, norm, pearsonr class Problem: """Wrapper for a problem or test function. Subclass from this and override f() to define your test function. """ n_eval_points = 1000 @cached_property def eval_grid(self): return make_scaled_sobol(lb=self.lb, ub=self.ub, size=self.n_eval_points) @property def name(self) -> str: raise NotImplementedError def f(self, x): raise NotImplementedError @cached_property def lb(self): return self.bounds[0] @cached_property def ub(self): return self.bounds[1] @property def bounds(self): raise NotImplementedError @property def metadata(self) -> Dict[str, Any]: """A dictionary of metadata passed to the Benchmark to be logged. Each key will become a column in the Benchmark's output dataframe, with its associated value stored in each row.""" return {"name": self.name} def p(self, x: np.ndarray) -> np.ndarray: """Evaluate response probability from test function. Args: x (np.ndarray): Points at which to evaluate. Returns: np.ndarray: Response probability at queries points. """ return norm.cdf(self.f(x)) def sample_y(self, x: np.ndarray) -> np.ndarray: """Sample a response from test function. Args: x (np.ndarray): Points at which to sample. Returns: np.ndarray: A single (bernoulli) sample at points. """ return bernoulli.rvs(self.p(x)) def f_hat(self, model: aepsych.models.base.ModelProtocol) -> torch.Tensor: """Generate mean predictions from the model over the evaluation grid. Args: model (aepsych.models.base.ModelProtocol): Model to evaluate. Returns: torch.Tensor: Posterior mean from underlying model over the evaluation grid. """ f_hat, _ = model.predict(self.eval_grid) return f_hat @cached_property def f_true(self) -> np.ndarray: """Evaluate true test function over evaluation grid. Returns: torch.Tensor: Values of true test function over evaluation grid. """ return self.f(self.eval_grid).detach().numpy() @cached_property def p_true(self) -> torch.Tensor: """Evaluate true response probability over evaluation grid. Returns: torch.Tensor: Values of true response probability over evaluation grid. """ return norm.cdf(self.f_true) def p_hat(self, model: aepsych.models.base.ModelProtocol) -> torch.Tensor: """Generate mean predictions from the model over the evaluation grid. Args: model (aepsych.models.base.ModelProtocol): Model to evaluate. Returns: torch.Tensor: Posterior mean from underlying model over the evaluation grid. """ p_hat, _ = model.predict(self.eval_grid, probability_space=True) return p_hat def evaluate( self, strat: Union[Strategy, SequentialStrategy], ) -> Dict[str, float]: """Evaluate the strategy with respect to this problem. Extend this in subclasses to add additional metrics. Metrics include: - mae (mean absolute error), mae (mean absolute error), max_abs_err (max absolute error), pearson correlation. All of these are computed over the latent variable f and the outcome probability p, w.r.t. the posterior mean. Squared and absolute errors (miae, mise) are also computed in expectation over the posterior, by sampling. - Brier score, which measures how well-calibrated the outcome probability is, both at the posterior mean (plain brier) and in expectation over the posterior (expected_brier). Args: strat (aepsych.strategy.Strategy): Strategy to evaluate. Returns: Dict[str, float]: A dictionary containing metrics and their values. """ # we just use model here but eval gets called on strat in case we need it in downstream evals # for example to separate out sobol vs opt trials model = strat.model assert model is not None, "Cannot evaluate strategy without a model!" # always eval f f_hat = self.f_hat(model).detach().numpy() p_hat = self.p_hat(model).detach().numpy() assert ( self.f_true.shape == f_hat.shape ), f"self.f_true.shape=={self.f_true.shape} != f_hat.shape=={f_hat.shape}" mae_f = np.mean(np.abs(self.f_true - f_hat)) mse_f = np.mean((self.f_true - f_hat) ** 2) max_abs_err_f = np.max(np.abs(self.f_true - f_hat)) corr_f = pearsonr(self.f_true.flatten(), f_hat.flatten())[0] mae_p = np.mean(np.abs(self.p_true - p_hat)) mse_p = np.mean((self.p_true - p_hat) ** 2) max_abs_err_p = np.max(np.abs(self.p_true - p_hat)) corr_p = pearsonr(self.p_true.flatten(), p_hat.flatten())[0] brier = np.mean(2 * np.square(self.p_true - p_hat)) # eval in samp-based expectation over posterior instead of just mean fsamps = model.sample(self.eval_grid, num_samples=1000).detach().numpy() try: psamps = ( model.sample(self.eval_grid, num_samples=1000, probability_space=True) # type: ignore .detach() .numpy() ) except TypeError: # vanilla models don't have proba_space samps, TODO maybe we should add them psamps = norm.cdf(fsamps) ferrs = fsamps - self.f_true[None, :] miae_f = np.mean(np.abs(ferrs)) mise_f = np.mean(ferrs**2) perrs = psamps - self.p_true[None, :] miae_p = np.mean(np.abs(perrs)) mise_p = np.mean(perrs**2) expected_brier = (2 * np.square(self.p_true[None, :] - psamps)).mean() metrics = { "mean_abs_err_f": mae_f, "mean_integrated_abs_err_f": miae_f, "mean_square_err_f": mse_f, "mean_integrated_square_err_f": mise_f, "max_abs_err_f": max_abs_err_f, "pearson_corr_f": corr_f, "mean_abs_err_p": mae_p, "mean_integrated_abs_err_p": miae_p, "mean_square_err_p": mse_p, "mean_integrated_square_err_p": mise_p, "max_abs_err_p": max_abs_err_p, "pearson_corr_p": corr_p, "brier": brier, "expected_brier": expected_brier, } return metrics class LSEProblem(Problem): """Level set estimation problem. This extends the base problem class to evaluate the LSE/threshold estimate in addition to the function estimate. """ threshold = 0.75 @property def metadata(self) -> Dict[str, Any]: """A dictionary of metadata passed to the Benchmark to be logged. Each key will become a column in the Benchmark's output dataframe, with its associated value stored in each row.""" md = super().metadata md["threshold"] = self.threshold return md def f_threshold(self, model=None): try: inverse_torch = model.likelihood.objective.inverse def inverse_link(x): return inverse_torch(torch.tensor(x)).numpy() except AttributeError: inverse_link = norm.ppf return float(inverse_link(self.threshold)) @cached_property def true_below_threshold(self) -> np.ndarray: """ Evaluate whether the true function is below threshold over the eval grid (used for proper scoring and threshold missclassification metric). """ return (self.p(self.eval_grid) <= self.threshold).astype(float) def evaluate(self, strat: Union[Strategy, SequentialStrategy]) -> Dict[str, float]: """Evaluate the model with respect to this problem. For level set estimation, we add metrics w.r.t. the true threshold: - brier_p_below_{thresh), the brier score w.r.t. p(f(x)<thresh), in contrast to regular brier, which is the brier score for p(phi(f(x))=1), and the same for misclassification error. Args: strat (aepsych.strategy.Strategy): Strategy to evaluate. Returns: Dict[str, float]: A dictionary containing metrics and their values, including parent class metrics. """ metrics = super().evaluate(strat) # we just use model here but eval gets called on strat in case we need it in downstream evals # for example to separate out sobol vs opt trials model = strat.model assert model is not None, "Cannot make predictions without a model!" # TODO bring back more threshold error metrics when we more clearly # define what "threshold" means in high-dim. # Predict p(below threshold) at test points p_l = model.p_below_threshold(self.eval_grid, self.f_threshold(model)) # Brier score on level-set probabilities thresh = self.threshold brier_name = f"brier_p_below_{thresh}" metrics[brier_name] = np.mean(2 * np.square(self.true_below_threshold - p_l)) # Classification error classerr_name = f"missclass_on_thresh_{thresh}" metrics[classerr_name] = np.mean( p_l * (1 - self.true_below_threshold) + (1 - p_l) * self.true_below_threshold ) return metrics
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import io import math from typing import Callable import numpy as np import pandas as pd from scipy.interpolate import CubicSpline, interp1d from scipy.stats import norm # manually scraped data from doi:10.1007/s10162-013-0396-x fig 2 raw = """\ freq,thresh,phenotype 0.25,6.816404934,Older-normal 0.5,5.488517768,Older-normal 1,3.512856308,Older-normal 2,5.909671334,Older-normal 3,6.700337017,Older-normal 4,10.08761498,Older-normal 6,13.46962853,Older-normal 8,12.97026073,Older-normal 0.25,5.520856346,Sensory 0.5,4.19296918,Sensory 1,5.618122764,Sensory 2,19.83681866,Sensory 3,42.00403606,Sensory 4,53.32679981,Sensory 6,62.0527006,Sensory 8,66.08775286,Sensory 0.25,21.2291323,Metabolic 0.5,22.00676227,Metabolic 1,24.24163372,Metabolic 2,33.92590956,Metabolic 3,41.35626176,Metabolic 4,47.17294402,Metabolic 6,54.1174655,Metabolic 8,58.31446133,Metabolic 0.25,20.25772154,Metabolic+Sensory 0.5,20.71121368,Metabolic+Sensory 1,21.97442369,Metabolic+Sensory 2,37.48866818,Metabolic+Sensory 3,53.17814263,Metabolic+Sensory 4,64.01507567,Metabolic+Sensory 6,75.00818649,Metabolic+Sensory 8,76.61433583,Metabolic+Sensory""" dubno_data = pd.read_csv(io.StringIO(raw)) def make_songetal_threshfun(x: np.ndarray, y: np.ndarray) -> Callable[[float], float]: """Generate a synthetic threshold function by interpolation of real data. Real data is from Dubno et al. 2013, and procedure follows Song et al. 2017, 2018. See make_songetal_testfun for more detail. Args: x (np.ndarray): Frequency y (np.ndarray): Threshold Returns: Callable[[float], float]: Function that interpolates the given frequencies and thresholds and returns threshold as a function of frequency. """ f_interp = CubicSpline(x, y, extrapolate=False) f_extrap = interp1d(x, y, fill_value="extrapolate") def f_combo(x): # interpolate first interpolated = f_interp(x) # whatever is nan needs extrapolating interpolated[np.isnan(interpolated)] = f_extrap(x[np.isnan(interpolated)]) return interpolated return f_combo def make_songetal_testfun( phenotype: str = "Metabolic", beta: float = 1 ) -> Callable[[np.ndarray, bool], np.ndarray]: """Make an audiometric test function following Song et al. 2017. To do so,we first compute a threshold by interpolation/extrapolation from real data, then assume a linear psychometric function in intensity with slope beta. Args: phenotype (str, optional): Audiometric phenotype from Dubno et al. 2013. Specifically, one of "Metabolic", "Sensory", "Metabolic+Sensory", or "Older-normal". Defaults to "Metabolic". beta (float, optional): Psychometric function slope. Defaults to 1. Returns: Callable[[np.ndarray, bool], np.ndarray]: A test function taking a [b x 2] array of points and returning the psychometric function value at those points. Raises: AssertionError: if an invalid phenotype is passed. References: Song, X. D., Garnett, R., & Barbour, D. L. (2017). Psychometric function estimation by probabilistic classification. The Journal of the Acoustical Society of America, 141(4), 2513–2525. https://doi.org/10.1121/1.4979594 """ valid_phenotypes = ["Metabolic", "Sensory", "Metabolic+Sensory", "Older-normal"] assert phenotype in valid_phenotypes, f"Phenotype must be one of {valid_phenotypes}" x = dubno_data[dubno_data.phenotype == phenotype].freq.values y = dubno_data[dubno_data.phenotype == phenotype].thresh.values # first, make the threshold fun threshfun = make_songetal_threshfun(x, y) # now make it into a test function def song_testfun(x, cdf=False): logfreq = x[..., 0] intensity = x[..., 1] thresh = threshfun(2**logfreq) return ( norm.cdf((intensity - thresh) / beta) if cdf else (intensity - thresh) / beta ) return song_testfun def novel_discrimination_testfun(x: np.ndarray) -> np.ndarray: """Evaluate novel discrimination test function from Owen et al. The threshold is roughly parabolic with context, and the slope varies with the threshold. Adding to the difficulty is the fact that the function is minimized at f=0 (or p=0.5), corresponding to discrimination being at chance at zero stimulus intensity. Args: x (np.ndarray): Points at which to evaluate. Returns: np.ndarray: Value of function at these points. """ freq = x[..., 0] amp = x[..., 1] context = 2 * (0.05 + 0.4 * (-1 + 0.2 * freq) ** 2 * freq**2) return 2 * (amp + 1) / context def novel_detection_testfun(x: np.ndarray) -> np.ndarray: """Evaluate novel detection test function from Owen et al. The threshold is roughly parabolic with context, and the slope varies with the threshold. Args: x (np.ndarray): Points at which to evaluate. Returns: np.ndarray: Value of function at these points. """ freq = x[..., 0] amp = x[..., 1] context = 2 * (0.05 + 0.4 * (-1 + 0.2 * freq) ** 2 * freq**2) return 4 * (amp + 1) / context - 4 def discrim_highdim(x: np.ndarray) -> np.ndarray: amp = x[..., 0] freq = x[..., 1] vscale = x[..., 2] vshift = x[..., 3] variance = x[..., 4] asym = x[..., 5] phase = x[..., 6] period = x[..., 7] context = ( -0.5 * vscale * np.cos(period * 0.6 * math.pi * freq + phase) + vscale / 2 + vshift ) * ( -1 * asym * np.sin(period * 0.6 * math.pi * 0.5 * freq + phase) + (2 - asym) ) - 1 z = (amp - context) / (variance + variance * (1 + context)) p = norm.cdf(z) p = (1 - 0.5) * p + 0.5 # Floor at p=0.5 p = np.clip(p, 0.5, 1 - 1e-5) # clip so that norm.ppf doesn't go to inf return norm.ppf(p) def modified_hartmann6(X): """ The modified Hartmann6 function used in Lyu et al. """ C = np.r_[0.2, 0.22, 0.28, 0.3] a_t = np.c_[ [8, 3, 10, 3.5, 1.7, 6], [0.5, 8, 10, 1.0, 6, 9], [3, 3.5, 1.7, 8, 10, 6], [10, 6, 0.5, 8, 1.0, 9], ].T p_t = ( 10 ** (-4) * np.c_[ [1312, 1696, 5569, 124, 8283, 5886], [2329, 4135, 8307, 3736, 1004, 9991], [2348, 1451, 3522, 2883, 3047, 6650], [4047, 8828, 8732, 5743, 1091, 381], ].T ) y = 0.0 for i, C_i in enumerate(C): t = 0 for j in range(6): t += a_t[i, j] * ((X[j] - p_t[i, j]) ** 2) y += C_i * np.exp(-t) return -10 * (float(y) - 0.1)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import datetime import logging import os import uuid from contextlib import contextmanager from pathlib import Path from typing import Dict import aepsych.database.tables as tables from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.session import close_all_sessions logger = logging.getLogger() class Database: def __init__(self, db_path=None): if db_path is None: db_path = "./databases/default.db" db_dir, db_name = os.path.split(db_path) self._db_name = db_name self._db_dir = db_dir if os.path.exists(db_path): logger.info(f"Found DB at {db_path}, appending!") else: logger.info(f"No DB found at {db_path}, creating a new DB!") self._engine = self.get_engine() def get_engine(self): if not hasattr(self, "_engine") or self._engine is None: self._full_db_path = Path(self._db_dir) self._full_db_path.mkdir(parents=True, exist_ok=True) self._full_db_path = self._full_db_path.joinpath(self._db_name) self._engine = create_engine(f"sqlite:///{self._full_db_path.as_posix()}") # create the table metadata and tables tables.Base.metadata.create_all(self._engine) # create an ongoing session to be used. Provides a conduit # to the db so the instantiated objects work properly. Session = sessionmaker(bind=self.get_engine()) self._session = Session() return self._engine def delete_db(self): if self._engine is not None and self._full_db_path.exists(): close_all_sessions() self._full_db_path.unlink() self._engine = None def is_update_required(self): return ( tables.DBMasterTable.requires_update(self._engine) or tables.DbReplayTable.requires_update(self._engine) or tables.DbStratTable.requires_update(self._engine) or tables.DbConfigTable.requires_update(self._engine) or tables.DbRawTable.requires_update(self._engine) or tables.DbParamTable.requires_update(self._engine) or tables.DbOutcomeTable.requires_update(self._engine) ) def perform_updates(self): """Perform updates on known tables. SQLAlchemy doesn't do alters so they're done the old fashioned way.""" tables.DBMasterTable.update(self._engine) tables.DbReplayTable.update(self._engine) tables.DbStratTable.update(self._engine) tables.DbConfigTable.update(self._engine) tables.DbRawTable.update(self, self._engine) tables.DbParamTable.update(self._engine) tables.DbOutcomeTable.update(self._engine) @contextmanager def session_scope(self): """Provide a transactional scope around a series of operations.""" Session = sessionmaker(bind=self.get_engine()) session = Session() try: yield session session.commit() except Exception as err: logger.error(f"db session use failed: {err}") session.rollback() raise finally: session.close() # @retry(stop_max_attempt_number=8, wait_exponential_multiplier=1.8) def execute_sql_query(self, query: str, vals: Dict[str, str]): """Execute an arbitrary query written in sql.""" with self.session_scope() as session: return session.execute(query, vals).fetchall() def get_master_records(self): """Grab the list of master records.""" records = self._session.query(tables.DBMasterTable).all() return records def get_master_record(self, experiment_id): """Grab the list of master record for a specific experiment (master) id.""" records = ( self._session.query(tables.DBMasterTable) .filter(tables.DBMasterTable.experiment_id == experiment_id) .all() ) if 0 < len(records): return records[0] return None def get_replay_for(self, master_id): """Get the replay records for a specific master row.""" master_record = self.get_master_record(master_id) if master_record is not None: return master_record.children_replay return None def get_strats_for(self, master_id=0): """Get the strat records for a specific master row.""" master_record = self.get_master_record(master_id) if master_record is not None and len(master_record.children_strat) > 0: return [c.strat for c in master_record.children_strat] return None def get_strat_for(self, master_id, strat_id=-1): """Get a specific strat record for a specific master row.""" master_record = self.get_master_record(master_id) if master_record is not None and len(master_record.children_strat) > 0: return master_record.children_strat[strat_id].strat return None def get_config_for(self, master_id): """Get the strat records for a specific master row.""" master_record = self.get_master_record(master_id) if master_record is not None: return master_record.children_config[0].config return None def get_raw_for(self, master_id): """Get the raw data for a specific master row.""" master_record = self.get_master_record(master_id) if master_record is not None: return master_record.children_raw return None def get_all_params_for(self, master_id): """Get the parameters for all the iterations of a specific experiment.""" raw_record = self.get_raw_for(master_id) params = [] if raw_record is not None: for raw in raw_record: for param in raw.children_param: params.append(param) return params return None def get_param_for(self, master_id, iteration_id): """Get the parameters for a specific iteration of a specific experiment.""" raw_record = self.get_raw_for(master_id) if raw_record is not None: for raw in raw_record: if raw.unique_id == iteration_id: return raw.children_param return None def get_all_outcomes_for(self, master_id): """Get the outcomes for all the iterations of a specific experiment.""" raw_record = self.get_raw_for(master_id) outcomes = [] if raw_record is not None: for raw in raw_record: for outcome in raw.children_outcome: outcomes.append(outcome) return outcomes return None def get_outcome_for(self, master_id, iteration_id): """Get the outcomes for a specific iteration of a specific experiment.""" raw_record = self.get_raw_for(master_id) if raw_record is not None: for raw in raw_record: if raw.unique_id == iteration_id: return raw.children_outcome return None def record_setup( self, description, name, extra_metadata=None, id=None, request=None, participant_id=None, ) -> str: self.get_engine() if id is None: master_table = tables.DBMasterTable() master_table.experiment_description = description master_table.experiment_name = name master_table.experiment_id = str(uuid.uuid4()) if participant_id is not None: master_table.participant_id = participant_id else: master_table.participant_id = str( uuid.uuid4() ) # no p_id specified will result in a generated UUID master_table.extra_metadata = extra_metadata self._session.add(master_table) logger.debug(f"record_setup = [{master_table}]") else: master_table = self.get_master_record(id) if master_table is None: raise RuntimeError(f"experiment id {id} doesn't exist in the db.") record = tables.DbReplayTable() record.message_type = "setup" record.message_contents = request if "extra_info" in request: record.extra_info = request["extra_info"] record.timestamp = datetime.datetime.now() record.parent = master_table logger.debug(f"record_setup = [{record}]") self._session.add(record) self._session.commit() # return the master table if it has a link to the list of child rows # tis needs to be passed into all future calls to link properly return master_table def record_message(self, master_table, type, request) -> None: # create a linked setup table record = tables.DbReplayTable() record.message_type = type record.message_contents = request if "extra_info" in request: record.extra_info = request["extra_info"] record.timestamp = datetime.datetime.now() record.parent = master_table self._session.add(record) self._session.commit() def record_raw(self, master_table, model_data, timestamp=None): raw_entry = tables.DbRawTable() raw_entry.model_data = model_data if timestamp is None: raw_entry.timestamp = datetime.datetime.now() else: raw_entry.timestamp = timestamp raw_entry.parent = master_table self._session.add(raw_entry) self._session.commit() return raw_entry def record_param(self, raw_table, param_name, param_value) -> None: param_entry = tables.DbParamTable() param_entry.param_name = param_name param_entry.param_value = param_value param_entry.parent = raw_table self._session.add(param_entry) self._session.commit() def record_outcome(self, raw_table, outcome_name, outcome_value) -> None: outcome_entry = tables.DbOutcomeTable() outcome_entry.outcome_name = outcome_name outcome_entry.outcome_value = outcome_value outcome_entry.parent = raw_table self._session.add(outcome_entry) self._session.commit() def record_strat(self, master_table, strat): strat_entry = tables.DbStratTable() strat_entry.strat = strat strat_entry.timestamp = datetime.datetime.now() strat_entry.parent = master_table self._session.add(strat_entry) self._session.commit() def record_config(self, master_table, config): config_entry = tables.DbConfigTable() config_entry.config = config config_entry.timestamp = datetime.datetime.now() config_entry.parent = master_table self._session.add(config_entry) self._session.commit() def list_master_records(self): master_records = self.get_master_records() print("Listing master records:") for record in master_records: print( f'\t{record.unique_id} - name: "{record.experiment_name}" experiment id: {record.experiment_id}' )
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import, division, print_function, unicode_literals import logging import pickle from collections.abc import Iterable from aepsych.config import Config from aepsych.version import __version__ from sqlalchemy import ( Boolean, Column, DateTime, Float, ForeignKey, Integer, PickleType, String, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker logger = logging.getLogger() Base = declarative_base() """ Original Schema CREATE TABLE master ( unique_id INTEGER NOT NULL, experiment_name VARCHAR(256), experiment_description VARCHAR(2048), experiment_id VARCHAR(10), PRIMARY KEY (unique_id), UNIQUE (experiment_id) ); CREATE TABLE replay_data ( unique_id INTEGER NOT NULL, timestamp DATETIME, message_type VARCHAR(64), message_contents BLOB, master_table_id INTEGER, PRIMARY KEY (unique_id), FOREIGN KEY(master_table_id) REFERENCES master (unique_id) ); """ class DBMasterTable(Base): """ Master table to keep track of all experiments and unique keys associated with the experiment """ __tablename__ = "master" unique_id = Column(Integer, primary_key=True, autoincrement=True) experiment_name = Column(String(256)) experiment_description = Column(String(2048)) experiment_id = Column(String(10), unique=True) participant_id = Column(String(50), unique=True) extra_metadata = Column(String(4096)) # JSON-formatted metadata children_replay = relationship("DbReplayTable", back_populates="parent") children_strat = relationship("DbStratTable", back_populates="parent") children_config = relationship("DbConfigTable", back_populates="parent") children_raw = relationship("DbRawTable", back_populates="parent") @classmethod def from_sqlite(cls, row): this = DBMasterTable() this.unique_id = row["unique_id"] this.experiment_name = row["experiment_name"] this.experiment_description = row["experiment_description"] this.experiment_id = row["experiment_id"] return this def __repr__(self): return ( f"<DBMasterTable(unique_id={self.unique_id})" f", experiment_name={self.experiment_name}, " f"experiment_description={self.experiment_description}, " f"experiment_id={self.experiment_id})>" ) @staticmethod def update(engine): logger.info("DBMasterTable : update called") if not DBMasterTable._has_column(engine, "extra_metadata"): DBMasterTable._add_column(engine, "extra_metadata") if not DBMasterTable._has_column(engine, "participant_id"): DBMasterTable._add_column(engine, "participant_id") @staticmethod def requires_update(engine): return not DBMasterTable._has_column( engine, "extra_metadata" ) or not DBMasterTable._has_column(engine, "participant_id") @staticmethod def _has_column(engine, column: str): result = engine.execute( "SELECT COUNT(*) FROM pragma_table_info('master') WHERE name='{0}'".format( column ) ) rows = result.fetchall() count = rows[0][0] return count != 0 @staticmethod def _add_column(engine, column: str): try: result = engine.execute( "SELECT COUNT(*) FROM pragma_table_info('master') WHERE name='{0}'".format( column ) ) rows = result.fetchall() count = rows[0][0] if 0 == count: logger.debug( "Altering the master table to add the {0} column".format(column) ) engine.execute( "ALTER TABLE master ADD COLUMN {0} VARCHAR".format(column) ) engine.commit() except Exception as e: logger.debug(f"Column already exists, no need to alter. [{e}]") class DbReplayTable(Base): __tablename__ = "replay_data" use_extra_info = False unique_id = Column(Integer, primary_key=True, autoincrement=True) timestamp = Column(DateTime) message_type = Column(String(64)) # specify the pickler to allow backwards compatibility between 3.7 and 3.8 message_contents = Column(PickleType(pickler=pickle)) extra_info = Column(PickleType(pickler=pickle)) master_table_id = Column(Integer, ForeignKey("master.unique_id")) parent = relationship("DBMasterTable", back_populates="children_replay") __mapper_args__ = {} @classmethod def from_sqlite(cls, row): this = DbReplayTable() this.unique_id = row["unique_id"] this.timestamp = row["timestamp"] this.message_type = row["message_type"] this.message_contents = row["message_contents"] this.master_table_id = row["master_table_id"] if "extra_info" in row: this.extra_info = row["extra_info"] else: this.extra_info = None this.strat = row["strat"] return this def __repr__(self): return ( f"<DbReplayTable(unique_id={self.unique_id})" f", timestamp={self.timestamp}, " f"message_type={self.message_type}" f", master_table_id={self.master_table_id})>" ) @staticmethod def _has_extra_info(engine): result = engine.execute( "SELECT COUNT(*) FROM pragma_table_info('replay_data') WHERE name='extra_info'" ) rows = result.fetchall() count = rows[0][0] return count != 0 @staticmethod def _configs_require_conversion(engine): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() results = session.query(DbReplayTable).all() for result in results: if result.message_contents["type"] == "setup": config_str = result.message_contents["message"]["config_str"] config = Config(config_str=config_str) if config.version < __version__: return True # assume that if any config needs to be refactored, all of them do return False @staticmethod def update(engine): logger.info("DbReplayTable : update called") if not DbReplayTable._has_extra_info(engine): DbReplayTable._add_extra_info(engine) if DbReplayTable._configs_require_conversion(engine): DbReplayTable._convert_configs(engine) @staticmethod def requires_update(engine): return not DbReplayTable._has_extra_info( engine ) or DbReplayTable._configs_require_conversion(engine) @staticmethod def _add_extra_info(engine): try: result = engine.execute( "SELECT COUNT(*) FROM pragma_table_info('replay_data') WHERE name='extra_info'" ) rows = result.fetchall() count = rows[0][0] if 0 == count: logger.debug( "Altering the replay_data table to add the extra_info column" ) engine.execute("ALTER TABLE replay_data ADD COLUMN extra_info BLOB") engine.commit() except Exception as e: logger.debug(f"Column already exists, no need to alter. [{e}]") @staticmethod def _convert_configs(engine): Session = sessionmaker(bind=engine) session = Session() results = session.query(DbReplayTable).all() for result in results: if result.message_contents["type"] == "setup": config_str = result.message_contents["message"]["config_str"] config = Config(config_str=config_str) if config.version < __version__: config.convert_to_latest() new_str = str(config) new_message = {"type": "setup", "message": {"config_str": new_str}} if "version" in result.message_contents: new_message["version"] = result.message_contents["version"] result.message_contents = new_message session.commit() logger.info("DbReplayTable : updated old configs.") class DbStratTable(Base): __tablename__ = "strat_data" unique_id = Column(Integer, primary_key=True, autoincrement=True) timestamp = Column(DateTime) strat = Column(PickleType(pickler=pickle)) master_table_id = Column(Integer, ForeignKey("master.unique_id")) parent = relationship("DBMasterTable", back_populates="children_strat") @classmethod def from_sqlite(cls, row): this = DbStratTable() this.unique_id = row["unique_id"] this.timestamp = row["timestamp"] this.strat = row["strat"] this.master_table_id = row["master_table_id"] return this def __repr__(self): return ( f"<DbStratTable(unique_id={self.unique_id})" f", timestamp={self.timestamp} " f", master_table_id={self.master_table_id})>" ) @staticmethod def update(engine): logger.info("DbStratTable : update called") @staticmethod def requires_update(engine): return False class DbConfigTable(Base): __tablename__ = "config_data" unique_id = Column(Integer, primary_key=True, autoincrement=True) timestamp = Column(DateTime) config = Column(PickleType(pickler=pickle)) master_table_id = Column(Integer, ForeignKey("master.unique_id")) parent = relationship("DBMasterTable", back_populates="children_config") @classmethod def from_sqlite(cls, row): this = DbConfigTable() this.unique_id = row["unique_id"] this.timestamp = row["timestamp"] this.strat = row["config"] this.master_table_id = row["master_table_id"] return this def __repr__(self): return ( f"<DbStratTable(unique_id={self.unique_id})" f", timestamp={self.timestamp} " f", master_table_id={self.master_table_id})>" ) @staticmethod def update(engine): logger.info("DbConfigTable : update called") @staticmethod def requires_update(engine): return False class DbRawTable(Base): """ Fact table to store the raw data of each iteration of an experiment. """ __tablename__ = "raw_data" unique_id = Column(Integer, primary_key=True, autoincrement=True) timestamp = Column(DateTime) model_data = Column(Boolean) master_table_id = Column(Integer, ForeignKey("master.unique_id")) parent = relationship("DBMasterTable", back_populates="children_raw") children_param = relationship("DbParamTable", back_populates="parent") children_outcome = relationship("DbOutcomeTable", back_populates="parent") @classmethod def from_sqlite(cls, row): this = DbRawTable() this.unique_id = row["unique_id"] this.timestamp = row["timestamp"] this.model_data = row["model_data"] this.master_table_id = row["master_table_id"] return this def __repr__(self): return ( f"<DbRawTable(unique_id={self.unique_id})" f", timestamp={self.timestamp} " f", master_table_id={self.master_table_id})>" ) @staticmethod def update(db, engine): logger.info("DbRawTable : update called") # Get every master table for master_table in db.get_master_records(): # Get raw tab for message in master_table.children_replay: if message.message_type != "tell": continue timestamp = message.timestamp # Deserialize pickle message message_contents = message.message_contents # Get outcome outcomes = message_contents["message"]["outcome"] # Get parameters params = message_contents["message"]["config"] # Get model_data model_data = message_contents["message"].get("model_data", True) db_raw_record = db.record_raw( master_table=master_table, model_data=bool(model_data), timestamp=timestamp, ) for param_name, param_value in params.items(): if isinstance(param_value, Iterable) and type(param_value) != str: if len(param_value) == 1: db.record_param( raw_table=db_raw_record, param_name=str(param_name), param_value=float(param_value[0]), ) else: for j, v in enumerate(param_value): db.record_param( raw_table=db_raw_record, param_name=str(param_name) + "_stimuli" + str(j), param_value=float(v), ) else: db.record_param( raw_table=db_raw_record, param_name=str(param_name), param_value=float(param_value), ) if isinstance(outcomes, Iterable) and type(outcomes) != str: for j, outcome_value in enumerate(outcomes): if ( isinstance(outcome_value, Iterable) and type(outcome_value) != str ): if len(outcome_value) == 1: outcome_value = outcome_value[0] else: raise ValueError( "Multi-outcome values must be a list of lists of length 1!" ) db.record_outcome( raw_table=db_raw_record, outcome_name="outcome_" + str(j), outcome_value=float(outcome_value), ) else: db.record_outcome( raw_table=db_raw_record, outcome_name="outcome", outcome_value=float(outcomes), ) @staticmethod def requires_update(engine): """Check if the raw table is empty, and data already exists.""" n_raws = engine.execute("SELECT COUNT (*) FROM raw_data").fetchone()[0] n_tells = engine.execute( "SELECT COUNT (*) FROM replay_data \ WHERE message_type = 'tell'" ).fetchone()[0] if n_raws == 0 and n_tells != 0: return True return False class DbParamTable(Base): """ Dimension table to store the parameters of each iteration of an experiment. Supports multiple parameters per iteration, and multiple stimuli per parameter. """ __tablename__ = "param_data" unique_id = Column(Integer, primary_key=True, autoincrement=True) param_name = Column(String(50)) param_value = Column(String(50)) iteration_id = Column(Integer, ForeignKey("raw_data.unique_id")) parent = relationship("DbRawTable", back_populates="children_param") @classmethod def from_sqlite(cls, row): this = DbParamTable() this.unique_id = row["unique_id"] this.param_name = row["param_name"] this.param_value = row["param_value"] this.iteration_id = row["iteration_id"] return this def __repr__(self): return ( f"<DbParamTable(unique_id={self.unique_id})" f", iteration_id={self.iteration_id}>" ) @staticmethod def update(engine): logger.info("DbParamTable : update called") @staticmethod def requires_update(engine): return False class DbOutcomeTable(Base): """ Dimension table to store the outcomes of each iteration of an experiment. Supports multiple outcomes per iteration. """ __tablename__ = "outcome_data" unique_id = Column(Integer, primary_key=True, autoincrement=True) outcome_name = Column(String(50)) outcome_value = Column(Float) iteration_id = Column(Integer, ForeignKey("raw_data.unique_id")) parent = relationship("DbRawTable", back_populates="children_outcome") @classmethod def from_sqlite(cls, row): this = DbOutcomeTable() this.unique_id = row["unique_id"] this.outcome_name = row["outcome_name"] this.outcome_value = row["outcome_value"] this.iteration_id = row["iteration_id"] return this def __repr__(self): return ( f"<DbOutcomeTable(unique_id={self.unique_id})" f", iteration_id={self.iteration_id}>" ) @staticmethod def update(engine): logger.info("DbOutcomeTable : update called") @staticmethod def requires_update(engine): return False
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import Any import torch from gpytorch.kernels.rbf_kernel_grad import RBFKernelGrad class RBFKernelPartialObsGrad(RBFKernelGrad): """An RBF kernel over observations of f, and partial/non-overlapping observations of the gradient of f. gpytorch.kernels.rbf_kernel_grad assumes a block structure where every partial derivative is observed at the same set of points at which x is observed. This generalizes that by allowing f and any subset of the derivatives of f to be observed at different sets of points. The final column of x1 and x2 needs to be an index that identifies what is observed at that point. It should be 0 if this observation is of f, and i if it is of df/dxi. """ def forward( self, x1: torch.Tensor, x2: torch.Tensor, diag: bool = False, **params: Any ) -> torch.Tensor: # Extract grad index from each grad_idx1 = x1[..., -1].to(dtype=torch.long) grad_idx2 = x2[..., -1].to(dtype=torch.long) K = super().forward(x1[..., :-1], x2[..., :-1], diag=diag, **params) # Compute which elements to return n1 = x1.shape[-2] n2 = x2.shape[-2] d = x1.shape[-1] - 1 p1 = [(i * (d + 1)) + int(grad_idx1[i]) for i in range(n1)] p2 = [(i * (d + 1)) + int(grad_idx2[i]) for i in range(n2)] if not diag: return K[..., p1, :][..., p2] else: return K[..., p1] def num_outputs_per_input(self, x1: torch.Tensor, x2: torch.Tensor) -> int: return 1
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree.
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. r""" """ from __future__ import annotations from typing import Optional import torch from aepsych.acquisition.monotonic_rejection import MonotonicMCAcquisition from botorch.acquisition.input_constructors import acqf_input_constructor from botorch.acquisition.monte_carlo import MCAcquisitionFunction from botorch.acquisition.objective import MCAcquisitionObjective from botorch.models.model import Model from botorch.sampling.base import MCSampler from botorch.sampling.normal import SobolQMCNormalSampler from botorch.utils.transforms import t_batch_mode_transform from torch import Tensor from torch.distributions.bernoulli import Bernoulli def bald_acq(obj_samples: torch.Tensor) -> torch.Tensor: """Evaluate Mutual Information acquisition function. With latent function F and X a hypothetical observation at a new point, I(F; X) = I(X; F) = H(X) - H(X |F), H(X |F ) = E_{f} (H(X |F =f ) i.e., we take the posterior entropy of the (Bernoulli) observation X given the current model posterior and subtract the conditional entropy on F, that being the mean entropy over the posterior for F. This is equivalent to the BALD acquisition function in Houlsby et al. NeurIPS 2012. Args: obj_samples (torch.Tensor): Objective samples from the GP, of shape num_samples x batch_shape x d_out Returns: torch.Tensor: Value of acquisition at samples. """ mean_p = obj_samples.mean(dim=0) posterior_entropies = Bernoulli(mean_p).entropy().squeeze(-1) sample_entropies = Bernoulli(obj_samples).entropy() conditional_entropies = sample_entropies.mean(dim=0).squeeze(-1) return posterior_entropies - conditional_entropies class BernoulliMCMutualInformation(MCAcquisitionFunction): """Mutual Information acquisition function for a bernoulli outcome. Given a model and an objective link function, calculate the mutual information of a trial at a new point and the distribution on the latent function. Objective here should give values in (0, 1) (e.g. logit or probit). """ def __init__( self, model: Model, objective: MCAcquisitionObjective, sampler: Optional[MCSampler] = None, ) -> None: r"""Single Bernoulli mutual information for active learning Args: model (Model): A fitted model. objective (MCAcquisitionObjective): An MCAcquisitionObjective representing the link function (e.g., logistic or probit) sampler (MCSampler, optional): The sampler used for drawing MC samples. """ if sampler is None: sampler = SobolQMCNormalSampler(sample_shape=torch.Size([1024])) super().__init__( model=model, sampler=sampler, objective=objective, X_pending=None ) @t_batch_mode_transform() def forward(self, X: Tensor) -> Tensor: r"""Evaluate mutual information on the candidate set `X`. Args: X: A `batch_size x q x d`-dim Tensor. Returns: Tensor of shape `batch_size x q` representing the mutual information of a hypothetical trial at X that active learning hopes to maximize. """ post = self.model.posterior(X) samples = self.sampler(post) return self.acquisition(self.objective(samples, X)) def acquisition(self, obj_samples: torch.Tensor) -> torch.Tensor: """Evaluate the acquisition function value based on samples. Args: obj_samples (torch.Tensor): Samples from the model, transformed through the objective. Returns: torch.Tensor: value of the acquisition function (BALD) at the input samples. """ # RejectionSampler drops the final dim so we reaugment it # here for compatibility with non-Monotonic MCAcquisition if len(obj_samples.shape) == 2: obj_samples = obj_samples[..., None] return bald_acq(obj_samples) @acqf_input_constructor(BernoulliMCMutualInformation) def construct_inputs_mi( model, training_data, objective=None, sampler=None, **kwargs, ): return { "model": model, "objective": objective, "sampler": sampler, } class MonotonicBernoulliMCMutualInformation(MonotonicMCAcquisition): def acquisition(self, obj_samples: torch.Tensor) -> torch.Tensor: """Evaluate the acquisition function value based on samples. Args: obj_samples (torch.Tensor): Samples from the model, transformed through the objective. Returns: torch.Tensor: value of the acquisition function (BALD) at the input samples. """ # TODO this is identical to nono-monotonic BALV acquisition with a different # base class mixin, consider redesigning? # RejectionSampler drops the final dim so we reaugment it # here for compatibility with non-Monotonic MCAcquisition if len(obj_samples.shape) == 2: obj_samples = obj_samples[..., None] return bald_acq(obj_samples)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from typing import Optional, Union import torch from aepsych.acquisition.objective import ProbitObjective from botorch.acquisition.input_constructors import acqf_input_constructor from botorch.acquisition.monte_carlo import ( MCAcquisitionFunction, MCAcquisitionObjective, MCSampler, ) from botorch.models.model import Model from botorch.sampling.normal import SobolQMCNormalSampler from botorch.utils.transforms import t_batch_mode_transform from torch import Tensor class MCLevelSetEstimation(MCAcquisitionFunction): def __init__( self, model: Model, target: Union[float, Tensor] = 0.75, beta: Union[float, Tensor] = 3.84, objective: Optional[MCAcquisitionObjective] = None, sampler: Optional[MCSampler] = None, ) -> None: r"""Monte-carlo level set estimation. Args: model: A fitted model. target: the level set (after objective transform) to be estimated beta: a parameter that governs explore-exploit tradeoff objective: An MCAcquisitionObjective representing the link function (e.g., logistic or probit.) applied on the samples. Can be implemented via GenericMCObjective. sampler: The sampler used for drawing MC samples. """ if sampler is None: sampler = SobolQMCNormalSampler(sample_shape=torch.Size([512])) if objective is None: objective = ProbitObjective() super().__init__(model=model, sampler=sampler, objective=None, X_pending=None) self.objective = objective self.beta = beta self.target = target def acquisition(self, obj_samples: torch.Tensor) -> torch.Tensor: """Evaluate the acquisition based on objective samples. Usually you should not call this directly unless you are subclassing this class and modifying how objective samples are generated. Args: obj_samples (torch.Tensor): Samples from the model, transformed by the objective. Should be samples x batch_shape. Returns: torch.Tensor: Acquisition function at the sampled values. """ mean = obj_samples.mean(dim=0) variance = obj_samples.var(dim=0) # prevent numerical issues if probit makes all the values 1 or 0 variance = torch.clamp(variance, min=1e-5) delta = torch.sqrt(self.beta * variance) return delta - torch.abs(mean - self.target) @t_batch_mode_transform() def forward(self, X: torch.Tensor) -> torch.Tensor: """Evaluate the acquisition function Args: X (torch.Tensor): Points at which to evaluate. Returns: torch.Tensor: Value of the acquisition functiona at these points. """ post = self.model.posterior(X) samples = self.sampler(post) # num_samples x batch_shape x q x d_out return self.acquisition(self.objective(samples, X)).squeeze(-1) @acqf_input_constructor(MCLevelSetEstimation) def construct_inputs_lse( model, training_data, objective=None, target=0.75, beta=3.84, sampler=None, **kwargs, ): return { "model": model, "objective": objective, "target": target, "beta": beta, "sampler": sampler, }
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Dict, Optional, Tuple import torch from botorch.acquisition.objective import PosteriorTransform from gpytorch.models import GP from gpytorch.utils.quadrature import GaussHermiteQuadrature1D from torch import Tensor from torch.distributions import Normal from .bvn import bvn_cdf def posterior_at_xstar_xq( model: GP, Xstar: Tensor, Xq: Tensor, posterior_transform: Optional[PosteriorTransform] = None, ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: """ Evaluate the posteriors of f at single point Xstar and set of points Xq. Args: model: The model to evaluate. Xstar: (b x 1 x d) tensor. Xq: (b x m x d) tensor. Returns: Mu_s: (b x 1) mean at Xstar. Sigma2_s: (b x 1) variance at Xstar. Mu_q: (b x m) mean at Xq. Sigma2_q: (b x m) variance at Xq. Sigma_sq: (b x m) covariance between Xstar and each point in Xq. """ # Evaluate posterior and extract needed components Xext = torch.cat((Xstar, Xq), dim=-2) posterior = model.posterior(Xext, posterior_transform=posterior_transform) mu = posterior.mean[..., :, 0] Mu_s = mu[..., 0].unsqueeze(-1) Mu_q = mu[..., 1:] Cov = posterior.distribution.covariance_matrix Sigma2_s = Cov[..., 0, 0].unsqueeze(-1) Sigma2_q = torch.diagonal(Cov[..., 1:, 1:], dim1=-1, dim2=-2) Sigma_sq = Cov[..., 0, 1:] return Mu_s, Sigma2_s, Mu_q, Sigma2_q, Sigma_sq def lookahead_levelset_at_xstar( model: GP, Xstar: Tensor, Xq: Tensor, posterior_transform: Optional[PosteriorTransform] = None, **kwargs: Dict[str, Any], ): """ Evaluate the look-ahead level-set posterior at Xq given observation at xstar. Args: model: The model to evaluate. Xstar: (b x 1 x d) observation point. Xq: (b x m x d) reference points. gamma: Threshold in f-space. Returns: Px: (b x m) Level-set posterior at Xq, before observation at xstar. P1: (b x m) Level-set posterior at Xq, given observation of 1 at xstar. P0: (b x m) Level-set posterior at Xq, given observation of 0 at xstar. py1: (b x 1) Probability of observing 1 at xstar. """ Mu_s, Sigma2_s, Mu_q, Sigma2_q, Sigma_sq = posterior_at_xstar_xq( model=model, Xstar=Xstar, Xq=Xq, posterior_transform=posterior_transform ) try: gamma = kwargs.get("gamma") except KeyError: raise RuntimeError("lookahead_levelset_at_xtar requires passing gamma!") # Compute look-ahead components Norm = torch.distributions.Normal(0, 1) Sigma_q = torch.sqrt(Sigma2_q) b_q = (gamma - Mu_q) / Sigma_q Phi_bq = Norm.cdf(b_q) denom = torch.sqrt(1 + Sigma2_s) a_s = Mu_s / denom Phi_as = Norm.cdf(a_s) Z_rho = -Sigma_sq / (Sigma_q * denom) Z_qs = bvn_cdf(a_s, b_q, Z_rho) Px = Phi_bq py1 = Phi_as P1 = Z_qs / py1 P0 = (Phi_bq - Z_qs) / (1 - py1) return Px, P1, P0, py1 def lookahead_p_at_xstar( model: GP, Xstar: Tensor, Xq: Tensor, posterior_transform: Optional[PosteriorTransform] = None, **kwargs: Dict[str, Any], ) -> Tuple[Tensor, Tensor, Tensor, Tensor]: """ Evaluate the look-ahead response probability posterior at Xq given observation at xstar. Uses the approximation given in expr. 9 in: Zhao, Guang, et al. "Efficient active learning for Gaussian process classification by error reduction." Advances in Neural Information Processing Systems 34 (2021): 9734-9746. Args: model: The model to evaluate. Xstar: (b x 1 x d) observation point. Xq: (b x m x d) reference points. kwargs: ignored (here for compatibility with other kinds of lookahead) Returns: Px: (b x m) Response posterior at Xq, before observation at xstar. P1: (b x m) Response posterior at Xq, given observation of 1 at xstar. P0: (b x m) Response posterior at Xq, given observation of 0 at xstar. py1: (b x 1) Probability of observing 1 at xstar. """ Mu_s, Sigma2_s, Mu_q, Sigma2_q, Sigma_sq = posterior_at_xstar_xq( model=model, Xstar=Xstar, Xq=Xq, posterior_transform=posterior_transform ) probit = Normal(0, 1).cdf def lookahead_inner(f_q): mu_tilde_star = Mu_s + (f_q - Mu_q) * Sigma_sq / Sigma2_q sigma_tilde_star = Sigma2_s - (Sigma_sq**2) / Sigma2_q return probit(mu_tilde_star / torch.sqrt(sigma_tilde_star + 1)) * probit(f_q) pstar_marginal_1 = probit(Mu_s / torch.sqrt(1 + Sigma2_s)) pstar_marginal_0 = 1 - pstar_marginal_1 pq_marginal_1 = probit(Mu_q / torch.sqrt(1 + Sigma2_q)) quad = GaussHermiteQuadrature1D() fq_mvn = Normal(Mu_q, torch.sqrt(Sigma2_q)) joint_ystar1_yq1 = quad(lookahead_inner, fq_mvn) joint_ystar0_yq1 = pq_marginal_1 - joint_ystar1_yq1 # now we need from the joint to the marginal on xq lookahead_pq1 = joint_ystar1_yq1 / pstar_marginal_1 lookahead_pq0 = joint_ystar0_yq1 / pstar_marginal_0 return pq_marginal_1, lookahead_pq1, lookahead_pq0, pstar_marginal_1 def approximate_lookahead_levelset_at_xstar( model: GP, Xstar: Tensor, Xq: Tensor, gamma: float, posterior_transform: Optional[PosteriorTransform] = None, ) -> Tuple[Tensor, Tensor, Tensor, Tensor]: """ The look-ahead posterior approximation of Lyu et al. Args: model: The model to evaluate. Xstar: (b x 1 x d) observation point. Xq: (b x m x d) reference points. gamma: Threshold in f-space. Returns: Px: (b x m) Level-set posterior at Xq, before observation at xstar. P1: (b x m) Level-set posterior at Xq, given observation of 1 at xstar. P0: (b x m) Level-set posterior at Xq, given observation of 0 at xstar. py1: (b x 1) Probability of observing 1 at xstar. """ Mu_s, Sigma2_s, Mu_q, Sigma2_q, Sigma_sq = posterior_at_xstar_xq( model=model, Xstar=Xstar, Xq=Xq, posterior_transform=posterior_transform ) Norm = torch.distributions.Normal(0, 1) Mu_s_pdf = torch.exp(Norm.log_prob(Mu_s)) Mu_s_cdf = Norm.cdf(Mu_s) # Formulae from the supplement of the paper (Result 2) vnp1_p = Mu_s_pdf**2 / Mu_s_cdf**2 + Mu_s * Mu_s_pdf / Mu_s_cdf # (C.4) p_p = Norm.cdf(Mu_s / torch.sqrt(1 + Sigma2_s)) # (C.5) vnp1_n = Mu_s_pdf**2 / (1 - Mu_s_cdf) ** 2 - Mu_s * Mu_s_pdf / ( 1 - Mu_s_cdf ) # (C.6) p_n = 1 - p_p # (C.7) vtild = vnp1_p * p_p + vnp1_n * p_n Sigma2_q_np1 = Sigma2_q - Sigma_sq**2 / ((1 / vtild) + Sigma2_s) # (C.8) Px = Norm.cdf((gamma - Mu_q) / torch.sqrt(Sigma2_q)) P1 = Norm.cdf((gamma - Mu_q) / torch.sqrt(Sigma2_q_np1)) P0 = P1 # Same because we ignore value of y in this approximation py1 = 0.5 * torch.ones(*Px.shape[:-1], 1) # Value doesn't matter because P1 = P0 return Px, P1, P0, py1
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import torch from botorch.posteriors import Posterior from botorch.sampling.base import MCSampler from torch import Tensor class RejectionSampler(MCSampler): """ Samples from a posterior subject to the constraint that samples in constrained_idx should be >= 0. If not enough feasible samples are generated, will return the least violating samples. """ def __init__( self, num_samples: int, num_rejection_samples: int, constrained_idx: Tensor ): """Initialize RejectionSampler Args: num_samples (int): Number of samples to return. Note that if fewer samples than this number are positive in the required dimension, the remaining samples returned will be the "least violating", i.e. closest to 0. num_rejection_samples (int): Number of samples to draw before rejecting. constrained_idx (Tensor): Indices of input dimensions that should be constrained positive. """ self.num_samples = num_samples self.num_rejection_samples = num_rejection_samples self.constrained_idx = constrained_idx super().__init__(sample_shape=torch.Size([num_samples])) def forward(self, posterior: Posterior) -> Tensor: """Run the rejection sampler. Args: posterior (Posterior): The unconstrained GP posterior object to perform rejection samples on. Returns: Tensor: Kept samples. """ samples = posterior.rsample( sample_shape=torch.Size([self.num_rejection_samples]) ) assert ( samples.shape[-1] == 1 ), "Batches not supported" # TODO T68656582 handle batches later constrained_samps = samples[:, self.constrained_idx, 0] valid = (constrained_samps >= 0).all(dim=1) if valid.sum() < self.num_samples: worst_violation = constrained_samps.min(dim=1)[0] keep = torch.argsort(worst_violation, descending=True)[: self.num_samples] else: keep = torch.where(valid)[0][: self.num_samples] return samples[keep, :, :]
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import sys from ..config import Config from .lookahead import ApproxGlobalSUR, EAVC, GlobalMI, GlobalSUR, LocalMI, LocalSUR from .lse import MCLevelSetEstimation from .mc_posterior_variance import MCPosteriorVariance, MonotonicMCPosteriorVariance from .monotonic_rejection import MonotonicMCLSE from .mutual_information import ( BernoulliMCMutualInformation, MonotonicBernoulliMCMutualInformation, ) from .objective import ( FloorGumbelObjective, FloorLogitObjective, FloorProbitObjective, ProbitObjective, semi_p, ) lse_acqfs = [ MonotonicMCLSE, GlobalMI, GlobalSUR, ApproxGlobalSUR, EAVC, LocalMI, LocalSUR, ] __all__ = [ "BernoulliMCMutualInformation", "MonotonicBernoulliMCMutualInformation", "MonotonicMCLSE", "MCPosteriorVariance", "MonotonicMCPosteriorVariance", "MCPosteriorVariance", "MCLevelSetEstimation", "ProbitObjective", "FloorProbitObjective", "FloorLogitObjective", "FloorGumbelObjective", "GlobalMI", "GlobalSUR", "ApproxGlobalSUR", "EAVC", "LocalMI", "LocalSUR", "semi_p", ] Config.register_module(sys.modules[__name__])
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from typing import Optional import torch from aepsych.acquisition.monotonic_rejection import MonotonicMCAcquisition from aepsych.acquisition.objective import ProbitObjective from botorch.acquisition.input_constructors import acqf_input_constructor from botorch.acquisition.monte_carlo import MCAcquisitionFunction from botorch.acquisition.objective import MCAcquisitionObjective from botorch.models.model import Model from botorch.sampling.base import MCSampler from botorch.sampling.normal import SobolQMCNormalSampler from botorch.utils.transforms import t_batch_mode_transform from torch import Tensor def balv_acq(obj_samps: torch.Tensor) -> torch.Tensor: """Evaluate BALV (posterior variance) on a set of objective samples. Args: obj_samps (torch.Tensor): Samples from the GP, transformed by the objective. Should be samples x batch_shape. Returns: torch.Tensor: Acquisition function value. """ # the output of objective is of shape num_samples x batch_shape x d_out # objective should project the last dimension to 1d, # so incoming should be samples x batch_shape, we take var in samp dim return obj_samps.var(dim=0).squeeze(-1) class MCPosteriorVariance(MCAcquisitionFunction): r"""Posterior variance, computed using samples so we can use objective/transform""" def __init__( self, model: Model, objective: Optional[MCAcquisitionObjective] = None, sampler: Optional[MCSampler] = None, ) -> None: r"""Posterior Variance of Link Function Args: model: A fitted model. objective: An MCAcquisitionObjective representing the link function (e.g., logistic or probit.) applied on the difference of (usually 1-d) two samples. Can be implemented via GenericMCObjective. sampler: The sampler used for drawing MC samples. """ if sampler is None: sampler = SobolQMCNormalSampler(sample_shape=torch.Size([512])) if objective is None: objective = ProbitObjective() super().__init__(model=model, sampler=sampler, objective=None, X_pending=None) self.objective = objective @t_batch_mode_transform() def forward(self, X: Tensor) -> Tensor: r"""Evaluate MCPosteriorVariance on the candidate set `X`. Args: X: A `batch_size x q x d`-dim Tensor Returns: Posterior variance of link function at X that active learning hopes to maximize """ # the output is of shape batch_shape x q x d_out post = self.model.posterior(X) samples = self.sampler(post) # num_samples x batch_shape x q x d_out return self.acquisition(self.objective(samples, X)) def acquisition(self, obj_samples: torch.Tensor) -> torch.Tensor: # RejectionSampler drops the final dim so we reaugment it # here for compatibility with non-Monotonic MCAcquisition if len(obj_samples.shape) == 2: obj_samples = obj_samples[..., None] return balv_acq(obj_samples) @acqf_input_constructor(MCPosteriorVariance) def construct_inputs( model, training_data, objective=None, sampler=None, **kwargs, ): return { "model": model, "objective": objective, "sampler": sampler, } class MonotonicMCPosteriorVariance(MonotonicMCAcquisition): def acquisition(self, obj_samples: torch.Tensor) -> torch.Tensor: return balv_acq(obj_samples)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from math import pi as _pi import torch inv_2pi = 1 / (2 * _pi) _neg_inv_sqrt2 = -1 / (2**0.5) def _gauss_legendre20(dtype): _abscissae = torch.tensor( [ 0.9931285991850949, 0.9639719272779138, 0.9122344282513259, 0.8391169718222188, 0.7463319064601508, 0.6360536807265150, 0.5108670019508271, 0.3737060887154196, 0.2277858511416451, 0.07652652113349733, ], dtype=dtype, ) _weights = torch.tensor( [ 0.01761400713915212, 0.04060142980038694, 0.06267204833410906, 0.08327674157670475, 0.1019301198172404, 0.1181945319615184, 0.1316886384491766, 0.1420961093183821, 0.1491729864726037, 0.1527533871307259, ], dtype=dtype, ) abscissae = torch.cat([1.0 - _abscissae, 1.0 + _abscissae], dim=0) weights = torch.cat([_weights, _weights], dim=0) return abscissae, weights def _ndtr(x: torch.Tensor) -> torch.Tensor: """ Standard normal CDF. Called <phid> in Genz's original code. """ return 0.5 * torch.erfc(_neg_inv_sqrt2 * x) def _bvnu( dh: torch.Tensor, dk: torch.Tensor, r: torch.Tensor, ) -> torch.Tensor: """ Primary subroutine for bvnu() """ # Precompute some terms h = dh k = dk hk = h * k x, w = _gauss_legendre20(dtype=dh.dtype) asr = 0.5 * torch.asin(r) sn = torch.sin(asr[..., None] * x) res = (sn * hk[..., None] - 0.5 * (h**2 + k**2)[..., None]) / (1 - sn**2) res = torch.sum(w * torch.exp(res), dim=-1) res = res * inv_2pi * asr + _ndtr(-h) * _ndtr(-k) return torch.clip(res, 0, 1) def bvn_cdf( xu: torch.Tensor, yu: torch.Tensor, r: torch.Tensor, ) -> torch.Tensor: """ Evaluate the bivariate normal CDF. WARNING: Implements only the routine for moderate levels of correlation. Will be inaccurate and should not be used for correlations larger than 0.925. Standard (mean 0, var 1) bivariate normal distribution with correlation r. Evaluated from -inf to xu, and -inf to yu. Based on function developed by Alan Genz: http://www.math.wsu.edu/faculty/genz/software/matlab/bvn.m based in turn on Drezner, Z and G.O. Wesolowsky, (1989), On the computation of the bivariate normal inegral, Journal of Statist. Comput. Simul. 35, pp. 101-107. Args: xu: Upper limits for cdf evaluation in x yu: Upper limits for cdf evaluation in y r: BVN correlation Returns: Tensor of cdf evaluations of same size as xu, yu, and r. """ p = 1 - _ndtr(-xu) - _ndtr(-yu) + _bvnu(xu, yu, r) return torch.clip(p, 0, 1)
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import Optional, Tuple from ax.models.torch.botorch_modular.acquisition import Acquisition from botorch.acquisition.objective import MCAcquisitionObjective, PosteriorTransform class AEPsychAcquisition(Acquisition): def get_botorch_objective_and_transform( self, **kwargs ) -> Tuple[Optional[MCAcquisitionObjective], Optional[PosteriorTransform]]: objective, transform = super().get_botorch_objective_and_transform(**kwargs) if "objective" in self.options: objective = self.options.pop("objective") return objective, transform
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from typing import Optional, Tuple, cast import numpy as np import torch from aepsych.utils import make_scaled_sobol from botorch.acquisition import AcquisitionFunction from botorch.acquisition.input_constructors import acqf_input_constructor from botorch.acquisition.objective import PosteriorTransform from botorch.models.gpytorch import GPyTorchModel from botorch.utils.transforms import t_batch_mode_transform from scipy.stats import norm from torch import Tensor from .lookahead_utils import ( approximate_lookahead_levelset_at_xstar, lookahead_levelset_at_xstar, lookahead_p_at_xstar, ) def Hb(p: Tensor): """ Binary entropy. Args: p: Tensor of probabilities. Returns: Binary entropy for each probability. """ epsilon = torch.tensor(np.finfo(float).eps) p = torch.clamp(p, min=epsilon, max=1 - epsilon) return -torch.nan_to_num(p * torch.log2(p) + (1 - p) * torch.log2(1 - p)) def MI_fn(Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: """ Average mutual information. H(p) - E_y*[H(p | y*)] Args: Px: (b x m) Level-set posterior before observation P1: (b x m) Level-set posterior given observation of 1 P0: (b x m) Level-set posterior given observation of 0 py1: (b x 1) Probability of observing 1 Returns: (b) tensor of mutual information averaged over Xq. """ mi = Hb(Px) - py1 * Hb(P1) - (1 - py1) * Hb(P0) return mi.sum(dim=-1) def ClassErr(p: Tensor) -> Tensor: """ Expected classification error, min(p, 1-p). """ return torch.min(p, 1 - p) def SUR_fn(Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: """ Stepwise uncertainty reduction. Expected reduction in expected classification error given observation at Xstar, averaged over Xq. Args: Px: (b x m) Level-set posterior before observation P1: (b x m) Level-set posterior given observation of 1 P0: (b x m) Level-set posterior given observation of 0 py1: (b x 1) Probability of observing 1 Returns: (b) tensor of SUR values. """ sur = ClassErr(Px) - py1 * ClassErr(P1) - (1 - py1) * ClassErr(P0) return sur.sum(dim=-1) def EAVC_fn(Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: """ Expected absolute value change. Expected absolute change in expected level-set volume given observation at Xstar. Args: Px: (b x m) Level-set posterior before observation P1: (b x m) Level-set posterior given observation of 1 P0: (b x m) Level-set posterior given observation of 0 py1: (b x 1) Probability of observing 1 Returns: (b) tensor of EAVC values. """ avc1 = torch.abs((Px - P1).sum(dim=-1)) avc0 = torch.abs((Px - P0).sum(dim=-1)) return py1.squeeze(-1) * avc1 + (1 - py1).squeeze(-1) * avc0 class LookaheadAcquisitionFunction(AcquisitionFunction): def __init__( self, model: GPyTorchModel, target: Optional[float], lookahead_type: str = "levelset", ) -> None: """ A localized look-ahead acquisition function. Args: model: The gpytorch model. target: Threshold value to target in p-space. """ super().__init__(model=model) if lookahead_type == "levelset": self.lookahead_fn = lookahead_levelset_at_xstar assert target is not None, "Need a target for levelset lookahead!" self.gamma = norm.ppf(target) elif lookahead_type == "posterior": self.lookahead_fn = lookahead_p_at_xstar self.gamma = None else: raise RuntimeError(f"Got unknown lookahead type {lookahead_type}!") ## Local look-ahead acquisitions class LocalLookaheadAcquisitionFunction(LookaheadAcquisitionFunction): def __init__( self, model: GPyTorchModel, lookahead_type: str = "levelset", target: Optional[float] = None, posterior_transform: Optional[PosteriorTransform] = None, ) -> None: """ A localized look-ahead acquisition function. Args: model: The gpytorch model. target: Threshold value to target in p-space. """ super().__init__(model=model, target=target, lookahead_type=lookahead_type) self.posterior_transform = posterior_transform @t_batch_mode_transform(expected_q=1) def forward(self, X: Tensor) -> Tensor: """ Evaluate acquisition function at X. Args: X: (b x 1 x d) point at which to evalaute acquisition function. Returns: (b) tensor of acquisition values. """ Px, P1, P0, py1 = self.lookahead_fn( model=self.model, Xstar=X, Xq=X, gamma=self.gamma, posterior_transform=self.posterior_transform, ) # Return shape here has m=1. return self._compute_acqf(Px, P1, P0, py1) def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: raise NotImplementedError class LocalMI(LocalLookaheadAcquisitionFunction): def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: return MI_fn(Px, P1, P0, py1) class LocalSUR(LocalLookaheadAcquisitionFunction): def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: return SUR_fn(Px, P1, P0, py1) @acqf_input_constructor(LocalMI, LocalSUR) def construct_inputs_local_lookahead( model: GPyTorchModel, training_data, lookahead_type="levelset", target: Optional[float] = None, posterior_transform: Optional[PosteriorTransform] = None, **kwargs, ): return { "model": model, "lookahead_type": lookahead_type, "target": target, "posterior_transform": posterior_transform, } ## Global look-ahead acquisitions class GlobalLookaheadAcquisitionFunction(LookaheadAcquisitionFunction): def __init__( self, model: GPyTorchModel, lookahead_type: str = "levelset", target: Optional[float] = None, posterior_transform: Optional[PosteriorTransform] = None, query_set_size: Optional[int] = 256, Xq: Optional[Tensor] = None, ) -> None: """ A global look-ahead acquisition function. Args: model: The gpytorch model. target: Threshold value to target in p-space. Xq: (m x d) global reference set. """ super().__init__(model=model, target=target, lookahead_type=lookahead_type) self.posterior_transform = posterior_transform assert ( Xq is not None or query_set_size is not None ), "Must pass either query set size or a query set!" if Xq is not None and query_set_size is not None: assert Xq.shape[0] == query_set_size, ( "If passing both Xq and query_set_size," + "first dim of Xq should be query_set_size, got {Xq.shape[0]} != {query_set_size}" ) if Xq is None: # cast to an int in case we got a float from Config, which # would raise on make_scaled_sobol query_set_size = cast(int, query_set_size) # make mypy happy assert int(query_set_size) == query_set_size # make sure casting is safe # if the asserts above pass and Xq is None, query_set_size is not None so this is safe query_set_size = int(query_set_size) # cast Xq = make_scaled_sobol(model.lb, model.ub, query_set_size) self.register_buffer("Xq", Xq) @t_batch_mode_transform(expected_q=1) def forward(self, X: Tensor) -> Tensor: """ Evaluate acquisition function at X. Args: X: (b x 1 x d) point at which to evalaute acquisition function. Returns: (b) tensor of acquisition values. """ Px, P1, P0, py1 = self._get_lookahead_posterior(X) return self._compute_acqf(Px, P1, P0, py1) def _get_lookahead_posterior( self, X: Tensor ) -> Tuple[Tensor, Tensor, Tensor, Tensor]: Xq_batch = self.Xq.expand(X.shape[0], *self.Xq.shape) return self.lookahead_fn( model=self.model, Xstar=X, Xq=Xq_batch, gamma=self.gamma, posterior_transform=self.posterior_transform, ) def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: raise NotImplementedError class GlobalMI(GlobalLookaheadAcquisitionFunction): def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: return MI_fn(Px, P1, P0, py1) class GlobalSUR(GlobalLookaheadAcquisitionFunction): def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: return SUR_fn(Px, P1, P0, py1) class ApproxGlobalSUR(GlobalSUR): def __init__( self, model: GPyTorchModel, lookahead_type="levelset", target: Optional[float] = None, query_set_size: Optional[int] = 256, Xq: Optional[Tensor] = None, ) -> None: assert ( lookahead_type == "levelset" ), f"ApproxGlobalSUR only supports lookahead on level set, got {lookahead_type}!" super().__init__( model=model, target=target, lookahead_type=lookahead_type, query_set_size=query_set_size, Xq=Xq, ) def _get_lookahead_posterior( self, X: Tensor ) -> Tuple[Tensor, Tensor, Tensor, Tensor]: Xq_batch = self.Xq.expand(X.shape[0], *self.Xq.shape) return approximate_lookahead_levelset_at_xstar( model=self.model, Xstar=X, Xq=Xq_batch, gamma=self.gamma, posterior_transform=self.posterior_transform, ) class EAVC(GlobalLookaheadAcquisitionFunction): def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: return EAVC_fn(Px, P1, P0, py1) class MOCU(GlobalLookaheadAcquisitionFunction): """ MOCU acquisition function given in expr. 4 of: Zhao, Guang, et al. "Uncertainty-aware active learning for optimal Bayesian classifier." International Conference on Learning Representations (ICLR) 2021. """ def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: current_max_query = torch.maximum(Px, 1 - Px) # expectation w.r.t. y* of the max of pq lookahead_pq1_max = torch.maximum(P1, 1 - P1) lookahead_pq0_max = torch.maximum(P0, 1 - P0) lookahead_max_query = lookahead_pq1_max * py1 + lookahead_pq0_max * (1 - py1) return (lookahead_max_query - current_max_query).mean(-1) class SMOCU(GlobalLookaheadAcquisitionFunction): """ SMOCU acquisition function given in expr. 11 of: Zhao, Guang, et al. "Bayesian active learning by soft mean objective cost of uncertainty." International Conference on Artificial Intelligence and Statistics (AISTATS) 2021. """ def __init__(self, k, *args, **kwargs): super().__init__(*args, **kwargs) self.k = k def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: stacked = torch.stack((Px, 1 - Px), dim=-1) current_softmax_query = torch.logsumexp(self.k * stacked, dim=-1) / self.k # expectation w.r.t. y* of the max of pq lookahead_pq1_max = torch.maximum(P1, 1 - P1) lookahead_pq0_max = torch.maximum(P0, 1 - P0) lookahead_max_query = lookahead_pq1_max * py1 + lookahead_pq0_max * (1 - py1) return (lookahead_max_query - current_softmax_query).mean(-1) class BEMPS(GlobalLookaheadAcquisitionFunction): """ BEMPS acquisition function given in: Tan, Wei, et al. "Diversity Enhanced Active Learning with Strictly Proper Scoring Rules." Advances in Neural Information Processing Systems 34 (2021). """ def __init__(self, scorefun, *args, **kwargs): super().__init__(*args, **kwargs) self.scorefun = scorefun def _compute_acqf(self, Px: Tensor, P1: Tensor, P0: Tensor, py1: Tensor) -> Tensor: current_score = self.scorefun(Px) lookahead_pq1_score = self.scorefun(P1) lookahead_pq0_score = self.scorefun(P0) lookahead_expected_score = lookahead_pq1_score * py1 + lookahead_pq0_score * ( 1 - py1 ) return (lookahead_expected_score - current_score).mean(-1) @acqf_input_constructor(GlobalMI, GlobalSUR, ApproxGlobalSUR, EAVC, MOCU, SMOCU, BEMPS) def construct_inputs_global_lookahead( model: GPyTorchModel, training_data, lookahead_type="levelset", target: Optional[float] = None, posterior_transform: Optional[PosteriorTransform] = None, query_set_size: Optional[int] = 256, Xq: Optional[Tensor] = None, **kwargs, ): lb = [bounds[0] for bounds in kwargs["bounds"]] ub = [bounds[1] for bounds in kwargs["bounds"]] Xq = Xq if Xq is not None else make_scaled_sobol(lb, ub, query_set_size) return { "model": model, "lookahead_type": lookahead_type, "target": target, "posterior_transform": posterior_transform, "query_set_size": query_set_size, "Xq": Xq, }
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import Optional import torch from botorch.acquisition.acquisition import AcquisitionFunction from botorch.acquisition.objective import IdentityMCObjective, MCAcquisitionObjective from botorch.models.model import Model from torch import Tensor from .rejection_sampler import RejectionSampler class MonotonicMCAcquisition(AcquisitionFunction): """ Acquisition function base class for use with the rejection sampling monotonic GP. This handles the bookkeeping of the derivative constraint points -- implement specific monotonic MC acquisition in subclasses. """ def __init__( self, model: Model, deriv_constraint_points: torch.Tensor, num_samples: int = 32, num_rejection_samples: int = 1024, objective: Optional[MCAcquisitionObjective] = None, ) -> None: """Initialize MonotonicMCAcquisition Args: model (Model): Model to use, usually a MonotonicRejectionGP. num_samples (int, optional): Number of samples to keep from the rejection sampler. . Defaults to 32. num_rejection_samples (int, optional): Number of rejection samples to draw. Defaults to 1024. objective (Optional[MCAcquisitionObjective], optional): Objective transform of the GP output before evaluating the acquisition. Defaults to identity transform. """ super().__init__(model=model) self.deriv_constraint_points = deriv_constraint_points self.num_samples = num_samples self.num_rejection_samples = num_rejection_samples self.sampler_shape = torch.Size([]) if objective is None: assert model.num_outputs == 1 objective = IdentityMCObjective() else: assert isinstance(objective, MCAcquisitionObjective) self.add_module("objective", objective) def forward(self, X: Tensor) -> Tensor: """Evaluate the acquisition function at a set of points. Args: X (Tensor): Points at which to evaluate the acquisition function. Should be (b) x q x d, and q should be 1. Returns: Tensor: Acquisition function value at these points. """ # This is currently doing joint samples over (b), and requiring q=1 # TODO T68656582 support batches properly. if len(X.shape) == 3: assert X.shape[1] == 1, "q must be 1" Xfull = torch.cat((X[:, 0, :], self.deriv_constraint_points), dim=0) else: Xfull = torch.cat((X, self.deriv_constraint_points), dim=0) if not hasattr(self, "sampler") or Xfull.shape != self.sampler_shape: self._set_sampler(X.shape) self.sampler_shape = Xfull.shape posterior = self.model.posterior(Xfull) samples = self.sampler(posterior) assert len(samples.shape) == 3 # Drop derivative samples samples = samples[:, : X.shape[0], :] # NOTE: Squeeze below makes sure that we pass in the same `X` that was used # to generate the `samples`. This is necessitated by `MCAcquisitionObjective`, # which verifies that `samples` and `X` have the same q-batch size. obj_samples = self.objective(samples, X=X.squeeze(-2) if X.ndim == 3 else X) return self.acquisition(obj_samples) def _set_sampler(self, Xshape: torch.Size) -> None: sampler = RejectionSampler( num_samples=self.num_samples, num_rejection_samples=self.num_rejection_samples, constrained_idx=torch.arange( Xshape[0], Xshape[0] + self.deriv_constraint_points.shape[0] ), ) self.add_module("sampler", sampler) def acquisition(self, obj_samples: torch.Tensor) -> torch.Tensor: raise NotImplementedError class MonotonicMCLSE(MonotonicMCAcquisition): def __init__( self, model: Model, deriv_constraint_points: torch.Tensor, target: float, num_samples: int = 32, num_rejection_samples: int = 1024, beta: float = 3.84, objective: Optional[MCAcquisitionObjective] = None, ) -> None: """Level set estimation acquisition function for use with monotonic models. Args: model (Model): Underlying model object, usually should be MonotonicRejectionGP. target (float): Level set value to target (after the objective). num_samples (int, optional): Number of MC samples to draw in MC acquisition. Defaults to 32. num_rejection_samples (int, optional): Number of rejection samples from which to subsample monotonic ones. Defaults to 1024. beta (float, optional): Parameter of the LSE acquisition function that governs exploration vs exploitation (similarly to the same parameter in UCB). Defaults to 3.84 (1.96 ** 2), which maps to the straddle heuristic of Bryan et al. 2005. objective (Optional[MCAcquisitionObjective], optional): Objective transform. Defaults to identity transform. """ self.beta = beta self.target = target super().__init__( model=model, deriv_constraint_points=deriv_constraint_points, num_samples=num_samples, num_rejection_samples=num_rejection_samples, objective=objective, ) def acquisition(self, obj_samples: torch.Tensor) -> torch.Tensor: mean = obj_samples.mean(dim=0) variance = obj_samples.var(dim=0) # prevent numerical issues if probit makes all the values 1 or 0 variance = torch.clamp(variance, min=1e-5) delta = torch.sqrt(self.beta * variance) return delta - torch.abs(mean - self.target)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import Optional import torch from botorch.acquisition.objective import MCAcquisitionObjective from torch import Tensor from torch.distributions.normal import Normal class AEPsychObjective(MCAcquisitionObjective): def inverse(self, samples: Tensor, X: Optional[Tensor] = None) -> Tensor: raise NotImplementedError class ProbitObjective(AEPsychObjective): """Probit objective Transforms the input through the normal CDF (probit). """ def forward(self, samples: Tensor, X: Optional[Tensor] = None) -> Tensor: """Evaluates the objective (normal CDF). Args: samples (Tensor): GP samples. X (Optional[Tensor], optional): ignored, here for compatibility with MCAcquisitionObjective. Returns: Tensor: [description] """ return Normal(loc=0, scale=1).cdf(samples.squeeze(-1)) def inverse(self, samples: Tensor, X: Optional[Tensor] = None) -> Tensor: """Evaluates the inverse of the objective (normal PPF). Args: samples (Tensor): GP samples. X (Optional[Tensor], optional): ignored, here for compatibility with MCAcquisitionObjective. Returns: Tensor: [description] """ return Normal(loc=0, scale=1).icdf(samples.squeeze(-1)) class FloorLinkObjective(AEPsychObjective): """ Wrapper for objectives to add a floor, when the probability is known not to go below it. """ def __init__(self, floor=0.5): self.floor = floor super().__init__() def forward(self, samples: Tensor, X: Optional[Tensor] = None) -> Tensor: """Evaluates the objective for input x and floor f Args: samples (Tensor): GP samples. X (Optional[Tensor], optional): ignored, here for compatibility with MCAcquisitionObjective. Returns: Tensor: outcome probability. """ return self.link(samples.squeeze(-1)) * (1 - self.floor) + self.floor def inverse(self, samples: Tensor, X: Optional[Tensor] = None) -> Tensor: """Evaluates the inverse of the objective. Args: samples (Tensor): GP samples. X (Optional[Tensor], optional): ignored, here for compatibility with MCAcquisitionObjective. Returns: Tensor: [description] """ return self.inverse_link((samples - self.floor) / (1 - self.floor)) def link(self, samples): raise NotImplementedError def inverse_link(self, samples): raise NotImplementedError @classmethod def from_config(cls, config): floor = config.getfloat(cls.__name__, "floor") return cls(floor=floor) class FloorLogitObjective(FloorLinkObjective): """ Logistic sigmoid (aka expit, aka logistic CDF), but with a floor so that its output is between floor and 1.0. """ def link(self, samples): return torch.special.expit(samples) def inverse_link(self, samples): return torch.special.logit(samples) class FloorGumbelObjective(FloorLinkObjective): """ Gumbel CDF but with a floor so that its output is between floor and 1.0. Note that this is not the standard Gumbel distribution, but rather the left-skewed Gumbel that arises as the log of the Weibull distribution, e.g. Treutwein 1995, doi:10.1016/0042-6989(95)00016-X. """ def link(self, samples): return torch.nan_to_num( -torch.special.expm1(-torch.exp(samples)), posinf=1.0, neginf=0.0 ) def inverse_link(self, samples): return torch.log(-torch.special.log1p(-samples)) class FloorProbitObjective(FloorLinkObjective): """ Probit (aka Gaussian CDF), but with a floor so that its output is between floor and 1.0. """ def link(self, samples): return Normal(0, 1).cdf(samples) def inverse_link(self, samples): return Normal(0, 1).icdf(samples)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import Optional import torch from aepsych.config import Config from aepsych.likelihoods import LinearBernoulliLikelihood from botorch.acquisition.objective import MCAcquisitionObjective from gpytorch.likelihoods import Likelihood from torch import Tensor class SemiPObjectiveBase(MCAcquisitionObjective): """Wraps the semi-parametric transform into an objective that correctly extracts various things """ # because we have an extra dim for the SemiP batch dimension, # all the q-batch output shape checks fail, disable them here _verify_output_shape: bool = False def __init__(self, stim_dim: int = 0): super().__init__() self.stim_dim = stim_dim class SemiPProbabilityObjective(SemiPObjectiveBase): """Wraps the semi-parametric transform into an objective that gives outcome probabilities """ def __init__(self, likelihood: Likelihood = None, *args, **kwargs): """Evaluates the probability objective. Args: likelihood (Likelihood). Underlying SemiP likelihood (which we use for its objective/link) other arguments are passed to the base class (notably, stim_dim). """ super().__init__(*args, **kwargs) self.likelihood = likelihood or LinearBernoulliLikelihood() def forward(self, samples: Tensor, X: Tensor) -> Tensor: """Evaluates the probability objective. Args: samples (Tensor): GP samples. X (Tensor): Inputs at which to evaluate objective. Unlike most AEPsych objectives, we need X here to split out the intensity dimension. Returns: Tensor: Response probabilities at the specific X values and function samples. """ Xi = X[..., self.stim_dim] # the output of LinearBernoulliLikelihood is (nsamp x b x n x 1) # but the output of MCAcquisitionObjective should be `nsamp x *batch_shape x q` # so we remove the final dim return self.likelihood.p(function_samples=samples, Xi=Xi).squeeze(-1) @classmethod def from_config(cls, config: Config): classname = cls.__name__ likelihood_cls = config.getobj(classname, "likelihood", fallback=None) if likelihood_cls is not None: if hasattr(likelihood_cls, "from_config"): likelihood = likelihood_cls.from_config(config) else: likelihood = likelihood_cls() else: likelihood = None # fall back to __init__ default return cls(likelihood=likelihood) class SemiPThresholdObjective(SemiPObjectiveBase): """Wraps the semi-parametric transform into an objective that gives the threshold distribution. """ def __init__(self, target: float, likelihood=None, *args, **kwargs): """Evaluates the probability objective. Args: target (float): the threshold to evaluate. likelihood (Likelihood): Underlying SemiP likelihood (which we use for its inverse link) other arguments are passed to the base class (notably, stim_dim). """ super().__init__(*args, **kwargs) self.likelihood = likelihood or LinearBernoulliLikelihood() self.fspace_target = self.likelihood.objective.inverse(torch.tensor(target)) def forward(self, samples: Tensor, X: Optional[Tensor] = None) -> Tensor: """Evaluates the probability objective. Args: samples (Tensor): GP samples. X (Tensor, optional): Ignored, here for compatibility with the objective API. Returns: Tensor: Threshold probabilities at the specific GP sample values. """ offset = samples[..., 0, :] slope = samples[..., 1, :] return (self.fspace_target + slope * offset) / slope @classmethod def from_config(cls, config: Config): classname = cls.__name__ likelihood_cls = config.getobj(classname, "likelihood", fallback=None) if likelihood_cls is not None: if hasattr(likelihood_cls, "from_config"): likelihood = likelihood_cls.from_config(config) else: likelihood = likelihood_cls() else: likelihood = None # fall back to __init__ default target = config.getfloat(classname, "target", fallback=0.75) return cls(likelihood=likelihood, target=target)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import sys from ...config import Config from .objective import ( AEPsychObjective, FloorGumbelObjective, FloorLogitObjective, FloorProbitObjective, ProbitObjective, ) from .semi_p import SemiPProbabilityObjective, SemiPThresholdObjective __all__ = [ "AEPsychObjective", "FloorGumbelObjective", "FloorLogitObjective", "FloorProbitObjective", "ProbitObjective", "SemiPProbabilityObjective", "SemiPThresholdObjective", ] Config.register_module(sys.modules[__name__])
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree.
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import torch from gpytorch.means.constant_mean import ConstantMean class ConstantMeanPartialObsGrad(ConstantMean): """A mean function for use with partial gradient observations. This follows gpytorch.means.constant_mean_grad and sets the prior mean for derivative observations to 0, though unlike that function it allows for partial observation of derivatives. The final column of input should be an index that is 0 if the observation is of f, or i if it is of df/dxi. """ def forward(self, input: torch.Tensor) -> torch.Tensor: idx = input[..., -1].to(dtype=torch.long) > 0 mean_fit = super(ConstantMeanPartialObsGrad, self).forward(input[..., ~idx, :]) sz = mean_fit.shape[:-1] + torch.Size([input.shape[-2]]) mean = torch.zeros(sz) mean[~idx] = mean_fit return mean
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import io import logging import os import sys import threading import traceback import warnings from typing import Optional import aepsych.database.db as db import aepsych.utils_logging as utils_logging import dill import numpy as np import pandas as pd import torch from aepsych.server.message_handlers import MESSAGE_MAP from aepsych.server.message_handlers.handle_ask import ask from aepsych.server.message_handlers.handle_setup import configure from aepsych.server.replay import ( get_dataframe_from_replay, get_strat_from_replay, get_strats_from_replay, replay, ) from aepsych.server.sockets import BAD_REQUEST, DummySocket, PySocket logger = utils_logging.getLogger(logging.INFO) DEFAULT_DESC = "default description" DEFAULT_NAME = "default name" def get_next_filename(folder, fname, ext): """Generates appropriate filename for logging purposes.""" n = sum(1 for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))) return f"{folder}/{fname}_{n+1}.{ext}" class AEPsychServer(object): def __init__(self, socket=None, database_path=None): """Server for doing black box optimization using gaussian processes. Keyword Arguments: socket -- socket object that implements `send` and `receive` for json messages (default: DummySocket()). TODO actually make an abstract interface to subclass from here """ if socket is None: self.socket = DummySocket() else: self.socket = socket self.db = None self.is_performing_replay = False self.exit_server_loop = False self._db_master_record = None self._db_raw_record = None self.db = db.Database(database_path) self.skip_computations = False self.strat_names = None if self.db.is_update_required(): self.db.perform_updates() self._strats = [] self._parnames = [] self._configs = [] self.strat_id = -1 self._pregen_asks = [] self.enable_pregen = False self.debug = False self.receive_thread = threading.Thread( target=self._receive_send, args=(self.exit_server_loop,), daemon=True ) self.queue = [] def cleanup(self): """Close the socket and terminate connection to the server. Returns: None """ self.socket.close() def _receive_send(self, is_exiting: bool) -> None: """Receive messages from the client. Args: is_exiting (bool): True to terminate reception of new messages from the client, False otherwise. Returns: None """ while True: request = self.socket.receive(is_exiting) if request != BAD_REQUEST: self.queue.append(request) if self.exit_server_loop: break logger.info("Terminated input thread") def _handle_queue(self) -> None: """Handles the queue of messages received by the server. Returns: None """ if self.queue: request = self.queue.pop(0) try: result = self.handle_request(request) except Exception as e: error_message = f"Request '{request}' raised error '{e}'!" result = f"server_error, {error_message}" logger.error(f"{error_message}! Full traceback follows:") logger.error(traceback.format_exc()) self.socket.send(result) else: if self.can_pregen_ask and (len(self._pregen_asks) == 0): self._pregen_asks.append(ask(self)) def serve(self) -> None: """Run the server. Note that all configuration outside of socket type and port happens via messages from the client. The server simply forwards messages from the client to its `setup`, `ask` and `tell` methods, and responds with either acknowledgment or other response as needed. To understand the server API, see the docs on the methods in this class. Returns: None Raises: RuntimeError: if a request from a client has no request type RuntimeError: if a request from a client has no known request type TODO make things a little more robust to bad messages from client; this requires resetting the req/rep queue status. """ logger.info("Server up, waiting for connections!") logger.info("Ctrl-C to quit!") # yeah we're not sanitizing input at all # Start the method to accept a client connection self.socket.accept_client() self.receive_thread.start() while True: self._handle_queue() if self.exit_server_loop: break # Close the socket and terminate with code 0 self.cleanup() sys.exit(0) def _unpack_strat_buffer(self, strat_buffer): if isinstance(strat_buffer, io.BytesIO): strat = torch.load(strat_buffer, pickle_module=dill) strat_buffer.seek(0) elif isinstance(strat_buffer, bytes): warnings.warn( "Strat buffer is not in bytes format!" + " This is a deprecated format, loading using dill.loads.", DeprecationWarning, ) strat = dill.loads(strat_buffer) else: raise RuntimeError("Trying to load strat in unknown format!") return strat def generate_experiment_table( self, experiment_id: str, table_name: str = "experiment_table", return_df: bool = False, ) -> Optional[pd.DataFrame]: """Generate a table of a given experiment with all the raw data. This table is generated from the database, and is added to the experiment's database. Args: experiment_id (str): The experiment ID to generate the table for. table_name (str): The name of the table. Defaults to "experiment_table". return_df (bool): If True, also return the dataframe. Returns: pd.DataFrame: The dataframe of the experiment table, if return_df is True. """ param_space = self.db.get_param_for(experiment_id, 1) outcome_space = self.db.get_outcome_for(experiment_id, 1) columns = [] columns.append("iteration_id") for param in param_space: columns.append(param.param_name) for outcome in outcome_space: columns.append(outcome.outcome_name) columns.append("timestamp") # Create dataframe df = pd.DataFrame(columns=columns) # Fill dataframe for raw in self.db.get_raw_for(experiment_id): row = {} row["iteration_id"] = raw.unique_id for param in raw.children_param: row[param.param_name] = param.param_value for outcome in raw.children_outcome: row[outcome.outcome_name] = outcome.outcome_value row["timestamp"] = raw.timestamp # concat to dataframe df = pd.concat([df, pd.DataFrame([row])], ignore_index=True) # Make iteration_id the index df.set_index("iteration_id", inplace=True) # Save to .db file df.to_sql(table_name, self.db.get_engine(), if_exists="replace") if return_df: return df else: return None ### Properties that are set on a per-strat basis @property def strat(self): if self.strat_id == -1: return None else: return self._strats[self.strat_id] @strat.setter def strat(self, s): self._strats.append(s) @property def config(self): if self.strat_id == -1: return None else: return self._configs[self.strat_id] @config.setter def config(self, s): self._configs.append(s) @property def parnames(self): if self.strat_id == -1: return [] else: return self._parnames[self.strat_id] @parnames.setter def parnames(self, s): self._parnames.append(s) @property def n_strats(self): return len(self._strats) @property def can_pregen_ask(self): return self.strat is not None and self.enable_pregen def _tensor_to_config(self, next_x): config = {} for name, val in zip(self.parnames, next_x): if val.dim() == 0: config[name] = [float(val)] else: config[name] = np.array(val) return config def _config_to_tensor(self, config): unpacked = [config[name] for name in self.parnames] # handle config elements being either scalars or length-1 lists if isinstance(unpacked[0], list): x = torch.tensor(np.stack(unpacked, axis=0)).squeeze(-1) else: x = torch.tensor(np.stack(unpacked)) return x def __getstate__(self): # nuke the socket since it's not pickleble state = self.__dict__.copy() del state["socket"] del state["db"] return state def write_strats(self, termination_type): if self._db_master_record is not None and self.strat is not None: logger.info(f"Dumping strats to DB due to {termination_type}.") for strat in self._strats: buffer = io.BytesIO() torch.save(strat, buffer, pickle_module=dill) buffer.seek(0) self.db.record_strat(master_table=self._db_master_record, strat=buffer) def generate_debug_info(self, exception_type, dumptype): fname = get_next_filename(".", dumptype, "pkl") logger.exception(f"Got {exception_type}, exiting! Server dump in {fname}") dill.dump(self, open(fname, "wb")) def handle_request(self, request): if "type" not in request.keys(): raise RuntimeError(f"Request {request} contains no request type!") else: type = request["type"] if type in MESSAGE_MAP.keys(): logger.info(f"Received msg [{type}]") ret_val = MESSAGE_MAP[type](self, request) return ret_val else: exception_message = ( f"unknown type: {type}. Allowed types [{MESSAGE_MAP.keys()}]" ) raise RuntimeError(exception_message) def replay(self, uuid_to_replay, skip_computations=False): return replay(self, uuid_to_replay, skip_computations) def get_strats_from_replay(self, uuid_of_replay=None, force_replay=False): return get_strats_from_replay(self, uuid_of_replay, force_replay) def get_strat_from_replay(self, uuid_of_replay=None, strat_id=-1): return get_strat_from_replay(self, uuid_of_replay, strat_id) def get_dataframe_from_replay(self, uuid_of_replay=None, force_replay=False): return get_dataframe_from_replay(self, uuid_of_replay, force_replay) #! THIS IS WHAT START THE SERVER def startServerAndRun( server_class, socket=None, database_path=None, config_path=None, uuid_of_replay=None ): server = server_class(socket=socket, database_path=database_path) try: if config_path is not None: with open(config_path) as f: config_str = f.read() configure(server, config_str=config_str) if socket is not None: if uuid_of_replay is not None: server.replay(uuid_of_replay, skip_computations=True) server._db_master_record = server.db.get_master_record(uuid_of_replay) server.serve() else: if config_path is not None: logger.info( "You have passed in a config path but this is a replay. If there's a config in the database it will be used instead of the passed in config path." ) server.replay(uuid_of_replay) except KeyboardInterrupt: exception_type = "CTRL+C" dump_type = "dump" server.write_strats(exception_type) server.generate_debug_info(exception_type, dump_type) except RuntimeError as e: exception_type = "RuntimeError" dump_type = "crashdump" server.write_strats(exception_type) server.generate_debug_info(exception_type, dump_type) raise RuntimeError(e) def parse_argument(): parser = argparse.ArgumentParser(description="AEPsych Server!") parser.add_argument( "--port", metavar="N", type=int, default=5555, help="port to serve on" ) parser.add_argument( "--ip", metavar="M", type=str, default="0.0.0.0", help="ip to bind", ) parser.add_argument( "-s", "--stratconfig", help="Location of ini config file for strat", type=str, ) parser.add_argument( "--logs", type=str, help="The logs path to use if not the default (./logs).", default="logs", ) parser.add_argument( "-d", "--db", type=str, help="The database to use if not the default (./databases/default.db).", default=None, ) parser.add_argument( "-r", "--replay", type=str, help="UUID of the experiment to replay." ) parser.add_argument( "-m", "--resume", action="store_true", help="Resume server after replay." ) args = parser.parse_args() return args def start_server(server_class, args): logger.info("Starting the AEPsychServer") try: if "db" in args and args.db is not None: database_path = args.db if "replay" in args and args.replay is not None: logger.info(f"Attempting to replay {args.replay}") if args.resume is True: sock = PySocket(port=args.port) logger.info(f"Will resume {args.replay}") else: sock = None startServerAndRun( server_class, socket=sock, database_path=database_path, uuid_of_replay=args.replay, config_path=args.stratconfig, ) else: logger.info(f"Setting the database path {database_path}") sock = PySocket(port=args.port) startServerAndRun( server_class, database_path=database_path, socket=sock, config_path=args.stratconfig, ) else: sock = PySocket(port=args.port) startServerAndRun(server_class, socket=sock, config_path=args.stratconfig) except (KeyboardInterrupt, SystemExit): logger.exception("Got Ctrl+C, exiting!") sys.exit() except RuntimeError as e: fname = get_next_filename(".", "dump", "pkl") logger.exception(f"CRASHING!! dump in {fname}") raise RuntimeError(e) def main(server_class=AEPsychServer): args = parse_argument() if args.logs: # overide logger path log_path = args.logs logger = utils_logging.getLogger(logging.DEBUG, log_path) logger.info(f"Saving logs to path: {log_path}") start_server(server_class, args) if __name__ == "__main__": main(AEPsychServer)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from .server import AEPsychServer __all__ = ["AEPsychServer"]
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import logging import warnings import aepsych.utils_logging as utils_logging import pandas as pd from aepsych.server.message_handlers.handle_tell import flatten_tell_record logger = utils_logging.getLogger(logging.INFO) def replay(server, uuid_to_replay, skip_computations=False): """ Run a replay against the server. The UUID will be looked up in the database. if skip_computations is true, skip all the asks and queries, which should make the replay much faster. """ if uuid_to_replay is None: raise RuntimeError("UUID is a required parameter to perform a replay") if server.db is None: raise RuntimeError("A database is required to perform a replay") if skip_computations is True: logger.info( "skip_computations=True, make sure to refit the final strat before doing anything!" ) master_record = server.db.get_master_record(uuid_to_replay) if master_record is None: raise RuntimeError( f"The UUID {uuid_to_replay} isn't in the database. Unable to perform replay." ) # this prevents writing back to the DB and creating a circular firing squad server.is_performing_replay = True server.skip_computations = skip_computations for result in master_record.children_replay: request = result.message_contents logger.debug(f"replay - type = {result.message_type} request = {request}") server.handle_request(request) def get_strats_from_replay(server, uuid_of_replay=None, force_replay=False): if uuid_of_replay is None: records = server.db.get_master_records() if len(records) > 0: uuid_of_replay = records[-1].experiment_id else: raise RuntimeError("Server has no experiment records!") if force_replay: warnings.warn( "Force-replaying to get non-final strats is deprecated after the ability" + " to save all strats was added, and will eventually be removed.", DeprecationWarning, ) replay(server, uuid_of_replay, skip_computations=True) for strat in server._strats: if strat.has_model: strat.model.fit(strat.x, strat.y) return server._strats else: strat_buffers = server.db.get_strats_for(uuid_of_replay) return [server._unpack_strat_buffer(sb) for sb in strat_buffers] def get_strat_from_replay(server, uuid_of_replay=None, strat_id=-1): if uuid_of_replay is None: records = server.db.get_master_records() if len(records) > 0: uuid_of_replay = records[-1].experiment_id else: raise RuntimeError("Server has no experiment records!") strat_buffer = server.db.get_strat_for(uuid_of_replay, strat_id) if strat_buffer is not None: return server._unpack_strat_buffer(strat_buffer) else: warnings.warn( "No final strat found (likely due to old DB," + " trying to replay tells to generate a final strat. Note" + " that this fallback will eventually be removed!", DeprecationWarning, ) # sometimes there's no final strat, e.g. if it's a very old database # (we dump strats on crash) in this case, replay the setup and tells replay(server, uuid_of_replay, skip_computations=True) # then if the final strat is model-based, refit strat = server._strats[strat_id] if strat.has_model: strat.model.fit(strat.x, strat.y) return strat def get_dataframe_from_replay(server, uuid_of_replay=None, force_replay=False): warnings.warn( "get_dataframe_from_replay is deprecated." + " Use generate_experiment_table with return_df = True instead.", DeprecationWarning, stacklevel=2, ) if uuid_of_replay is None: records = server.db.get_master_records() if len(records) > 0: uuid_of_replay = records[-1].experiment_id else: raise RuntimeError("Server has no experiment records!") recs = server.db.get_replay_for(uuid_of_replay) strats = get_strats_from_replay(server, uuid_of_replay, force_replay=force_replay) out = pd.DataFrame( [flatten_tell_record(server, rec) for rec in recs if rec.message_type == "tell"] ) # flatten any final nested lists def _flatten(x): return x[0] if len(x) == 1 else x for col in out.columns: if out[col].dtype == object: out.loc[:, col] = out[col].apply(_flatten) n_tell_records = len(out) n_strat_datapoints = 0 post_means = [] post_vars = [] # collect posterior means and vars for strat in strats: if strat.has_model: post_mean, post_var = strat.predict(strat.x) n_tell_records = len(out) n_strat_datapoints += len(post_mean) post_means.extend(post_mean.detach().numpy()) post_vars.extend(post_var.detach().numpy()) if n_tell_records == n_strat_datapoints: out["post_mean"] = post_means out["post_var"] = post_vars else: logger.warn( f"Number of tell records ({n_tell_records}) does not match " + f"number of datapoints in strat ({n_strat_datapoints}) " + "cowardly refusing to populate GP mean and var to dataframe!" ) return out
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import logging import os import sys import aepsych.database.db as db import aepsych.utils_logging as utils_logging logger = utils_logging.getLogger(logging.INFO) def get_next_filename(folder, fname, ext): n = sum(1 for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))) return f"{folder}/{fname}_{n+1}.{ext}" def parse_argument(): parser = argparse.ArgumentParser(description="AEPsych Database!") parser.add_argument( "-l", "--list", help="Lists available experiments in the database.", action="store_true", ) parser.add_argument( "-d", "--db", type=str, help="The database to use if not the default (./databases/default.db).", default=None, ) parser.add_argument( "-u", "--update", action="store_true", help="Update the database tables with the most recent columns and tables.", ) args = parser.parse_args() return args def run_database(args): logger.info("Starting AEPsych Database!") try: database_path = args.db database = db.Database(database_path) if args.list is True: database.list_master_records() elif "update" in args and args.update: logger.info(f"Updating the database {database_path}") if database.is_update_required(): database.perform_updates() logger.info(f"- updated database {database_path}") else: logger.info(f"- update not needed for database {database_path}") except (KeyboardInterrupt, SystemExit): logger.exception("Got Ctrl+C, exiting!") sys.exit() except RuntimeError as e: fname = get_next_filename(".", "dump", "pkl") logger.exception(f"CRASHING!! dump in {fname}") raise RuntimeError(e) def main(): args = parse_argument() run_database(args) if __name__ == "__main__": main()
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import json import logging import select import socket import sys import aepsych.utils_logging as utils_logging import numpy as np logger = utils_logging.getLogger(logging.INFO) BAD_REQUEST = "bad request" def SimplifyArrays(message): return { k: v.tolist() if type(v) == np.ndarray else SimplifyArrays(v) if type(v) is dict else v for k, v in message.items() } class DummySocket(object): def close(self): pass class PySocket(object): def __init__(self, port, ip=""): addr = (ip, port) # all interfaces if socket.has_dualstack_ipv6(): self.socket = socket.create_server( addr, family=socket.AF_INET6, dualstack_ipv6=True ) else: self.socket = socket.create_server(addr) self.conn, self.addr = None, None def close(self): self.socket.close() def return_socket(self): return self.socket def accept_client(self): client_not_connected = True logger.info("Waiting for connection...") while client_not_connected: rlist, wlist, xlist = select.select([self.socket], [], [], 0) if rlist: for sock in rlist: try: self.conn, self.addr = sock.accept() logger.info( f"Connected by {self.addr}, waiting for messages..." ) client_not_connected = False except Exception as e: logger.info(f"Connection to client failed with error {e}") raise Exception def receive(self, server_exiting): while not server_exiting: rlist, wlist, xlist = select.select( [self.conn], [], [], 0 ) # 0 Here is the timeout. It makes the server constantly poll for output. Timeout can be added to save CPU usage. # rlist,wlist,xlist represent lists of sockets to check against. Rlist is sockets to read from, wlist is sockets to write to, xlist is sockets to listen to for errors. for sock in rlist: try: if rlist: recv_result = sock.recv( 1024 * 512 ) # 1024 * 512 is the max size of the message msg = json.loads(recv_result) logger.debug(f"receive : result = {recv_result}") logger.info(f"Got: {msg}") return msg except Exception: return BAD_REQUEST def send(self, message): if self.conn is None: logger.error("No connection to send to!") return if type(message) == str: pass # keep it as-is elif type(message) == int: message = str(message) else: message = json.dumps(SimplifyArrays(message)) logger.info(f"Sending: {message}") sys.stdout.flush() self.conn.sendall(bytes(message, "utf-8"))