├── .gitignore ├── DVS128_DataModule.py ├── LICENSE ├── README.md ├── data_generation.py ├── dataset_scripts ├── asl.py ├── caltech_101.py ├── dvs128.py ├── dvs128_split_dataset.py └── sl_animals.py ├── evaluation_stats.py ├── evaluation_utils.py ├── model_overview_v6.png ├── models ├── EvT.py └── positional_encoding.py ├── requirements.txt ├── train.py ├── trainer.py └── training_utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /DVS128_DataModule.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Apr 27 17:26:41 2021 5 | 6 | @author: asabater 7 | """ 8 | 9 | from torch.utils.data import Dataset, DataLoader 10 | from pytorch_lightning import LightningDataModule 11 | import torch 12 | # from torch.nn.utils.rnn import pad_sequence 13 | 14 | import os 15 | import pickle 16 | import numpy as np 17 | import json 18 | from skimage.util import view_as_blocks 19 | import copy 20 | from scipy import ndimage 21 | 22 | 23 | class_mapping = {0: 'background', 1: 'hand_clapping', 2: 'right_hand_wave', 24 | 3: 'left_hand_wave', 4: 'right_arm_clockwise', 25 | 5: 'right_arm_counter_clockwise', 6: 'left_arm_clockwise', 26 | 7: 'left_arm_counter_clockwise', 8: 'arm_roll', 27 | 9: 'air_drums', 10: 'air_guitar', 11: 'other_gestures'} 28 | 29 | 30 | # - TODO: split event sequences by chunks 31 | # - TODO: zero-pad chunks 32 | # - TODO: zero-pad batches 33 | # TODO: ensure events sorted by time 34 | 35 | # - TODO: remove last chunk (not complete) 36 | # - TODO: create chunks by filtering the array, not iterating over events. -> move array to torch tensor 37 | 38 | # TODO: BatchSampler -> generates indices per batch. Create custom para samplear por class y duplicados (anchoring) 39 | # TODO: change all the np.random to torch.random 40 | 41 | # class DVS128Dataset(Dataset): 42 | # def __init__(self, samples_folder, chunk_len_ms, height=128, width=128, 43 | # skip_last_event=False, classes_to_exclude=[], transform=None): 44 | 45 | # self.samples_folder = samples_folder 46 | # self.chunk_len_ms = chunk_len_ms 47 | # self.chunk_len_us = chunk_len_ms*1000 48 | # self.height = height 49 | # self.width = width 50 | # self.skip_last_event = skip_last_event 51 | # self.transform = transform 52 | 53 | # self.samples = os.listdir(samples_folder) 54 | # for l in classes_to_exclude: 55 | # self.samples = [ s for s in self.samples if '_label{:02}'.format(l) not in s ] 56 | 57 | # self.labels = np.array([ int(t[5:7]) for s in self.samples for t in s.split('_') if 'label' in t ]).astype('int8') 58 | # unique_labels = { l:i for i,l in enumerate(set(self.labels)) } 59 | # self.labels = [ unique_labels[l] for l in self.labels ] 60 | # self.num_classes = len(unique_labels) 61 | 62 | # def __len__(self): 63 | # return len(self.samples) 64 | 65 | # def get_label_dict(self): 66 | # label_dict = { c:[] for c in set(self.labels) } 67 | # for i,l in enumerate(self.labels): label_dict[l].append(i) 68 | # for k in label_dict: label_dict[k] = torch.IntTensor(label_dict[k]) 69 | # return label_dict 70 | 71 | # # event_chunk -> [N, 4], [x, y, t, p] x N -> (p0,p1) x N, (x,y) x N 72 | # def aggregate_events_array_per_pixel(self, event_chunk): 73 | # # [N, 2] -> (pixel_num, p) x N 74 | # polarity = torch.nn.functional.one_hot(event_chunk[:,3].long(), num_classes=2) 75 | # # (N) 76 | # pixels = event_chunk[:,0] + event_chunk[:,1]*self.width 77 | 78 | # # Aggreagate by pixels and count polarities 79 | # unique_pixels, pixel_inds = pixels.unique(dim=0, return_inverse=True) 80 | # pixel_inds = pixel_inds.view(pixels.size(0), 1).expand(-1, polarity.size(1)) 81 | # unique_pixels = unique_pixels.view(unique_pixels.size(0), 1).expand(-1, polarity.size(1)) 82 | # agg_polarity_pixel_count = torch.zeros_like(unique_pixels, dtype=torch.long).scatter_add_(0, pixel_inds, polarity) 83 | 84 | # # Transform unique pixels to x/y 85 | # unique_pixels = torch.column_stack([torch.remainder(unique_pixels[:,0], self.width), unique_pixels[:,0] // self.width]) 86 | 87 | # return agg_polarity_pixel_count, unique_pixels 88 | 89 | # # Split events into chunks 90 | # def get_total_chunks_by_iteration(self, total_events): 91 | # total_chunks = []; init_t = total_events[0][2]; curr_chunk = [] 92 | # for e in total_events: 93 | # if init_t + self.chunk_len_us < e[2]: 94 | # total_chunks.append(torch.stack(curr_chunk, axis=0)) 95 | # curr_chunk, init_t = [], e[2] 96 | # curr_chunk.append(e) 97 | # if not self.skip_last_event: 98 | # total_chunks.append(torch.stack(curr_chunk, axis=0)) 99 | # curr_chunk = [] 100 | # return total_chunks 101 | # def get_total_chunks_by_filtering(self, total_events): 102 | # total_chunks = [] 103 | # while total_events.shape[0] > 0: 104 | # init_t = total_events[0][2] 105 | # chunk_inds = torch.where(total_events[:,2] <= init_t + self.chunk_len_us) 106 | # total_chunks.append(total_events[chunk_inds]) 107 | # total_events = total_events[chunk_inds[0].max()+1:] 108 | # return total_chunks 109 | # def extract_chunk_data(self, total_chunks): 110 | # chunk_data = [ self.aggregate_events_array_per_pixel(curr_chunk) for curr_chunk in total_chunks ] 111 | # return [ cd[0] for cd in chunk_data ], [ cd[1] for cd in chunk_data ] 112 | 113 | # def __getitem__(self, idx): 114 | # filename = self.samples[idx] 115 | # label = self.labels[idx] 116 | 117 | # total_events = pickle.load(open(os.path.join(self.samples_folder + filename), 'rb')) # (events, label) 118 | # # total_events = total_events[0] # (x,y,t,p) 119 | # total_events = torch.Tensor(total_events[0].astype('int32')) # (x,y,t,p) 120 | 121 | # if self.transform: 122 | # # sample = self.transform(sample) 123 | # raise ValueError('Transformations not implemented') 124 | 125 | # else: 126 | 127 | # # total_chunks = self.get_total_chunks_by_iteration(total_events) # 15.18s 128 | # total_chunks = self.get_total_chunks_by_filtering(total_events) # 404.74ms 129 | # total_polarity, total_pixels = self.extract_chunk_data(total_chunks) # 4.93 ms 130 | 131 | 132 | # return total_polarity, total_pixels, label 133 | 134 | 135 | class DVS128Dataset_from_frames(Dataset): 136 | def __init__(self, samples_folder, chunk_len_ms, 137 | validation, 138 | # max_sample_len_ms = -1, 139 | augmentation_params, 140 | preproc_polarity, patch_size, min_activations_per_patch, 141 | bins, 142 | min_patches_per_chunk, min_events_per_chunk, num_extra_chunks, 143 | dataset_name, height, width, 144 | classes_to_exclude=[]): 145 | 146 | print(' * Creating DVS128Dataset_from_frames. Validation:', validation) 147 | 148 | self.samples_folder = samples_folder 149 | self.validation = validation 150 | self.chunk_len_ms = chunk_len_ms 151 | self.chunk_len_us = chunk_len_ms*1000 152 | 153 | self.sparse_frame_len_us = int(self.samples_folder.split('/')[-3].split('_')[-1]) # len of each loaded sparse frame 154 | self.sparse_frame_len_ms = self.sparse_frame_len_us // 1000 155 | assert self.chunk_len_us % self.sparse_frame_len_us == 0 156 | self.chunk_size = self.chunk_len_us // self.sparse_frame_len_us # Size of the grouped frame chunks 157 | 158 | self.height = height 159 | self.width = width 160 | self.min_patches_per_chunk = min_patches_per_chunk 161 | self.min_events_per_chunk = min_events_per_chunk 162 | self.num_extra_chunks = num_extra_chunks 163 | 164 | # Define data augmentation functions 165 | print(augmentation_params, 'max_sample_len_ms' in augmentation_params, augmentation_params['max_sample_len_ms'] != -1) 166 | # self.crop_in_time, self.crop_in_space, self.drop_token, self.random_shift, self.crop_events = None, None, None, None, None 167 | self.augmentation_params = augmentation_params 168 | if augmentation_params is not None and len(augmentation_params) != 0: 169 | if 'max_sample_len_ms' in augmentation_params and augmentation_params['max_sample_len_ms'] != -1: 170 | # assert augmentation_params['max_sample_len_ms'] % self.sparse_frame_len_ms == 0 171 | self.num_sparse_frames = augmentation_params['max_sample_len_ms'] // self.sparse_frame_len_ms 172 | # self.crop_in_time = self.get_crop_in_time_func(augmentation_params['max_sample_len_ms']) 173 | if 'random_frame_size' in augmentation_params and augmentation_params['random_frame_size'] is not None: 174 | self.x_lims = (int(width*augmentation_params['random_frame_size']), width) 175 | self.y_lims = (int(height*augmentation_params['random_frame_size']), height) 176 | # self.crop_in_space = self.get_crop_in_space_func((int(height*augmentation_params['random_frame_size']), height), 177 | # (int(width*augmentation_params['random_frame_size']), width)) 178 | if 'drop_token' in augmentation_params and augmentation_params['drop_token'][0] != 0.0: 179 | self.drop_perc, self.drop_mode = augmentation_params['drop_token'] 180 | # self.drop_token = self.get_drop_token_function(*augmentation_params['drop_token']) 181 | if 'random_shift' in augmentation_params and augmentation_params['random_shift']: 182 | # self.random_shift = self.get_shift_func() 183 | pass 184 | if 'crop_to_max_events' in augmentation_params and augmentation_params['crop_to_max_events'] is not None: 185 | raise ValueError('Not Implemented') 186 | min_crop = min([ min(s) for s in augmentation_params['random_frame_size'] ]) if self.crop_in_space else min(height, width) 187 | med_frame_size = 128-(128-min_crop)//2 188 | res = json.load(open('./datasets/DvsGesture/dataset_stats_{}.json'.format(med_frame_size), 'r')) 189 | max_events = int(res[str(self.chunk_len_ms)][augmentation_params['crop_to_max_events']]) 190 | if self.drop_token: max_events = int(max_events*(1-augmentation_params['drop_token'][0])) 191 | self.max_events_per_chunk = max_events 192 | # self.crop_events = self.get_crop_to_max_events(max_events) 193 | self.h_flip = augmentation_params.get('h_flip', False) 194 | 195 | # print('+'*20, self.crop_in_time, self.crop_in_space, self.drop_token, self.random_shift) 196 | 197 | self.bins = bins 198 | self.preproc_polarity = preproc_polarity 199 | self.patch_size = patch_size 200 | self.original_event_size = 1 if '1' in self.preproc_polarity else 2 201 | self.preproc_event_size = self.original_event_size*bins 202 | self.token_dim = patch_size*patch_size * self.preproc_event_size 203 | 204 | if min_activations_per_patch > 0 and min_activations_per_patch <= 1: 205 | self.min_activations_per_patch = int(min_activations_per_patch*patch_size*patch_size+1) 206 | else: self.min_activations_per_patch = 0 207 | print(f' * patch_size {patch_size}x{patch_size} [{patch_size*patch_size}] | min_activations {self.min_activations_per_patch}') 208 | 209 | 210 | self.height = height 211 | self.width = width 212 | 213 | self.samples = os.listdir(samples_folder) 214 | if dataset_name == 'DVS128': 215 | for l in classes_to_exclude: 216 | self.samples = [ s for s in self.samples if '_label{:02}'.format(l) not in s ] 217 | self.labels = np.array([ int(t[5:7]) for s in self.samples for t in s.split('_') if 'label' in t ]).astype('int8') 218 | self.unique_labels = { l:i for i,l in enumerate(sorted(set(self.labels))) } 219 | self.labels = [ self.unique_labels[l] for l in self.labels ] 220 | self.num_classes = len(self.unique_labels) 221 | elif dataset_name in ['ASL_DVS', 'HMDB', 'UCF101', 'UCF50', 'SLAnimals_4s', 'SLAnimals_3s', 'N_Cars', 'Caltech']: 222 | self.labels = [ s.split('_')[-1][:-5] for s in self.samples ] 223 | self.unique_labels = { l:i for i,l in enumerate(sorted(set(self.labels))) } 224 | self.labels = [ self.unique_labels[l] for l in self.labels ] 225 | self.num_classes = len(self.unique_labels) 226 | else: raise ValueError(f'dataset_name [{dataset_name}] not handled') 227 | 228 | 229 | def get_class_weights(self): 230 | label_dict = self.get_label_dict() 231 | label_dict = { k:label_dict[k] for k in sorted(label_dict) } 232 | num_samples = sum([ len(v) for v in label_dict.values() ]) 233 | # max_len = max([ len(v) for v in label_dict.values() ]) 234 | # class_weigths = { k:max_len/len(v) for k,v in label_dict.items() } 235 | # class_weigths = { k:(len(v), num_samples/(len(label_dict)*len(v))) for k,v in label_dict.items() } 236 | # class_weigths = { k:num_samples/(len(label_dict)*len(v)) for k,v in label_dict.items() } 237 | class_weigths = [ num_samples/(len(label_dict)*len(v)) for k,v in label_dict.items() ] 238 | return torch.tensor(class_weigths) 239 | 240 | 241 | # Crop sequence to self.num_sparse_frames 242 | # def get_crop_in_time_func(self, max_sample_len_ms): 243 | # assert max_sample_len_ms % self.sparse_frame_len_ms == 0 244 | # num_sparse_frames = max_sample_len_ms // self.sparse_frame_len_ms 245 | # # print('num_sparse_frames', num_sparse_frames) 246 | # def crop(total_events): 247 | # # print('Cropping:', len(total_events)) 248 | # if len(total_events) > num_sparse_frames: 249 | # if not self.validation: # Crop sequence randomly 250 | # init = np.random.randint(len(total_events) - num_sparse_frames) 251 | # end = init + num_sparse_frames 252 | # total_events = total_events[init:end] 253 | # else: # Crop to the middle part 254 | # init = (len(total_events) - num_sparse_frames) // 2 255 | # end = init + num_sparse_frames 256 | # total_events = total_events[init:end] 257 | # # assert len(total_events) < num_sparse_frames, str(len(total_events)) + ' ' + str(num_sparse_frames) 258 | # return total_events 259 | # # print('Return crop func') 260 | # return crop 261 | def crop_in_time(self, total_events): 262 | # print('Cropping:', len(total_events)) 263 | if len(total_events) > self.num_sparse_frames: 264 | if not self.validation: # Crop sequence randomly 265 | init = np.random.randint(len(total_events) - self.num_sparse_frames) 266 | end = init + self.num_sparse_frames 267 | total_events = total_events[init:end] 268 | else: # Crop to the middle part 269 | init = (len(total_events) - self.num_sparse_frames) // 2 270 | end = init + self.num_sparse_frames 271 | total_events = total_events[init:end] 272 | # assert len(total_events) < num_sparse_frames, str(len(total_events)) + ' ' + str(num_sparse_frames) 273 | return total_events 274 | 275 | 276 | # Crop sequence in space 277 | # x_lims/y_lims -> (min/max length) -> (length, not coordinates) 278 | # def get_crop_in_space_func(self, x_lims, y_lims): 279 | # # print('get_crop_in_space_func', x_lims, y_lims) 280 | # def crop(total_events): 281 | # _, y_size, x_size, _ = total_events.shape 282 | # # print((y_lims, x_lims), (y_size, x_size), total_events.shape) 283 | # if not self.validation: # Crop sequence randomly 284 | # new_x_size = np.random.randint(x_lims[0], x_lims[1]+1) 285 | # new_y_size = np.random.randint(y_lims[0], y_lims[1]+1) 286 | 287 | # if self.patch_size != 1: 288 | # new_x_size -= new_x_size % self.patch_size 289 | # new_y_size -= new_y_size % self.patch_size 290 | 291 | # x_init = np.random.randint(x_size - new_x_size+1); x_end = x_init + new_x_size 292 | # y_init = np.random.randint(y_size - new_y_size+1); y_end = y_init + new_y_size 293 | # # total_events = total_events[:, x_init:x_end, y_init:y_end, :] 294 | # total_events = total_events[:, y_init:y_end, x_init:x_end, :] 295 | # else: # Crop to the middle part 296 | # new_x_size = (x_lims[0] + x_lims[1])//2 297 | # new_y_size = (y_lims[0] + y_lims[1])//2 298 | 299 | # if self.patch_size != 1: 300 | # new_x_size -= new_x_size % self.patch_size 301 | # new_y_size -= new_y_size % self.patch_size 302 | 303 | # x_init = (x_size - new_x_size)//2; x_end = x_init + new_x_size 304 | # y_init = (y_size - new_y_size)//2; y_end = y_init + new_y_size 305 | # # total_events = total_events[:, x_init:x_end, y_init:y_end, :] 306 | # total_events = total_events[:, y_init:y_end, x_init:x_end, :] 307 | # # print('total_events.shape', total_events.shape, (new_y_size, new_x_size)) 308 | # assert total_events.shape[1] == new_y_size and total_events.shape[2] == new_x_size 309 | # return total_events 310 | # return crop 311 | def crop_in_space(self, total_events): 312 | # print(type(total_events), len(total_events), total_events.shape) 313 | _, y_size, x_size, _ = total_events.shape 314 | # print(self.y_lims, '|', self.x_lims, '|', total_events.shape) 315 | if not self.validation: # Crop sequence randomly 316 | new_x_size = np.random.randint(self.x_lims[0], self.x_lims[1]+1) 317 | new_y_size = np.random.randint(self.y_lims[0], self.y_lims[1]+1) 318 | 319 | if self.patch_size != 1: 320 | new_x_size -= new_x_size % self.patch_size 321 | new_y_size -= new_y_size % self.patch_size 322 | 323 | x_init = np.random.randint(x_size - new_x_size+1); x_end = x_init + new_x_size 324 | y_init = np.random.randint(y_size - new_y_size+1); y_end = y_init + new_y_size 325 | # total_events = total_events[:, x_init:x_end, y_init:y_end, :] 326 | total_events = total_events[:, y_init:y_end, x_init:x_end, :] 327 | else: # Crop to the middle part 328 | new_x_size = (self.x_lims[0] + self.x_lims[1])//2 329 | new_y_size = (self.y_lims[0] + self.y_lims[1])//2 330 | 331 | if self.patch_size != 1: 332 | new_x_size -= new_x_size % self.patch_size 333 | new_y_size -= new_y_size % self.patch_size 334 | 335 | x_init = (x_size - new_x_size)//2; x_end = x_init + new_x_size 336 | y_init = (y_size - new_y_size)//2; y_end = y_init + new_y_size 337 | # total_events = total_events[:, x_init:x_end, y_init:y_end, :] 338 | total_events = total_events[:, y_init:y_end, x_init:x_end, :] 339 | # print('total_events.shape', total_events.shape, (new_y_size, new_x_size)) 340 | # print(total_events.shape, '|', new_y_size, y_init, y_end, '|', new_x_size, x_init, x_end) 341 | assert total_events.shape[1] == new_y_size and total_events.shape[2] == new_x_size, print(total_events.shape, new_y_size, new_x_size) 342 | return total_events 343 | 344 | 345 | 346 | # Remove random events from sequence based on percentage 347 | # drop_mode == 'fixed' -> drop same pixels for all the sequence 348 | # drop_mode == 'rand' -> drop random events in each time-step 349 | # def get_drop_token_function(self, drop_perc, drop_mode): 350 | # def drop_token(total_events): 351 | # if self.validation: 352 | # return total_events 353 | # if drop_mode == 'rand': 354 | # mask = np.random.rand(*total_events.shape[:-1]) < drop_perc 355 | # total_events[mask] = 0.0 356 | # elif drop_mode == 'fixed': 357 | # mask = np.random.rand(*total_events.shape[1:-1]) < drop_perc 358 | # total_events[:, mask] = 0.0 359 | # return total_events 360 | # return drop_token 361 | def drop_token(self, total_events): 362 | if self.validation: 363 | return total_events 364 | if self.drop_mode == 'rand': 365 | mask = np.random.rand(*total_events.shape[:-1]) < self.drop_perc 366 | total_events[mask] = 0.0 367 | elif self.drop_mode == 'fixed': 368 | mask = np.random.rand(*total_events.shape[1:-1]) < self.drop_perc 369 | total_events[:, mask] = 0.0 370 | return total_events 371 | 372 | # def get_shift_func(self): 373 | # def shift(total_pixels, cropped_shape): 374 | # height_diff, width_diff = self.height - cropped_shape[1], self.width - cropped_shape[0] 375 | # # print(height_diff, width_diff, cropped_shape, self.height, self.width) 376 | # if not self.validation: 377 | # new_height_init = np.random.randint(0, height_diff) if height_diff != 0.0 else 0 378 | # new_width_init = np.random.randint(0, width_diff) if width_diff != 0.0 else 0 379 | # else: 380 | # new_height_init, new_width_init = height_diff // 2, width_diff // 2, 381 | # for i in range(len(total_pixels)): 382 | # total_pixels[i][:, 1] += new_height_init 383 | # total_pixels[i][:, 0] += new_width_init 384 | # return total_pixels 385 | # return shift 386 | def shift(self, total_pixels, cropped_shape): 387 | height_diff, width_diff = self.height - cropped_shape[0], self.width - cropped_shape[1] 388 | # print(height_diff, width_diff, cropped_shape, self.height, self.width) 389 | if not self.validation: 390 | new_height_init = np.random.randint(0, height_diff) if height_diff != 0.0 else 0 391 | new_width_init = np.random.randint(0, width_diff) if width_diff != 0.0 else 0 392 | else: 393 | new_height_init, new_width_init = height_diff // 2, width_diff // 2 394 | 395 | # print(1, new_height_init, new_width_init, self.height, self.width, cropped_shape) 396 | new_height_init -= new_height_init % self.patch_size #; new_height_init += self.patch_size//2 397 | new_width_init -= new_width_init % self.patch_size #; new_width_init += self.patch_size//2 398 | # print(2, new_height_init, new_width_init) 399 | 400 | for i in range(len(total_pixels)): 401 | total_pixels[i][:, 0] += new_height_init 402 | total_pixels[i][:, 1] += new_width_init 403 | return total_pixels 404 | 405 | # def get_crop_to_max_events(self, max_events_per_chunk): 406 | # print(' *** get_crop_to_max_events', max_events_per_chunk) 407 | # def crop_to_max_events(total_polarity, total_pixels): 408 | # if not self.validation: 409 | # for i in range(len(total_pixels)): 410 | # if len(total_polarity[i]) > max_events_per_chunk: 411 | # inds = np.random.choice(list(range(len(total_polarity[i]))), size=max_events_per_chunk, replace=False) 412 | # # print(inds) 413 | # # print('----', total_polarity[i].shape, len(total_polarity[i]), max_events_per_chunk) 414 | # total_polarity[i] = total_polarity[i][inds] 415 | # # print('++++', total_polarity[i].shape) 416 | # total_pixels[i] = total_pixels[i][inds] 417 | # return total_polarity, total_pixels 418 | # return crop_to_max_events 419 | def crop_to_max_events(self, total_polarity, total_pixels): 420 | if not self.validation: 421 | for i in range(len(total_pixels)): 422 | if len(total_polarity[i]) > self.max_events_per_chunk: 423 | inds = np.random.choice(list(range(len(total_polarity[i]))), size=self.max_events_per_chunk, replace=False) 424 | # print(inds) 425 | # print('----', total_polarity[i].shape, len(total_polarity[i]), self.max_events_per_chunk) 426 | total_polarity[i] = total_polarity[i][inds] 427 | # print('++++', total_polarity[i].shape) 428 | total_pixels[i] = total_pixels[i][inds] 429 | return total_polarity, total_pixels 430 | 431 | 432 | def __len__(self): 433 | return len(self.samples) 434 | 435 | def get_label_dict(self): 436 | label_dict = { c:[] for c in set(self.labels) } 437 | for i,l in enumerate(self.labels): label_dict[l].append(i) 438 | for k in label_dict: label_dict[k] = torch.IntTensor(label_dict[k]) 439 | return label_dict 440 | 441 | # Return -> [num_timesteps, num_chunk_events, 2pol] | [num_timesteps, num_chunk_events, 2pix_xy], [num_timesteps] 442 | # def __getitem__(self, idx, return_sparse_array=False): 443 | def __getitem_v0__(self, idx, return_sparse_array=False): 444 | 445 | # print('*********') 446 | 447 | filename = self.samples[idx] 448 | label = self.labels[idx] 449 | 450 | # Load sparse matrix 451 | total_events = pickle.load(open(os.path.join(self.samples_folder + filename), 'rb')) # events (t x H x W x 2) 452 | total_events = total_events.todense() 453 | # print('****** total_events.shape', total_events.shape) 454 | 455 | 456 | # Crop sequence to self.num_sparse_frames 457 | # if self.crop_in_time: total_events = self.crop_in_time(total_events) 458 | # if self.crop_in_space: total_events = self.crop_in_space(total_events) 459 | # if self.drop_token: total_events = self.drop_token(total_events) 460 | 461 | if 'max_sample_len_ms' in self.augmentation_params and self.augmentation_params['max_sample_len_ms'] != -1: 462 | total_events = self.crop_in_time(total_events) 463 | if 'random_frame_size' in self.augmentation_params and self.augmentation_params['random_frame_size'] is not None: 464 | total_events = self.crop_in_space(total_events) 465 | if 'drop_token' in self.augmentation_params and self.augmentation_params['drop_token'][0] != 0.0: 466 | total_events = self.drop_token(total_events) 467 | 468 | # Slice and group into self.chunk_len_ms length 469 | diff_frames = total_events.shape[0] % self.chunk_size 470 | if diff_frames != 0 and total_events.shape[0] > self.chunk_size : 471 | if np.random.rand() < 0: total_events = total_events[:diff_frames] 472 | else: total_events = total_events[diff_frames:] 473 | 474 | 475 | # total_chunks = [ total_events[i:i+self.chunk_size].todense() for i in range(0, total_events.shape[0], self.chunk_size) ] # .sum(0) 476 | total_chunks = [ total_events[i:i+self.chunk_size] for i in range(0, total_events.shape[0], self.chunk_size) ] # .sum(0) 477 | # total_chunks = [ c.sum(0) for c in total_chunks ] 478 | 479 | 480 | if return_sparse_array: return total_chunks 481 | else: 482 | total_pixels, total_polarity = [], [] 483 | for nc, c in enumerate(total_chunks): 484 | 485 | bins_init = c.shape[0]; bins_step = bins_init//self.bins 486 | if bins_step == 0: 487 | print('*****', c.shape, 0, bins_init, bins_step) 488 | print(f'Empty chunk [{nc}]') 489 | continue 490 | 491 | # c = np.concatenate([ c[i:i+bins_step].sum(0) for i in range(0, bins_init, bins_step) ], axis=2) 492 | c = np.stack([ c[i:i+bins_step].sum(0) for i in range(0, bins_init, bins_step) ], axis=-1) 493 | # c = [ c[i:i+bins_step].sum(0) for i in range(0, bins_init, bins_step) ] 494 | 495 | if '1' in self.preproc_polarity: c = c.sum(2, keepdims=True) 496 | 497 | c = c.reshape(c.shape[0], c.shape[1], c.shape[2]*c.shape[3]) 498 | 499 | if 'log' in self.preproc_polarity: c = np.log(c + 1) 500 | elif 'unique' in self.preproc_polarity: c = (c>0).astype('float') 501 | elif 'norm' in self.preproc_polarity: 502 | raise ValueError('Not implemented') 503 | # c = c / c.max(2, keepdims=True) # [0] 504 | 505 | 506 | polarity = view_as_blocks(c, (self.patch_size,self.patch_size, self.preproc_event_size)); 507 | 508 | # aggregate by pixel (unique), by patch (sum) -> get the ones with >= min_activations | (num_patches, bool) 509 | inds = (polarity.sum(-1)!=0).reshape(polarity.shape[0], polarity.shape[1], self.patch_size*self.patch_size) \ 510 | .sum(-1).reshape(polarity.shape[0] * polarity.shape[1]) >= self.min_activations_per_patch 511 | 512 | # Reshape to (num_patches x token_dim) 513 | polarity = polarity.reshape(polarity.shape[0] * polarity.shape[1], self.token_dim) 514 | 515 | pixels = np.array([ (i+self.patch_size//2,j+self.patch_size//2) for i in range(0, c.shape[0], self.patch_size) for j in range(0, c.shape[1], self.patch_size) ]) 516 | polarity, pixels = polarity[inds], pixels[inds] 517 | 518 | total_pixels.append(torch.tensor(pixels).long()); total_polarity.append(torch.tensor(polarity).long()) 519 | 520 | # assert len(total_pixels) > 0 521 | # if self.crop_events: total_polarity, total_pixels = self.crop_events(total_polarity, total_pixels) 522 | # if self.random_shift: total_pixels = self.random_shift(total_pixels, total_events.shape[1:-1]) 523 | 524 | if 'crop_to_max_events' in self.augmentation_params and self.augmentation_params['crop_to_max_events'] is not None: 525 | total_polarity, total_pixels = self.crop_to_max_events(total_polarity, total_pixels) 526 | if 'random_shift' in self.augmentation_params and self.augmentation_params['random_shift']: 527 | total_pixels = self.shift(total_pixels, total_events.shape[1:-1]) 528 | 529 | return total_polarity, total_pixels, label 530 | 531 | 532 | # Return -> [num_timesteps, num_chunk_events, 2pol] | [num_timesteps, num_chunk_events, 2pix_xy], [num_timesteps] 533 | def __getitem__(self, idx, return_sparse_array=False): 534 | # def __getitem_v1__(self, idx, return_sparse_array=False): 535 | # %% 536 | # print(idx) 537 | # raise ValueError('**********') 538 | filename = self.samples[idx] 539 | label = self.labels[idx] 540 | 541 | # Load sparse matrix 542 | total_events = pickle.load(open(os.path.join(self.samples_folder + filename), 'rb')) # events (t x H x W x 2) 543 | # total_events = total_events.todense() 544 | # print('****** total_events.shape', total_events.shape, filename) 545 | 546 | ############################################## 547 | ############################################## 548 | ############################################## 549 | # self.chunk_len_ms = 8 # ms 550 | # self.sparse_frame_len_ms = 2 # each sparse frame is 2 ms 551 | # self.augmentation_params['max_sample_len_ms'] = 500 # Each sequence must last 500 ms 552 | # # self.num_sparse_frames = augmentation_params['max_sample_len_ms'] // self.sparse_frame_len_ms 553 | # self.num_sparse_frames = 250 # 250 sparse frames needed 554 | # self.chunk_size = 4 # Number of sparse frames needed to complete a chunk 555 | 556 | # self.bins = 4 557 | # self.min_patches_per_chunk = None 558 | # self.min_events_per_chunk = None 559 | # self.min_activations_per_patch = int(0.05*self.patch_size*self.patch_size+1) 560 | ############################################## 561 | ############################################## 562 | ############################################## 563 | 564 | # Crop sequence to self.num_sparse_frames 565 | dense = False 566 | if 'max_sample_len_ms' in self.augmentation_params and self.augmentation_params['max_sample_len_ms'] != -1: 567 | total_events = self.crop_in_time(total_events) 568 | if not self.validation and 'rotate' in self.augmentation_params and self.augmentation_params['rotate'] is not None and len(self.augmentation_params['rotate']) > 0: 569 | total_events = total_events.todense(); dense = True 570 | angl = np.random.uniform(-self.augmentation_params['rotate']['angle'], self.augmentation_params['rotate']['angle']) 571 | total_events = ndimage.rotate(total_events, angl, axes=(2,1), reshape=False, mode=self.augmentation_params['rotate']['mode']) 572 | if 'random_frame_size' in self.augmentation_params and self.augmentation_params['random_frame_size'] is not None: 573 | total_events = self.crop_in_space(total_events) 574 | # print('****', total_events.shape) 575 | 576 | if not self.validation and self.h_flip and np.random.rand() > 0.5: total_events = total_events[:,:,::-1,:] 577 | 578 | # if self.center_frame: 579 | # pass 580 | 581 | # 1.0. Get chunks by grouping sparse frames 582 | 583 | 584 | total_pixels, total_polarity = [], [] 585 | current_chunk = None 586 | # sf = total_events[0] 587 | # for sf_num, sf in enumerate(total_events[::-1]): 588 | # for sf_num in list(range(len(total_events)-1,-1, -1))[::2]: 589 | 590 | # NUM_EXTRA_CHUNKS = 2 591 | sf_num = len(total_events) - 1 592 | while sf_num >= 0: 593 | # print(sf_num) 594 | 595 | if current_chunk is None: 596 | # print(sf_num-self.chunk_size, sf_num) 597 | current_chunk = total_events[max(0, sf_num-self.chunk_size):sf_num][::-1] 598 | if not dense: current_chunk = current_chunk.todense() 599 | sf_num -= self.chunk_size 600 | # current_chunk = total_events[min(0, sf_num-self.chunk_size):sf_num][::-1]; sf_num -= self.chunk_size 601 | if '1' in self.preproc_polarity: current_chunk = current_chunk.sum(-1, keepdims=True) 602 | 603 | else: 604 | sf = total_events[max(0, sf_num-self.num_extra_chunks):sf_num][::-1] 605 | if not dense: sf = sf.todense() 606 | sf_num -= self.num_extra_chunks 607 | # sf = total_events[min(0, sf_num-self.num_extra_chunks):sf_num][::-1]; sf_num -= self.num_extra_chunks 608 | if '1' in self.preproc_polarity: sf = sf.sum(-1, keepdims=True) 609 | current_chunk = np.concatenate([current_chunk, sf]) 610 | 611 | 612 | 613 | # sf = np.stack([total_events[sf_num], total_events[sf_num-1]]).todense() 614 | # # print(sf_num) 615 | 616 | # # TODO: get 2 sparse frames at the same time 617 | # # sf = sf.todense() 618 | # if '1' in self.preproc_polarity: sf = sf.sum(-1, keepdims=True) 619 | 620 | # # if current_chunk is None: current_chunk = sf[np.newaxis, ...] 621 | # # else: current_chunk = np.concatenate([current_chunk, sf[np.newaxis, ...]]) 622 | # if current_chunk is None: current_chunk = sf 623 | # else: current_chunk = np.concatenate([current_chunk, sf]) 624 | 625 | # if len(current_chunk) < self.chunk_size: 626 | # # print('aaaaaaaaaaaaaaaa', current_chunk.shape, self.chunk_size, sf_num) 627 | # continue 628 | # else: 629 | 630 | if current_chunk.shape[0] >= self.bins: 631 | 632 | # print(0, current_chunk.shape) 633 | 634 | # Get bins 635 | bins_init = current_chunk.shape[0]; 636 | bins_step = bins_init//self.bins 637 | # if bins_step*self.bins < bins_init: bins_step = bins_init//(self.bins-1) 638 | if bins_step == 0: 639 | print('*****', current_chunk.shape, 0, bins_init, bins_step) 640 | # print(f'Empty chunk [{nc}]') 641 | # continue 642 | # chunk_candidate = np.stack([ current_chunk[i:i+bins_step].sum(0) for i in range(0, bins_init, bins_step) ], axis=-1) 643 | chunk_candidate = [] 644 | for ib_num, i in enumerate(list(range(0, bins_init, bins_step))[:self.bins]): 645 | if ib_num == self.bins-1: step = 99999 646 | else: step = bins_step 647 | chunk_candidate.append(current_chunk[i:i+step].sum(0)) 648 | chunk_candidate = np.stack(chunk_candidate, axis=-1).astype(float) 649 | # chunk_candidate = np.stack([ current_chunk[i:i+bins_step].sum(0) for i in list(range(0, bins_init, bins_step))[:self.bins] ], axis=-1) 650 | chunk_candidate = chunk_candidate.reshape(chunk_candidate.shape[0], chunk_candidate.shape[1], chunk_candidate.shape[2]*chunk_candidate.shape[3]) 651 | # print('chunk_candidate.shape', chunk_candidate.shape) 652 | 653 | # Extract patches 654 | # print('1,', sf.shape, current_chunk.shape, chunk_candidate.shape) 655 | # print('aaa', current_chunk.shape, chunk_candidate.shape, (self.patch_size,self.patch_size, self.preproc_event_size), list(range(0, bins_init, bins_step))) 656 | polarity = view_as_blocks(chunk_candidate, (self.patch_size,self.patch_size, self.preproc_event_size)); 657 | 658 | # aggregate by pixel (unique), by patch (sum) -> get the ones with >= min_activations | (num_patches, bool) 659 | inds = (polarity.sum(-1)!=0).reshape(polarity.shape[0], polarity.shape[1], self.patch_size*self.patch_size) \ 660 | .sum(-1).reshape(polarity.shape[0] * polarity.shape[1]) >= self.min_activations_per_patch 661 | 662 | 663 | if inds.sum() == 0: continue 664 | # Check if chunk has the desired patch activations and #events 665 | if self.min_patches_per_chunk and inds.sum() < self.min_patches_per_chunk: continue 666 | if self.min_events_per_chunk and polarity.sum() < self.min_events_per_chunk: continue 667 | 668 | # break 669 | # Good chunk -> process and store 670 | 671 | # Reshape to (num_patches x token_dim) 672 | polarity = polarity.reshape(polarity.shape[0] * polarity.shape[1], self.patch_size*self.patch_size*self.preproc_event_size) # self.token_dim 673 | 674 | pixels = np.array([ (i+self.patch_size//2,j+self.patch_size//2) for i in range(0, chunk_candidate.shape[0], self.patch_size) for j in range(0, chunk_candidate.shape[1], self.patch_size) ]) 675 | # pixels = np.array([ (i,j) for i in range((self.patch_size//2), chunk_candidate.shape[1], self.patch_size) for j in range((self.patch_size//2), chunk_candidate.shape[0], self.patch_size) ]) 676 | # print(2, polarity.shape, pixels.shape) 677 | # print(pixels) 678 | 679 | inds = np.where(inds)[0] 680 | # print(f'{len(total_pixels)} || {inds.shape[0]} patches || {polarity.sum()} events') 681 | 682 | # 1.1. Drop patch tokens 683 | # Apply over the final patch-tokens 684 | if not self.validation and len(inds)>0 and 'drop_token' in self.augmentation_params and self.augmentation_params['drop_token'][0] != 0.0: 685 | # inds = self.drop_token(inds) 686 | inds = np.random.choice(inds, replace=False, size=max(1, int(len(inds)*(1-self.augmentation_params['drop_token'][0])))) 687 | # print('*******', inds.shape, polarity.shape, pixels.shape) 688 | polarity, pixels = polarity[inds], pixels[inds] 689 | 690 | 691 | if 'log' in self.preproc_polarity: polarity = np.log(polarity + 1) 692 | elif 'unique' in self.preproc_polarity: polarity = (polarity>0).astype('float') 693 | elif 'norm' in self.preproc_polarity: 694 | raise ValueError('Not implemented') 695 | # c = c / c.max(2, keepdims=True) # [0] 696 | 697 | assert len(pixels) > 0 and len(polarity) > 0 698 | # 2.0. Process token_dim 699 | total_polarity.append(torch.tensor(polarity)) 700 | total_pixels.append(torch.tensor(pixels).long()) 701 | current_chunk = None 702 | 703 | 704 | # Ensure at least one chunk in the list 705 | if len(total_pixels) == 0 and current_chunk.shape[0] >= self.bins: 706 | # Get bins 707 | bins_init = current_chunk.shape[0]; 708 | bins_step = bins_init//self.bins 709 | # if bins_step*self.bins < bins_init: bins_step = bins_init//(self.bins-1) 710 | if bins_step == 0: 711 | print('*****', current_chunk.shape, 0, bins_init, bins_step) 712 | # print(f'Empty chunk [{nc}]') 713 | # continue 714 | # chunk_candidate = np.stack([ current_chunk[i:i+bins_step].sum(0) for i in range(0, bins_init, bins_step) ], axis=-1) 715 | chunk_candidate = [] 716 | for ib_num, i in enumerate(list(range(0, bins_init, bins_step))[:self.bins]): 717 | if ib_num == self.bins-1: step = 99999 718 | else: step = bins_step 719 | chunk_candidate.append(current_chunk[i:i+step].sum(0)) 720 | chunk_candidate = np.stack(chunk_candidate, axis=-1).astype(float) 721 | # chunk_candidate = np.stack([ current_chunk[i:i+bins_step].sum(0) for i in list(range(0, bins_init, bins_step))[:self.bins] ], axis=-1) 722 | chunk_candidate = chunk_candidate.reshape(chunk_candidate.shape[0], chunk_candidate.shape[1], chunk_candidate.shape[2]*chunk_candidate.shape[3]) 723 | 724 | 725 | # Extract patches 726 | # print('1,', sf.shape, current_chunk.shape, chunk_candidate.shape) 727 | polarity = view_as_blocks(chunk_candidate, (self.patch_size,self.patch_size, self.preproc_event_size)); 728 | 729 | # aggregate by pixel (unique), by patch (sum) -> get the ones with >= min_activations | (num_patches, bool) 730 | inds = (polarity.sum(-1)!=0).reshape(polarity.shape[0], polarity.shape[1], self.patch_size*self.patch_size) \ 731 | .sum(-1).reshape(polarity.shape[0] * polarity.shape[1]) >= self.min_activations_per_patch 732 | if inds.sum() == 0: 733 | inds = (polarity.sum(-1)!=0).reshape(polarity.shape[0], polarity.shape[1], self.patch_size*self.patch_size) \ 734 | .sum(-1).reshape(polarity.shape[0] * polarity.shape[1]) >= 1.0 735 | if inds.sum() == 0: 736 | inds = (polarity.sum(-1)!=0).reshape(polarity.shape[0], polarity.shape[1], self.patch_size*self.patch_size) \ 737 | .sum(-1).reshape(polarity.shape[0] * polarity.shape[1]) >= 0.0 738 | if inds.sum() == 0: 739 | print(len(inds), inds.sum(), current_chunk.shape, chunk_candidate.shape, sf_num, len(total_polarity), len(total_pixels), total_events.shape, filename) 740 | 741 | 742 | # break 743 | # Good chunk -> process and store 744 | 745 | # Reshape to (num_patches x token_dim) 746 | polarity = polarity.reshape(polarity.shape[0] * polarity.shape[1], self.patch_size*self.patch_size*self.preproc_event_size) # self.token_dim 747 | 748 | pixels = np.array([ (i+self.patch_size//2,j+self.patch_size//2) for i in range(0, chunk_candidate.shape[0], self.patch_size) for j in range(0, chunk_candidate.shape[1], self.patch_size) ]) 749 | # print(2, polarity.shape, pixels.shape) 750 | 751 | inds = np.where(inds)[0] 752 | # print(f'{len(total_pixels)} || {inds.shape[0]} patches || {polarity.sum()} events') 753 | 754 | # 1.1. Drop patch tokens 755 | # Apply over the final patch-tokens 756 | if not self.validation and len(inds)>0 and 'drop_token' in self.augmentation_params and self.augmentation_params['drop_token'][0] != 0.0: 757 | # inds = self.drop_token(inds) 758 | inds = np.random.choice(inds, replace=False, size=max(1, int(len(inds)*(1-self.augmentation_params['drop_token'][0])))) 759 | # print('*******', inds.shape, polarity.shape, pixels.shape) 760 | polarity, pixels = polarity[inds], pixels[inds] 761 | 762 | 763 | if 'log' in self.preproc_polarity: polarity = np.log(polarity + 1) 764 | elif 'unique' in self.preproc_polarity: polarity = (polarity>0).astype('float') 765 | elif 'norm' in self.preproc_polarity: 766 | raise ValueError('Not implemented') 767 | # c = c / c.max(2, keepdims=True) # [0] 768 | 769 | # 2.0. Process token_dim 770 | assert len(pixels) > 0 and len(polarity) > 0 771 | total_polarity.append(torch.tensor(polarity)) 772 | total_pixels.append(torch.tensor(pixels).long()) 773 | current_chunk = None 774 | 775 | 776 | if 'random_shift' in self.augmentation_params and self.augmentation_params['random_shift']: 777 | total_pixels = self.shift(total_pixels, total_events.shape[1:-1]) 778 | 779 | # assert len(total_polarity) > 0 and len(total_pixels) > 0, f'{len(total_pixels)} , {len(total_polarity)} , {current_chunk.shape} , {self.bins} , {total_events.shape} , {filename}' 780 | return total_polarity, total_pixels, label 781 | 782 | 783 | 784 | 785 | # Return the batch sample indices randomly. 786 | class CustomBatchSampler(): 787 | 788 | # TODO: remove used samples from dict and re-create when empty ? 789 | # - TODO: add samples_per_class 790 | def __init__(self, batch_size, label_dict, sample_repetitions=1, drop_last=False): 791 | 792 | assert batch_size % sample_repetitions == 0 793 | self.batch_size = batch_size 794 | self.label_dict = label_dict 795 | self.sample_repetitions = sample_repetitions 796 | self.drop_last = drop_last 797 | self.generator = torch.Generator() 798 | self.generator.manual_seed(0) 799 | self.num_classes = len(self.label_dict) 800 | self.unique_labels = list(self.label_dict.keys()) 801 | 802 | def __len__(self): 803 | epoch_length = sum([ len(v) for v in self.label_dict.values() ])*self.sample_repetitions // self.batch_size 804 | print('**********', epoch_length) 805 | return epoch_length 806 | # return 5 807 | 808 | def __iter__(self): 809 | 810 | # if self.label_dict is not None: 811 | # keys = list(self.label_dict.keys()) 812 | # num_classes = len(keys) 813 | 814 | total_labels = [] 815 | while True: 816 | # ks = [] 817 | inds = [] 818 | 819 | for b in range(self.batch_size // self.sample_repetitions): 820 | 821 | if len(total_labels) == 0: total_labels = self.unique_labels.copy() 822 | 823 | k = np.random.randint(0, len(total_labels), size=(1))[0] 824 | k = total_labels.pop(k) 825 | # ks.append(k) 826 | 827 | # if self.sample_dict is not None: 828 | # k = torch.randint(0, self.num_classes, size=(1,), generator=self.generator)[0].item() 829 | # k = np.random.randint(0, self.num_classes, size=(1))[0] 830 | # k = keys[torch.randint(0, num_classes, size=(1,), generator=self.generator)[0].item()] 831 | num_k_samples = len(self.label_dict[k]) 832 | # ind = torch.randint(0, num_k_samples, size=(1,), generator=self.generator)[0].item() 833 | ind = np.random.randint(0, num_k_samples, size=(1))[0] 834 | ind = self.label_dict[k][ind] 835 | for _ in range(self.sample_repetitions): inds.append(ind) 836 | 837 | # print('***', len(ks), ks) 838 | yield inds 839 | 840 | 841 | # Pad sequences by timesteps and events 842 | # Samples: ([batch_size], [timesteps/chunk], [events], event_data) 843 | def pad_list_of_sequences(samples, token_size, pre_padding = True): 844 | # print(f'time_steps || max {max([ len(s) for s in samples ])} | mean {np.mean([ len(s) for s in samples ])}') 845 | # print(f'events_num || max {max([ chunk.shape[0] for sample in samples for chunk in sample ])} | mean {np.mean([ chunk.shape[0] for sample in samples for chunk in sample ])}') 846 | max_timesteps = max([ len(s) for s in samples ]) 847 | batch_size = len(samples) 848 | max_event_num = max([ chunk.shape[0] for sample in samples for chunk in sample ]) 849 | # token_size = samples[0][0][0].shape[-1] 850 | 851 | batch_data = torch.zeros(max_timesteps, batch_size, max_event_num, token_size) 852 | for num_sample, action_sample in enumerate(samples): 853 | num_chunks = len(action_sample) 854 | # print([ c.shape for c in action_sample ]) 855 | for chunk_num, chunk in enumerate(action_sample): 856 | chunk_events = chunk.shape[0] 857 | # print(' ** {} {}'.format(batch_data.shape, chunk_events)) 858 | if chunk_events == 0: 859 | # pass 860 | continue 861 | if pre_padding: batch_data[-(num_chunks-chunk_num), num_sample, -chunk_events:, :] = chunk 862 | else: batch_data[chunk_num, num_sample, :chunk_events, :] = chunk 863 | 864 | return batch_data 865 | 866 | 867 | # def get_custom_collate_fn(pre_padding = True): 868 | # def custom_collate_fn(batch_samples): 869 | # pols, pixels, labels = [], [], [] 870 | # for sample in batch_samples: 871 | # pols.append(sample[0]) 872 | # pixels.append(sample[1]) 873 | # labels.append(sample[2]) 874 | 875 | # token_size = pols[0][0].shape[-1] 876 | 877 | # pols = pad_list_of_sequences(pols, token_size, pre_padding) 878 | # pixels = pad_list_of_sequences(pixels, 2, pre_padding) 879 | # # if '1' in preproc_polarity: pols = pols.sum(-1, keepdims=True) 880 | # # if 'log' in preproc_polarity: pols = torch.log(pols + 1) 881 | # # elif 'unique' in preproc_polarity: pols = (pols>0).float() 882 | # # elif 'norm' in preproc_polarity: pols = pols / pols.max(2, True)[0] 883 | 884 | # pols, pixels, labels = pols, pixels.long(), torch.tensor(labels).long() 885 | # # print('+++++', pols.shape, pixels.shape, labels.shape) 886 | # return pols, pixels, labels 887 | # return custom_collate_fn 888 | 889 | 890 | 891 | class DVS128DataModule(LightningDataModule): 892 | def __init__(self, batch_size, chunk_len_ms, 893 | patch_size, min_activations_per_patch, bins, 894 | min_patches_per_chunk, min_events_per_chunk, num_extra_chunks, 895 | augmentation_params, 896 | dataset_name, 897 | from_frames=True, 898 | skip_last_event=False, sample_repetitions=1, preproc_polarity=None, 899 | one_sample_per_chunk=False, 900 | custom_sampler = True, 901 | workers=8, pin_memory=False, classes_to_exclude=[], balance=None): 902 | super().__init__() 903 | self.batch_size = batch_size 904 | # self.event_size = event_size 905 | self.chunk_len_ms = chunk_len_ms 906 | self.patch_size = patch_size 907 | self.min_activations_per_patch = min_activations_per_patch 908 | self.bins = bins 909 | self.min_patches_per_chunk = min_patches_per_chunk 910 | self.min_events_per_chunk = min_events_per_chunk 911 | self.num_extra_chunks = num_extra_chunks 912 | 913 | 914 | self.augmentation_params = augmentation_params 915 | self.dataset_name = dataset_name 916 | self.from_frames = from_frames 917 | self.workers = workers 918 | self.sample_repetitions = sample_repetitions 919 | self.preproc_polarity = preproc_polarity 920 | self.skip_last_event = skip_last_event 921 | self.pin_memory = pin_memory 922 | self.classes_to_exclude = classes_to_exclude 923 | 924 | self.pre_padding = True 925 | self.one_sample_per_chunk = one_sample_per_chunk 926 | self.custom_sampler = custom_sampler 927 | 928 | 929 | 930 | assert self.chunk_len_ms / 2 % self.bins == 0.0 931 | if not from_frames: raise ValueError('not from_frames not implemented') 932 | 933 | self.dataset_name = dataset_name 934 | if dataset_name == 'DVS128': 935 | # if self.chunk_len_ms == 8 or self.bins not in [1,2]: self.data_folder = './datasets/DvsGesture/clean_dataset_frames_2000/' 936 | # # self.data_folder = './datasets/DvsGesture/clean_dataset_frames_6000/' 937 | # else: self.data_folder = './datasets/DvsGesture/clean_dataset_frames_12000/' 938 | self.data_folder = './datasets/DvsGesture/clean_dataset_frames_2000/' 939 | 940 | self.width, self.height = 128, 128 941 | self.num_classes = 12 - len(classes_to_exclude) 942 | self.class_mapping = copy.deepcopy(class_mapping) 943 | for c in classes_to_exclude: del self.class_mapping[c] 944 | # self.class_mapping = { i:l for i,_,l in enumerate(sorted(self.class_mapping.items(), key=lambda x:x[0])) } 945 | self.class_mapping = { i:l[1] for i,l in enumerate(sorted(self.class_mapping.items(), key=lambda x:x[0])) } 946 | elif dataset_name == 'ASL_DVS': 947 | self.data_folder = './datasets/ICCV2019_DVS_dataset/clean_dataset_frames_2000/' 948 | self.width, self.height = 240, 180 949 | # self.width, self.height = 180, 240 950 | self.num_classes = 24 951 | self.class_mapping = { i:l for i,l in enumerate('a b c d e f g h i k l m n o p q r s t u v w x y'.split()) } 952 | elif dataset_name == 'HMDB': 953 | self.data_folder = './datasets/HMDB_DVS/dataset_s0.3_2000/' 954 | self.width, self.height = 240, 180 955 | # self.width, self.height = 180, 240 956 | self.num_classes = 51 957 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 958 | elif dataset_name == 'UCF101': 959 | self.data_folder = './datasets/UCF101_DVS/dataset_split1_2000/' 960 | self.width, self.height = 240, 180 961 | # self.width, self.height = 180, 240 962 | self.num_classes = 101 963 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 964 | elif dataset_name == 'UCF50': 965 | self.data_folder = './datasets/UCF50_DVS/dataset_split1_2000/' 966 | self.width, self.height = 240, 180 967 | # self.width, self.height = 180, 240 968 | self.num_classes = 50 969 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 970 | elif dataset_name == 'SLAnimals_3s': 971 | # if self.chunk_len_ms == 8 or self.bins not in [1,2]: self.data_folder = './datasets/SL_animal_splits/dataset_3sets_2000/' 972 | # else: self.data_folder = './datasets/SL_animal_splits/dataset_3sets_12000/' 973 | self.data_folder = './datasets/SL_animal_splits/dataset_3sets_2000/' 974 | self.width, self.height = 128, 128 975 | # self.width, self.height = 180, 240 976 | self.num_classes = 19 977 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 978 | elif dataset_name == 'SLAnimals_4s': 979 | # if self.chunk_len_ms == 8 or self.bins not in [1,2]: self.data_folder = './datasets/SL_animal_splits/dataset_4sets_2000/' 980 | # else: self.data_folder = './datasets/SL_animal_splits/dataset_4sets_12000/' 981 | self.data_folder = './datasets/SL_animal_splits/dataset_4sets_2000/' 982 | self.width, self.height = 128, 128 983 | # self.width, self.height = 180, 240 984 | self.num_classes = 19 985 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 986 | elif dataset_name == 'N_Cars': 987 | self.data_folder = './datasets/Prophesee_Dataset_n_cars/dataset_2000/' 988 | self.width, self.height = 128, 128 989 | # self.width, self.height = 180, 240 990 | self.num_classes = 2 991 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 992 | elif dataset_name == 'Caltech': 993 | self.data_folder = './datasets/N_Caltech_101/clean_dataset_frames_2000/' 994 | self.width, self.height = 240, 180 995 | # self.width, self.height = 180, 240 996 | self.num_classes = 101 997 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 998 | else: raise ValueError(f'Dataset [{dataset_name}] not handled') 999 | 1000 | # if from_frames: self.data_folder = './datasets/DvsGesture/clean_dataset_frames_2000/' 1001 | # else: self.data_folder = './datasets/DvsGesture/clean_dataset/' 1002 | 1003 | self.preproc_event_size = 1 if '1' in self.preproc_polarity else 2 1004 | self.preproc_event_size *= bins 1005 | self.token_dim = patch_size*patch_size * self.preproc_event_size 1006 | 1007 | 1008 | def custom_collate_fn(self, batch_samples): 1009 | pols, pixels, labels = [], [], [] 1010 | 1011 | # one_sample_per_chunk | Each chunk will be a sample with 1 time-step 1012 | if self.one_sample_per_chunk: sample_id, sample_labels, idx = [], [], 0 1013 | 1014 | for num_sample, sample in enumerate(batch_samples): 1015 | # Sample -> time_sequence 1016 | # #samples == batch_size 1017 | 1018 | if sample is None or len(sample[0]) == 0: 1019 | print('Empty sample') 1020 | print(len(sample), len(sample[0])) 1021 | continue 1022 | 1023 | # print(len(sample[0]), sample[0][0].shape, len(sample[1]), sample[1][0].shape) 1024 | if self.one_sample_per_chunk: 1025 | for i in range(len(sample[0])): 1026 | pols.append([sample[0][i]]) 1027 | pixels.append([sample[1][i]]) 1028 | labels.append(sample[2]) 1029 | # sample_id.append(num_sample) 1030 | sample_id.append(list(range(idx, idx+len(sample[0])))) 1031 | sample_labels.append(sample[2]) 1032 | idx += len(sample[0]) 1033 | else: 1034 | pols.append(sample[0]) 1035 | pixels.append(sample[1]) 1036 | labels.append(sample[2]) 1037 | 1038 | token_size = pols[0][0].shape[-1] 1039 | 1040 | pols = pad_list_of_sequences(pols, token_size, self.pre_padding) 1041 | pixels = pad_list_of_sequences(pixels, 2, self.pre_padding) 1042 | # if '1' in preproc_polarity: pols = pols.sum(-1, keepdims=True) 1043 | # if 'log' in preproc_polarity: pols = torch.log(pols + 1) 1044 | # elif 'unique' in preproc_polarity: pols = (pols>0).float() 1045 | # elif 'norm' in preproc_polarity: pols = pols / pols.max(2, True)[0] 1046 | 1047 | pols, pixels, labels = pols, pixels.long(), torch.tensor(labels).long() 1048 | # print('+++++', pols.shape, pixels.shape, labels.shape) 1049 | if self.one_sample_per_chunk: 1050 | sample_labels = torch.tensor(sample_labels).long() 1051 | return pols, pixels, (labels, sample_id, sample_labels) 1052 | else: return pols, pixels, labels 1053 | 1054 | 1055 | def train_dataloader(self): 1056 | # if self.from_frames: 1057 | dt = DVS128Dataset_from_frames(self.data_folder+'train/', chunk_len_ms = self.chunk_len_ms, 1058 | validation=False, 1059 | preproc_polarity=self.preproc_polarity, patch_size=self.patch_size, 1060 | min_activations_per_patch=self.min_activations_per_patch, 1061 | bins = self.bins, 1062 | min_patches_per_chunk = self.min_patches_per_chunk, min_events_per_chunk = self.min_events_per_chunk, 1063 | num_extra_chunks = self.num_extra_chunks, 1064 | dataset_name=self.dataset_name, height=self.height, width=self.width, 1065 | augmentation_params=self.augmentation_params, 1066 | classes_to_exclude=self.classes_to_exclude) 1067 | # else: 1068 | # dt = DVS128Dataset(self.data_folder+'train/', chunk_len_ms = self.chunk_len_ms, 1069 | # skip_last_event=self.skip_last_event, classes_to_exclude=self.classes_to_exclude) 1070 | if self.custom_sampler: 1071 | sampler = CustomBatchSampler(batch_size=self.batch_size, label_dict=dt.get_label_dict(), sample_repetitions=self.sample_repetitions) 1072 | dl = DataLoader(dt, batch_sampler=sampler, collate_fn=self.custom_collate_fn, num_workers=self.workers, pin_memory=self.pin_memory) 1073 | else: 1074 | dl = DataLoader(dt, batch_size=self.batch_size, collate_fn=self.custom_collate_fn, shuffle=True, num_workers=self.workers, pin_memory=self.pin_memory) 1075 | return dl 1076 | def val_dataloader(self): 1077 | # if self.from_frames: 1078 | dt = DVS128Dataset_from_frames(self.data_folder+'test/', chunk_len_ms = self.chunk_len_ms, 1079 | validation=True, 1080 | preproc_polarity=self.preproc_polarity, patch_size=self.patch_size, 1081 | min_activations_per_patch=self.min_activations_per_patch, 1082 | bins = self.bins, 1083 | min_patches_per_chunk = self.min_patches_per_chunk, min_events_per_chunk = self.min_patches_per_chunk, 1084 | num_extra_chunks = self.num_extra_chunks, 1085 | dataset_name=self.dataset_name, height=self.height, width=self.width, 1086 | augmentation_params=self.augmentation_params, 1087 | classes_to_exclude=self.classes_to_exclude) 1088 | # else: 1089 | # dt = DVS128Dataset(self.data_folder+'test/', chunk_len_ms = self.chunk_len_ms, 1090 | # skip_last_event=self.skip_last_event, classes_to_exclude=self.classes_to_exclude) 1091 | # sampler = CustomBatchSampler(batch_size=self.batch_size, label_dict=dt.get_label_dict(), sample_repetitions=self.sample_repetitions) 1092 | # dl = DataLoader(dt, batch_sampler=sampler, collate_fn=get_custom_collate_fn(pre_padding=True), num_workers=self.workers) 1093 | # dl = DataLoader(dt, batch_size=(self.batch_size//2)+1, collate_fn=get_custom_collate_fn(pre_padding=True), num_workers=self.workers, pin_memory=self.pin_memory) 1094 | dl = DataLoader(dt, batch_size=(self.batch_size//2)+1, shuffle=False, collate_fn=self.custom_collate_fn, num_workers=self.workers, pin_memory=self.pin_memory) 1095 | return dl 1096 | 1097 | 1098 | 1099 | 1100 | # %% 1101 | 1102 | if __name__ == '__main__': 1103 | 1104 | from tqdm import tqdm 1105 | import os 1106 | os.chdir('../..') 1107 | import time 1108 | 1109 | np.random.seed(0) 1110 | 1111 | 1112 | data_params = {'batch_size': 32, 'sample_repetitions': 1, 'chunk_len_ms': 20, 1113 | 'classes_to_exclude':[], 'workers': 1, 1114 | 'preproc_polarity': 'log', 'pin_memory': False, 1115 | 'patch_size': 8, 'min_activations_per_patch': 0.1, 1116 | 'bins': 1, 1117 | 'min_patches_per_chunk': 128, 'min_events_per_chunk': None, 'num_extra_chunks': 8, 1118 | 'one_sample_per_chunk': False, 1119 | # 'one_sample_per_chunk': True, 1120 | # 'event_size': 2, 1121 | # 'preproc_polarity': None, 1122 | # 'dataset_name': 'DVS128', 1123 | # 'dataset_name': 'ASL_DVS', 1124 | 'dataset_name': 'HMDB', 1125 | # 'dataset_name': 'Caltech', 1126 | 'augmentation_params': { 'max_sample_len_ms': 200, 'random_frame_size': 0.75, 1127 | 'random_shift': True, 1128 | 'drop_token': (0.2, 'fixed'), 1129 | # 'drop_token': (0.0, 'fixed'), 1130 | 'crop_to_max_events': None, 1131 | } } 1132 | # validation = True 1133 | validation = False 1134 | 1135 | # from_frames = False 1136 | # dm = DVS128DataModule(**data_params, from_frames = from_frames) 1137 | # if not validation: dlf = dm.train_dataloader() 1138 | # else: dlf = dm.val_dataloader() 1139 | 1140 | from_frames = True 1141 | dm = DVS128DataModule(**data_params, from_frames = from_frames) 1142 | 1143 | # Initialize self for testing 1144 | dlt = dm.val_dataloader() 1145 | dt = dlt.dataset 1146 | self = dt 1147 | batch_samples = [dt[0]] 1148 | idx = 32 1149 | filename = self.samples[idx] 1150 | label = self.labels[idx] 1151 | 1152 | 1153 | if not validation: dlt = dm.train_dataloader() 1154 | else: dlt = dm.val_dataloader() 1155 | 1156 | print(dlt.dataset.num_classes) #dlf.dataset.num_classes, 1157 | 1158 | # dlt = iter(dlt) 1159 | # dlf = iter(dlf) 1160 | 1161 | # for _ in tqdm(range(dlf.__len__())): 1162 | # for _ in tqdm(range(100)): 1163 | # for i in range(800): 1164 | # batch_data_t = next(dlt) 1165 | t = time.time() 1166 | times = [] 1167 | print(' * time-steps x batch_size x num_patches x token_dim *') 1168 | for i, batch_data_t in enumerate(dlt): 1169 | # print(i, batch_data_f[0].shape, batch_data_t[0].shape, batch_data_f[2], batch_data_t[2]) 1170 | # print(i, batch_data_t[0].shape, batch_data_t[1].shape, batch_data_t[2]) 1171 | print(i, batch_data_t[0].shape, batch_data_t[1].shape, batch_data_t[2].shape) 1172 | t = time.time()-t 1173 | times.append(t) 1174 | print(np.mean(times), t) 1175 | t = time.time() 1176 | 1177 | # del batch_data_t 1178 | 1179 | # break 1180 | 1181 | 1182 | 1183 | # %% 1184 | 1185 | if False: 1186 | # %% 1187 | dlt = dm.val_dataloader() 1188 | dt = dlt.dataset 1189 | self = dt 1190 | batch_samples = [dt[0]] 1191 | 1192 | 1193 | # %% 1194 | 1195 | idx = 32 1196 | filename = self.samples[idx] 1197 | label = self.labels[idx] 1198 | 1199 | # %% 1200 | 1201 | label_dict = dt.get_label_dict() 1202 | num_samples = sum([ len(v) for v in label_dict.values() ]) 1203 | max_len = max([ len(v) for v in label_dict.values() ]) 1204 | class_weigths = { k:max_len/len(v) for k,v in label_dict.items() } 1205 | class_weigths = { k:(len(v), num_samples/(len(label_dict)*len(v))) for k,v in label_dict.items() } 1206 | 1207 | 1208 | 1209 | 1210 | 1211 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [[Paper](https://arxiv.org/abs/2204.03355)] [[Supplementary video](https://drive.google.com/file/d/1X4OviJTxTUbi2W0zQYKG3qqtEUf98a0p/view?usp=sharing)] 2 | 3 | This repository contains the official code from __Event Transformer. A sparse-aware solution for efficient event data processing__. 4 | 5 | Event Transformer (EvT) takes advantage of the event-data sparsity to increase its efficiency. EvT usses a new sparse patch-based event-data representation and a compact transformer architecture that naturally processes it. EvT shows high classification accuracy while requiring minimal computation resources, being able to work with minimal latency both in GPU and CPU. 6 | 7 |

8 | 9 |

10 | 11 | #### Citation: 12 | ``` 13 | @InProceedings{Sabater_2022_CVPR, 14 | author = {Sabater, Alberto and Montesano, Luis and Murillo, Ana C.}, 15 | title = {Event Transformer. A sparse-aware solution for efficient event data processing}, 16 | booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) Workshops}, 17 | month = {June}, 18 | year = {2022}, 19 | } 20 | ``` 21 | 22 | 23 | ### REPOSITORY REQUIREMENTS 24 | 25 | The present work has been developed and tested with Python 3.7.10, pytorch 1.9.0 and Ubuntu 18.04 26 | To reproduce our results we suggest to create a Python environment as follows. 27 | 28 | ``` 29 | conda create --name evt python=3.7.10 30 | conda activate evt 31 | pip install -r requirements.txt 32 | ``` 33 | 34 | 35 | 36 | ### PRETRAINED MODELS 37 | 38 | The pretrained models must be located under a `./pretrained_models` directory and can be downloaded from Drive ( 39 | [DVS128 10 classes](https://drive.google.com/file/d/184I-hOOyGwzsT9uPBUXrbhR2Trou0JJh/view?usp=sharing), 40 | [DVS128 11 classes](https://drive.google.com/file/d/1pzvVgIC9aSpCjvl3IUQj_NT6JK-fJVHJ/view?usp=sharing), 41 | [Sl-Animals 3-Sets](https://drive.google.com/file/d/1nDwVZQ5ivnyBSW1U3hH51ebv3nudDUQN/view?usp=sharing), 42 | [Sl-Animals 4-Sets](https://drive.google.com/file/d/1BAM2DTbyqN_AUR0aIlHuJUuRl65xQKL6/view?usp=sharing), 43 | [ASL-DVS](https://drive.google.com/file/d/1WqCcuLILKO1ACeGV4tj1KgP5Bdut8Pqe/view?usp=sharing)). 44 | 45 | 46 | 47 | ### DATA DOWNLOAD AND PRE-PROCESSING 48 | 49 | The datasets involved in the present work must be downloaded from their source and stored under a `./datasets` path: 50 | - DVS128: https://research.ibm.com/interactive/dvsgesture/ 51 | - SL-Animals-DVS: http://www2.imse-cnm.csic.es/neuromorphs/index.php/SL-ANIMALS-DVS-Database 52 | - ASL: https://github.com/PIX2NVS/NVS2Graph 53 | - N-Caltech-101: https://www.garrickorchard.com/datasets/n-caltech101 54 | 55 | In order to have a faster training process we pre-process the source data by building intermediate sparse frame representations, that will be later loaded by our data generator. 56 | This transformation can be perfomed with the files located under `./dataset_scripts`. 57 | In the case of DVS128, it is mandatory to execute first `dvs128_split_dataset.py` and later `dvs128.py`. 58 | 59 | 60 | 61 | ### EvT EVALUATION 62 | 63 | The evaluation of our pretrained models can be performed by executing: `python evaluation_stats.py` 64 | At the beginning of the file you can select the pretrained model to evaluate and the device where to evaluate it (CPU or GPU). Evaluation results include FLOPs, parameters, average activated patches, average processing time, and validation accuracy. 65 | 66 | 67 | 68 | ### EvT TRAINING 69 | 70 | The training of a new model can be performed by executing: `python train.py` 71 | At the beginning of the file you can select the pretraining model from where to copy its training hyper-parameters. 72 | Note that, since the involved datasets do not contain many training samples and there is data augmentation involed in the training, final results might not be exactly equal than the ones reported in the article. If so, please perform several training executions. 73 | -------------------------------------------------------------------------------- /data_generation.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import Dataset, DataLoader 2 | from pytorch_lightning import LightningDataModule 3 | import torch 4 | 5 | import os 6 | import pickle 7 | import numpy as np 8 | import json 9 | from skimage.util import view_as_blocks 10 | import copy 11 | from scipy import ndimage 12 | 13 | 14 | DVS128_class_mapping = {0: 'background', 1: 'hand_clapping', 2: 'right_hand_wave', 15 | 3: 'left_hand_wave', 4: 'right_arm_clockwise', 16 | 5: 'right_arm_counter_clockwise', 6: 'left_arm_clockwise', 17 | 7: 'left_arm_counter_clockwise', 8: 'arm_roll', 18 | 9: 'air_drums', 10: 'air_guitar', 11: 'other_gestures'} 19 | 20 | 21 | 22 | # EventDataset load the event data organized in sparse frames 23 | # Each sparse frame represents 2-12ms 24 | # Contiguous frames are processed together to represent a time-window (24-48-100ms) 25 | class EventDataset(Dataset): 26 | def __init__(self, samples_folder, # Folder from where to load the data 27 | chunk_len_ms, # Base time-window length (ms) 28 | validation, # Wether to use data augmentation or not 29 | augmentation_params, # Augmentation params 30 | preproc_polarity, # '1' to merge both polarities 31 | patch_size, # Side of the patches 32 | bins, # Histogram bins 33 | min_activations_per_patch, # Percentage of minimum required events per activated patch 34 | min_patches_per_chunk, # Minimum amount of patches per time-window 35 | num_extra_chunks, # Number of extra sparse frames to extend the time-window if needed 36 | dataset_name, height, width, 37 | classes_to_exclude=[] # Used to exclude classes from DV128 38 | ): 39 | 40 | self.samples_folder = samples_folder 41 | self.validation = validation 42 | self.chunk_len_ms = chunk_len_ms 43 | self.chunk_len_us = chunk_len_ms*1000 44 | 45 | self.sparse_frame_len_us = int(self.samples_folder.split('/')[-3].split('_')[-1]) # len of each loaded sparse frame 46 | self.sparse_frame_len_ms = self.sparse_frame_len_us // 1000 47 | assert self.chunk_len_us % self.sparse_frame_len_us == 0 48 | self.chunk_size = self.chunk_len_us // self.sparse_frame_len_us # Size of the grouped frame chunks 49 | 50 | self.height = height 51 | self.width = width 52 | self.min_patches_per_chunk = min_patches_per_chunk 53 | self.num_extra_chunks = num_extra_chunks 54 | 55 | # Define data augmentation functions 56 | self.augmentation_params = augmentation_params 57 | if augmentation_params is not None and len(augmentation_params) != 0: 58 | # Size of the cropped event-sequences 59 | if 'max_sample_len_ms' in augmentation_params and augmentation_params['max_sample_len_ms'] != -1: 60 | self.num_sparse_frames = augmentation_params['max_sample_len_ms'] // self.sparse_frame_len_ms 61 | # Minimum values of cropped samples 62 | if 'random_frame_size' in augmentation_params and augmentation_params['random_frame_size'] is not None: 63 | self.x_lims = (int(width*augmentation_params['random_frame_size']), width) 64 | self.y_lims = (int(height*augmentation_params['random_frame_size']), height) 65 | # Percentage of tokens to drop during training 66 | if 'drop_token' in augmentation_params and augmentation_params['drop_token'][0] != 0.0: 67 | self.drop_perc, self.drop_mode = augmentation_params['drop_token'] 68 | self.h_flip = augmentation_params.get('h_flip', False) 69 | 70 | 71 | self.bins = bins 72 | self.preproc_polarity = preproc_polarity 73 | self.patch_size = patch_size 74 | self.original_event_size = 1 if '1' in self.preproc_polarity else 2 75 | self.preproc_event_size = self.original_event_size*bins 76 | self.token_dim = patch_size*patch_size * self.preproc_event_size 77 | 78 | if min_activations_per_patch > 0 and min_activations_per_patch <= 1: 79 | self.min_activations_per_patch = int(min_activations_per_patch*patch_size*patch_size+1) 80 | else: self.min_activations_per_patch = 0 81 | 82 | self.height = height 83 | self.width = width 84 | 85 | self.samples = os.listdir(samples_folder) 86 | if dataset_name == 'DVS128': 87 | for l in classes_to_exclude: 88 | self.samples = [ s for s in self.samples if '_label{:02}'.format(l) not in s ] 89 | self.labels = np.array([ int(t[5:7]) for s in self.samples for t in s.split('_') if 'label' in t ]).astype('int8') 90 | self.unique_labels = { l:i for i,l in enumerate(sorted(set(self.labels))) } 91 | self.labels = [ self.unique_labels[l] for l in self.labels ] 92 | self.num_classes = len(self.unique_labels) 93 | elif dataset_name in ['ASL_DVS', 'HMDB', 'UCF101', 'UCF50', 'SLAnimals_4s', 'SLAnimals_3s', 'N_Cars', 'Caltech']: 94 | self.labels = [ s.split('_')[-1][:-5] for s in self.samples ] 95 | self.unique_labels = { l:i for i,l in enumerate(sorted(set(self.labels))) } 96 | self.labels = [ self.unique_labels[l] for l in self.labels ] 97 | self.num_classes = len(self.unique_labels) 98 | else: raise ValueError(f'dataset_name [{dataset_name}] not handled') 99 | 100 | 101 | # Weigths to balance datasets 102 | def get_class_weights(self): 103 | label_dict = self.get_label_dict() 104 | label_dict = { k:label_dict[k] for k in sorted(label_dict) } 105 | num_samples = sum([ len(v) for v in label_dict.values() ]) 106 | class_weigths = [ num_samples/(len(label_dict)*len(v)) for k,v in label_dict.items() ] 107 | return torch.tensor(class_weigths) 108 | 109 | 110 | # Crop the given event-streams in time 111 | def crop_in_time(self, total_events): 112 | # print('Cropping:', len(total_events)) 113 | if len(total_events) > self.num_sparse_frames: 114 | if not self.validation: # Crop sequence randomly 115 | init = np.random.randint(len(total_events) - self.num_sparse_frames) 116 | end = init + self.num_sparse_frames 117 | total_events = total_events[init:end] 118 | else: # Crop to the middle part 119 | init = (len(total_events) - self.num_sparse_frames) // 2 120 | end = init + self.num_sparse_frames 121 | total_events = total_events[init:end] 122 | # assert len(total_events) < num_sparse_frames, str(len(total_events)) + ' ' + str(num_sparse_frames) 123 | return total_events 124 | 125 | 126 | # Crop event-streams in space 127 | def crop_in_space(self, total_events): 128 | _, y_size, x_size, _ = total_events.shape 129 | if not self.validation: # Crop sequence randomly 130 | new_x_size = np.random.randint(self.x_lims[0], self.x_lims[1]+1) 131 | new_y_size = np.random.randint(self.y_lims[0], self.y_lims[1]+1) 132 | 133 | if self.patch_size != 1: 134 | new_x_size -= new_x_size % self.patch_size 135 | new_y_size -= new_y_size % self.patch_size 136 | 137 | x_init = np.random.randint(x_size - new_x_size+1); x_end = x_init + new_x_size 138 | y_init = np.random.randint(y_size - new_y_size+1); y_end = y_init + new_y_size 139 | total_events = total_events[:, y_init:y_end, x_init:x_end, :] 140 | else: # Crop to the middle part 141 | new_x_size = (self.x_lims[0] + self.x_lims[1])//2 142 | new_y_size = (self.y_lims[0] + self.y_lims[1])//2 143 | 144 | if self.patch_size != 1: 145 | new_x_size -= new_x_size % self.patch_size 146 | new_y_size -= new_y_size % self.patch_size 147 | 148 | x_init = (x_size - new_x_size)//2; x_end = x_init + new_x_size 149 | y_init = (y_size - new_y_size)//2; y_end = y_init + new_y_size 150 | total_events = total_events[:, y_init:y_end, x_init:x_end, :] 151 | assert total_events.shape[1] == new_y_size and total_events.shape[2] == new_x_size, print(total_events.shape, new_y_size, new_x_size) 152 | return total_events 153 | 154 | 155 | 156 | # Remove random events from sequence based on percentage 157 | # drop_mode == 'fixed' -> drop same pixels for all the sequence 158 | # drop_mode == 'rand' -> drop random events in each time-step 159 | def drop_token(self, total_events): 160 | if self.validation: 161 | return total_events 162 | if self.drop_mode == 'rand': 163 | mask = np.random.rand(*total_events.shape[:-1]) < self.drop_perc 164 | total_events[mask] = 0.0 165 | elif self.drop_mode == 'fixed': 166 | mask = np.random.rand(*total_events.shape[1:-1]) < self.drop_perc 167 | total_events[:, mask] = 0.0 168 | return total_events 169 | 170 | # Shift patches in space 171 | def shift(self, total_pixels, cropped_shape): 172 | height_diff, width_diff = self.height - cropped_shape[0], self.width - cropped_shape[1] 173 | if not self.validation: 174 | new_height_init = np.random.randint(0, height_diff) if height_diff != 0.0 else 0 175 | new_width_init = np.random.randint(0, width_diff) if width_diff != 0.0 else 0 176 | else: 177 | new_height_init, new_width_init = height_diff // 2, width_diff // 2 178 | 179 | new_height_init -= new_height_init % self.patch_size #; new_height_init += self.patch_size//2 180 | new_width_init -= new_width_init % self.patch_size #; new_width_init += self.patch_size//2 181 | 182 | for i in range(len(total_pixels)): 183 | total_pixels[i][:, 0] += new_height_init 184 | total_pixels[i][:, 1] += new_width_init 185 | return total_pixels 186 | 187 | 188 | def __len__(self): 189 | return len(self.samples) 190 | 191 | def get_label_dict(self): 192 | label_dict = { c:[] for c in set(self.labels) } 193 | for i,l in enumerate(self.labels): label_dict[l].append(i) 194 | for k in label_dict: label_dict[k] = torch.IntTensor(label_dict[k]) 195 | return label_dict 196 | 197 | 198 | # Return -> [num_timesteps, num_chunk_events, 2pol], [num_timesteps, num_chunk_events, 2pix_xy], [num_timesteps] 199 | def __getitem__(self, idx, return_sparse_array=False): 200 | 201 | filename = self.samples[idx] 202 | label = self.labels[idx] 203 | 204 | # Load sparse matrix 205 | total_events = pickle.load(open(os.path.join(self.samples_folder + filename), 'rb')) # events (t x H x W x 2) 206 | 207 | # Crop sequence to self.num_sparse_frames 208 | if 'max_sample_len_ms' in self.augmentation_params and self.augmentation_params['max_sample_len_ms'] != -1: 209 | total_events = self.crop_in_time(total_events) 210 | if 'random_frame_size' in self.augmentation_params and self.augmentation_params['random_frame_size'] is not None: 211 | total_events = self.crop_in_space(total_events) 212 | 213 | if not self.validation and self.h_flip and np.random.rand() > 0.5: total_events = total_events[:,:,::-1,:] 214 | 215 | 216 | total_pixels, total_polarity = [], [] 217 | current_chunk = None 218 | 219 | # Iterate until read all the total_events (max_sample_len_ms) 220 | sf_num = len(total_events) - 1 221 | while sf_num >= 0: 222 | 223 | # Get chunks by grouping sparse frames 224 | if current_chunk is None: 225 | current_chunk = total_events[max(0, sf_num-self.chunk_size):sf_num][::-1] 226 | current_chunk = current_chunk.todense() 227 | sf_num -= self.chunk_size 228 | if '1' in self.preproc_polarity: current_chunk = current_chunk.sum(-1, keepdims=True) 229 | else: 230 | sf = total_events[max(0, sf_num-self.num_extra_chunks):sf_num][::-1] 231 | sf = sf.todense() 232 | sf_num -= self.num_extra_chunks 233 | if '1' in self.preproc_polarity: sf = sf.sum(-1, keepdims=True) 234 | current_chunk = np.concatenate([current_chunk, sf]) 235 | 236 | 237 | if current_chunk.shape[0] < self.bins: continue 238 | # if current_chunk.shape[0] >= self.bins: 239 | # Divide time-window into bins 240 | bins_init = current_chunk.shape[0]; 241 | bins_step = bins_init//self.bins 242 | chunk_candidate = [] 243 | for ib_num, i in enumerate(list(range(0, bins_init, bins_step))[:self.bins]): 244 | if ib_num == self.bins-1: step = 99999 245 | else: step = bins_step 246 | chunk_candidate.append(current_chunk[i:i+step].sum(0)) 247 | chunk_candidate = np.stack(chunk_candidate, axis=-1).astype(float) 248 | chunk_candidate = chunk_candidate.reshape(chunk_candidate.shape[0], chunk_candidate.shape[1], chunk_candidate.shape[2]*chunk_candidate.shape[3]) 249 | 250 | # Extract patches 251 | polarity = view_as_blocks(chunk_candidate, (self.patch_size,self.patch_size, self.preproc_event_size)); 252 | # aggregate by pixel (unique), by patch (sum) -> get the ones with >= min_activations | (num_patches, bool) 253 | inds = (polarity.sum(-1)!=0).reshape(polarity.shape[0], polarity.shape[1], self.patch_size*self.patch_size) \ 254 | .sum(-1).reshape(polarity.shape[0] * polarity.shape[1]) >= self.min_activations_per_patch 255 | 256 | if inds.sum() == 0: continue 257 | # Check if chunk has the desired patch activations and #events 258 | if self.min_patches_per_chunk and inds.sum() < self.min_patches_per_chunk: continue 259 | 260 | # Reshape to (num_patches x token_dim) 261 | polarity = polarity.reshape(polarity.shape[0] * polarity.shape[1], self.patch_size*self.patch_size*self.preproc_event_size) # self.token_dim 262 | # Get pixel locations 263 | pixels = np.array([ (i+self.patch_size//2,j+self.patch_size//2) for i in range(0, chunk_candidate.shape[0], self.patch_size) for j in range(0, chunk_candidate.shape[1], self.patch_size) ]) 264 | 265 | inds = np.where(inds)[0] 266 | 267 | # Drop patch tokens 268 | # Apply over the final patch-tokens 269 | if not self.validation and len(inds)>0 and 'drop_token' in self.augmentation_params and self.augmentation_params['drop_token'][0] != 0.0: 270 | inds = np.random.choice(inds, replace=False, size=max(1, int(len(inds)*(1-self.augmentation_params['drop_token'][0])))) 271 | polarity, pixels = polarity[inds], pixels[inds] 272 | 273 | if 'log' in self.preproc_polarity: polarity = np.log(polarity + 1) 274 | else: raise ValueError('Not implemented', self.preproc_polarity) 275 | 276 | assert len(pixels) > 0 and len(polarity) > 0 277 | total_polarity.append(torch.tensor(polarity)) 278 | total_pixels.append(torch.tensor(pixels).long()) 279 | current_chunk = None 280 | 281 | 282 | if 'random_shift' in self.augmentation_params and self.augmentation_params['random_shift']: 283 | total_pixels = self.shift(total_pixels, total_events.shape[1:-1]) 284 | 285 | return total_polarity, total_pixels, label 286 | 287 | 288 | 289 | 290 | # Return the batch sample indices randomly. 291 | class CustomBatchSampler(): 292 | 293 | def __init__(self, batch_size, label_dict, sample_repetitions=1, drop_last=False): 294 | 295 | assert batch_size % sample_repetitions == 0 296 | self.batch_size = batch_size 297 | self.label_dict = label_dict 298 | self.sample_repetitions = sample_repetitions 299 | self.drop_last = drop_last 300 | self.generator = torch.Generator() 301 | self.generator.manual_seed(0) 302 | self.num_classes = len(self.label_dict) 303 | self.unique_labels = list(self.label_dict.keys()) 304 | 305 | def __len__(self): 306 | epoch_length = sum([ len(v) for v in self.label_dict.values() ])*self.sample_repetitions // self.batch_size 307 | return epoch_length 308 | 309 | def __iter__(self): 310 | 311 | total_labels = [] 312 | while True: 313 | inds = [] 314 | for b in range(self.batch_size // self.sample_repetitions): 315 | if len(total_labels) == 0: total_labels = self.unique_labels.copy() 316 | k = np.random.randint(0, len(total_labels), size=(1))[0] 317 | k = total_labels.pop(k) 318 | num_k_samples = len(self.label_dict[k]) 319 | ind = np.random.randint(0, num_k_samples, size=(1))[0] 320 | ind = self.label_dict[k][ind] 321 | for _ in range(self.sample_repetitions): inds.append(ind) 322 | 323 | yield inds 324 | 325 | 326 | # Pad sequences by timesteps and #events 327 | # Samples: ([batch_size], [timesteps/chunk], [events], event_data) 328 | def pad_list_of_sequences(samples, token_size, pre_padding = True): 329 | max_timesteps = max([ len(s) for s in samples ]) 330 | batch_size = len(samples) 331 | max_event_num = max([ chunk.shape[0] for sample in samples for chunk in sample ]) 332 | 333 | batch_data = torch.zeros(max_timesteps, batch_size, max_event_num, token_size) 334 | for num_sample, action_sample in enumerate(samples): 335 | num_chunks = len(action_sample) 336 | for chunk_num, chunk in enumerate(action_sample): 337 | chunk_events = chunk.shape[0] 338 | if chunk_events == 0: 339 | continue 340 | if pre_padding: batch_data[-(num_chunks-chunk_num), num_sample, -chunk_events:, :] = chunk 341 | else: batch_data[chunk_num, num_sample, :chunk_events, :] = chunk 342 | 343 | return batch_data 344 | 345 | 346 | 347 | class Event_DataModule(LightningDataModule): 348 | def __init__(self, batch_size, chunk_len_ms, 349 | patch_size, min_activations_per_patch, bins, 350 | min_patches_per_chunk, num_extra_chunks, 351 | augmentation_params, 352 | dataset_name, 353 | skip_last_event=False, sample_repetitions=1, preproc_polarity=None, 354 | custom_sampler = True, 355 | workers=8, pin_memory=False, classes_to_exclude=[], balance=None): 356 | super().__init__() 357 | self.batch_size = batch_size 358 | self.chunk_len_ms = chunk_len_ms 359 | self.patch_size = patch_size 360 | self.min_activations_per_patch = min_activations_per_patch 361 | self.bins = bins 362 | self.min_patches_per_chunk = min_patches_per_chunk 363 | self.num_extra_chunks = num_extra_chunks 364 | 365 | self.augmentation_params = augmentation_params 366 | self.dataset_name = dataset_name 367 | self.workers = workers 368 | self.sample_repetitions = sample_repetitions 369 | self.preproc_polarity = preproc_polarity 370 | self.skip_last_event = skip_last_event 371 | self.pin_memory = pin_memory 372 | self.classes_to_exclude = classes_to_exclude 373 | 374 | self.pre_padding = True 375 | self.custom_sampler = custom_sampler 376 | 377 | 378 | self.dataset_name = dataset_name 379 | if dataset_name == 'DVS128': 380 | self.data_folder = './datasets/DvsGesture/clean_dataset_frames_12000/' 381 | self.width, self.height = 128, 128 382 | self.num_classes = 12 - len(classes_to_exclude) 383 | self.class_mapping = copy.deepcopy(DVS128_class_mapping) 384 | for c in classes_to_exclude: del self.class_mapping[c] 385 | self.class_mapping = { i:l[1] for i,l in enumerate(sorted(self.class_mapping.items(), key=lambda x:x[0])) } 386 | elif dataset_name == 'ASL_DVS': 387 | self.data_folder = './datasets/ICCV2019_DVS_dataset/clean_dataset_frames_2000/' 388 | self.width, self.height = 240, 180 389 | self.num_classes = 24 390 | self.class_mapping = { i:l for i,l in enumerate('a b c d e f g h i k l m n o p q r s t u v w x y'.split()) } 391 | elif dataset_name == 'SLAnimals_3s': 392 | self.data_folder = './datasets/SL_animal_splits/dataset_3sets_12000/' 393 | self.width, self.height = 128, 128 394 | self.num_classes = 19 395 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 396 | elif dataset_name == 'SLAnimals_4s': 397 | self.data_folder = './datasets/SL_animal_splits/dataset_4sets_12000/' 398 | self.width, self.height = 128, 128 399 | self.num_classes = 19 400 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 401 | elif dataset_name == 'Caltech': 402 | self.data_folder = './datasets/N_Caltech_101/clean_dataset_frames_2000/' 403 | self.width, self.height = 240, 180 404 | self.num_classes = 101 405 | self.class_mapping = { i:l for i,l in enumerate(range(self.num_classes)) } 406 | else: raise ValueError(f'Dataset [{dataset_name}] not handled') 407 | 408 | 409 | self.preproc_event_size = 1 if '1' in self.preproc_polarity else 2 410 | self.preproc_event_size *= bins 411 | self.token_dim = patch_size*patch_size * self.preproc_event_size 412 | 413 | 414 | def custom_collate_fn(self, batch_samples): 415 | pols, pixels, labels = [], [], [] 416 | 417 | for num_sample, sample in enumerate(batch_samples): 418 | # Sample -> time_sequence 419 | # #samples == batch_size 420 | 421 | if sample is None or len(sample[0]) == 0: 422 | print('Empty sample') 423 | print(len(sample), len(sample[0])) 424 | continue 425 | 426 | pols.append(sample[0]) 427 | pixels.append(sample[1]) 428 | labels.append(sample[2]) 429 | 430 | if len(pols) == 0: return None, None, None 431 | token_size = pols[0][0].shape[-1] 432 | 433 | pols = pad_list_of_sequences(pols, token_size, self.pre_padding) 434 | pixels = pad_list_of_sequences(pixels, 2, self.pre_padding) 435 | 436 | pols, pixels, labels = pols, pixels.long(), torch.tensor(labels).long() 437 | return pols, pixels, labels 438 | 439 | 440 | def train_dataloader(self): 441 | dt = EventDataset(self.data_folder+'train/', chunk_len_ms = self.chunk_len_ms, 442 | validation=False, 443 | preproc_polarity=self.preproc_polarity, patch_size=self.patch_size, 444 | min_activations_per_patch=self.min_activations_per_patch, 445 | bins = self.bins, 446 | min_patches_per_chunk = self.min_patches_per_chunk, 447 | num_extra_chunks = self.num_extra_chunks, 448 | dataset_name=self.dataset_name, height=self.height, width=self.width, 449 | augmentation_params=self.augmentation_params, 450 | classes_to_exclude=self.classes_to_exclude) 451 | if self.custom_sampler: 452 | sampler = CustomBatchSampler(batch_size=self.batch_size, label_dict=dt.get_label_dict(), sample_repetitions=self.sample_repetitions) 453 | dl = DataLoader(dt, batch_sampler=sampler, collate_fn=self.custom_collate_fn, num_workers=self.workers, pin_memory=self.pin_memory) 454 | else: 455 | dl = DataLoader(dt, batch_size=self.batch_size, collate_fn=self.custom_collate_fn, shuffle=True, num_workers=self.workers, pin_memory=self.pin_memory) 456 | return dl 457 | def val_dataloader(self): 458 | dt = EventDataset(self.data_folder+'test/', chunk_len_ms = self.chunk_len_ms, 459 | validation=True, 460 | preproc_polarity=self.preproc_polarity, patch_size=self.patch_size, 461 | min_activations_per_patch=self.min_activations_per_patch, 462 | bins = self.bins, 463 | min_patches_per_chunk = self.min_patches_per_chunk, 464 | num_extra_chunks = self.num_extra_chunks, 465 | dataset_name=self.dataset_name, height=self.height, width=self.width, 466 | augmentation_params=self.augmentation_params, 467 | classes_to_exclude=self.classes_to_exclude) 468 | dl = DataLoader(dt, batch_size=(self.batch_size//2)+1, shuffle=False, collate_fn=self.custom_collate_fn, num_workers=self.workers, pin_memory=self.pin_memory) 469 | return dl 470 | 471 | 472 | 473 | 474 | 475 | -------------------------------------------------------------------------------- /dataset_scripts/asl.py: -------------------------------------------------------------------------------- 1 | import scipy.io 2 | import os 3 | from tqdm import tqdm 4 | import sparse 5 | import numpy as np 6 | import pickle 7 | 8 | from sklearn.model_selection import train_test_split 9 | from joblib import Parallel, delayed 10 | 11 | 12 | 13 | # Source data folder 14 | path_dataset = '../datasets/ICCV2019_DVS_dataset/' 15 | # Target data folder 16 | path_dataset_dst = '../datasets/ICCV2019_DVS_dataset/clean_dataset_frames_2000/' 17 | 18 | 19 | chunk_len_ms = 2 20 | chunk_len_us = chunk_len_ms*1000 21 | width = 240; height = 180 22 | 23 | 24 | total_samples = [ s for d in os.listdir(path_dataset) for s in os.listdir(os.path.join(path_dataset, d)) ] 25 | total_labels = [ s.split('_')[0] for s in total_samples ] 26 | 27 | train_samples, test_samples = train_test_split(total_samples, test_size=0.2, random_state=0, stratify=total_labels) 28 | 29 | 30 | 31 | def process_file_sample(path_dataset, label, f, train_samples): 32 | mode = 'train' if f in train_samples else 'test' 33 | filename_dst = path_dataset_dst + '/{}/'.format(mode) + '{}.pckl'.format(f[:-4]) 34 | if os.path.isfile(filename_dst): return 35 | 36 | mat = scipy.io.loadmat(os.path.join(path_dataset,label, f)) 37 | 38 | if mat['ts'][-1] < mat['ts'][0] > 200*1000: print(mat['ts'][-1], f) 39 | 40 | total_events = np.array([mat['x'], mat['y'], mat['ts'], mat['pol']]).transpose()[0] 41 | 42 | total_chunks = [] 43 | while total_events.shape[0] > 0: 44 | end_t = total_events[-1][2] 45 | chunk_inds = np.where(total_events[:,2] >= end_t - chunk_len_us)[0] 46 | if len(chunk_inds) <= 4: 47 | pass 48 | else: 49 | total_chunks.append(total_events[chunk_inds]) 50 | total_events = total_events[:chunk_inds.min()] 51 | if len(total_chunks) == 0: 52 | print('aaa') 53 | return 54 | total_chunks = total_chunks[::-1] 55 | 56 | total_frames = [] 57 | for chunk in total_chunks: 58 | frame = sparse.COO(chunk[:,[1,0,3]].transpose().astype('int32'), 59 | np.ones(chunk.shape[0]).astype('int32'), 60 | (height, width, 2)) # .to_dense() 61 | total_frames.append(frame) 62 | total_frames = sparse.stack(total_frames) 63 | 64 | total_frames = np.clip(total_frames, a_min=0, a_max=255) 65 | total_frames = total_frames.astype('uint8') 66 | 67 | if len(total_frames) > 200*1000 / chunk_len_us: print(mat['ts'][-1], f) 68 | 69 | pickle.dump(total_frames, open(filename_dst, 'wb')) 70 | 71 | 72 | label = os.listdir(path_dataset)[0] 73 | f = os.listdir(os.path.join(path_dataset, label))[0] 74 | 75 | Parallel(n_jobs=8)(delayed(process_file_sample)(path_dataset, label, f, train_samples) for label in tqdm(os.listdir(path_dataset)) for f in tqdm(os.listdir(os.path.join(path_dataset, label)))) 76 | 77 | 78 | # %% 79 | 80 | import os 81 | 82 | path_dataset_dst = '../../datasets/ICCV2019_DVS_dataset/clean_dataset_frames_2000/' 83 | class_mapping = { l:i for i,l in enumerate('a b c d e f g h i k l m n o p q r s t u v w x y'.split()) } 84 | 85 | for f in os.listdir(path_dataset_dst + 'train'): os.rename(path_dataset_dst + 'train/' + f, path_dataset_dst + 'train/' + f.replace('.pckl', f'_{class_mapping[f.split("_")[0]]}.pckl')) 86 | for f in os.listdir(path_dataset_dst + 'test'): os.rename(path_dataset_dst + 'test/' + f, path_dataset_dst + 'test/' + f.replace('.pckl', f'_{class_mapping[f.split("_")[0]]}.pckl')) 87 | 88 | 89 | -------------------------------------------------------------------------------- /dataset_scripts/caltech_101.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import sparse 4 | from sklearn.model_selection import train_test_split 5 | import pickle 6 | from tqdm import tqdm 7 | 8 | 9 | width, height = 240, 180 10 | chunk_len_ms = 2 11 | chunk_len_us = chunk_len_ms*1000 12 | size = 0.25 13 | 14 | 15 | # Source data folder 16 | path_dataset = '../datasets/N_Caltech_101/Caltech101/' 17 | # Target data folder 18 | path_dataset_dst = '../datasets/N_Caltech_101/clean_dataset_frames_2000/' 19 | 20 | if not os.path.isfile(path_dataset_dst): 21 | os.mkdir(path_dataset_dst) 22 | os.mkdir(path_dataset_dst + '/train') 23 | os.mkdir(path_dataset_dst + '/test') 24 | 25 | sample_files = [ os.path.join(path_dataset, cat, fs) for cat in os.listdir(path_dataset) for fs in os.listdir(os.path.join(path_dataset, cat)) ] 26 | 27 | train_samples, test_samples = train_test_split(sample_files, test_size=size, random_state=0, 28 | stratify=[ f.split('/')[-2] for f in sample_files ]) 29 | 30 | max_values = [] 31 | class_folders = os.listdir(path_dataset) 32 | for cat_id, cat in enumerate(tqdm(class_folders)): 33 | 34 | file_samples = os.listdir(os.path.join(path_dataset, cat)) 35 | for fs in file_samples: 36 | 37 | with open(os.path.join(path_dataset, cat, fs), "rb") as f: 38 | 39 | mode = 'train' if os.path.join(path_dataset, cat, fs) in train_samples else 'test' 40 | filename_dst = path_dataset_dst + f'{mode}/' + f'{cat}_{fs.replace(".bin", "")}_{cat_id}.pckl' 41 | 42 | raw_data = np.fromfile(open(os.path.join(path_dataset, cat, fs), 'rb'), dtype=np.uint8) 43 | 44 | raw_data = np.uint32(raw_data) 45 | all_y = raw_data[1::5] 46 | all_x = raw_data[0::5] 47 | all_p = (raw_data[2::5] & 128) >> 7 #bit 7 48 | all_ts = ((raw_data[2::5] & 127) << 16) | (raw_data[3::5] << 8) | (raw_data[4::5]) 49 | 50 | 51 | total_events = np.array([all_x, all_y, all_ts, all_p]).transpose() 52 | max_values.append(total_events.max(0)) 53 | 54 | total_chunks = [] 55 | while total_events.shape[0] > 0: 56 | end_t = total_events[-1][2] 57 | chunk_inds = np.where(total_events[:,2] >= end_t - chunk_len_us)[0] 58 | if len(chunk_inds) <= 4: 59 | pass 60 | else: 61 | total_chunks.append(total_events[chunk_inds]) 62 | total_events = total_events[:chunk_inds.min()-1] 63 | if len(total_chunks) == 0: continue 64 | total_chunks = total_chunks[::-1] 65 | 66 | total_frames = [] 67 | for chunk in total_chunks: 68 | frame = sparse.COO(chunk[:,[1,0,3]].transpose().astype('int32'), 69 | np.ones(chunk.shape[0]).astype('int32'), 70 | (height, width, 2)) # .to_dense() 71 | total_frames.append(frame) 72 | total_frames = sparse.stack(total_frames) 73 | 74 | total_frames = np.clip(total_frames, a_min=0, a_max=255) 75 | total_frames = total_frames.astype('uint8') 76 | 77 | pickle.dump(total_frames, open(filename_dst, 'wb')) 78 | 79 | -------------------------------------------------------------------------------- /dataset_scripts/dvs128.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from tqdm import tqdm 3 | import pickle 4 | import os 5 | import sparse 6 | os.chdir('..') 7 | 8 | 9 | 10 | chunk_len_ms = 12 11 | chunk_len_us = chunk_len_ms*1000 12 | height = width = 128 13 | mode = 'train' 14 | 15 | # Read dataset filenames 16 | if mode == 'train': 17 | # Source data folder 18 | path_dataset_src = './datasets/DvsGesture/clean_dataset/train/' 19 | # Target data folder 20 | path_dataset_dst = './datasets/DvsGesture/clean_dataset_frames_{}/train/'.format(chunk_len_us) 21 | else: 22 | path_dataset_src = './datasets/DvsGesture/clean_dataset/test/' 23 | path_dataset_dst = './datasets/DvsGesture/clean_dataset_frames_{}/test/'.format(chunk_len_us) 24 | 25 | event_files = os.listdir(path_dataset_src) 26 | if not os.path.isdir(path_dataset_dst): os.makedirs(path_dataset_dst) 27 | 28 | 29 | # %% 30 | 31 | 32 | for ef in tqdm(event_files): 33 | 34 | total_events, label = pickle.load(open(path_dataset_src+ef, 'rb')) 35 | total_events = total_events.astype('int32') 36 | 37 | total_chunks = [] 38 | while total_events.shape[0] > 0: 39 | end_t = total_events[-1][2] 40 | chunk_inds = np.where(total_events[:,2] >= end_t - chunk_len_us)[0] 41 | if len(chunk_inds) <= 4: 42 | pass 43 | else: 44 | total_chunks.append(total_events[chunk_inds]) 45 | total_events = total_events[:max(1, chunk_inds.min())-1] 46 | if len(total_chunks) == 0: 47 | print('aaa') 48 | continue 49 | total_chunks = total_chunks[::-1] 50 | 51 | total_frames = [] 52 | for chunk in total_chunks: 53 | frame = sparse.COO(chunk[:,[1,0,3]].transpose().astype('int32'), 54 | np.ones(chunk.shape[0]).astype('int32'), 55 | (height, width, 2)) # .to_dense() 56 | total_frames.append(frame) 57 | total_frames = sparse.stack(total_frames) 58 | 59 | total_frames = np.clip(total_frames, a_min=0, a_max=255) 60 | total_frames = total_frames.astype('uint8') 61 | 62 | pickle.dump(total_frames, open(path_dataset_dst + ef, 'wb')) 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /dataset_scripts/dvs128_split_dataset.py: -------------------------------------------------------------------------------- 1 | import aermanager 2 | from aermanager.aerparser import load_events_from_file 3 | import numpy as np 4 | import pandas as pd 5 | from tqdm import tqdm 6 | import pickle 7 | import os 8 | 9 | 10 | # Source data folder 11 | path_dataset_src = '../datasets/DvsGesture/' 12 | # Target data folder 13 | path_dataset_dst = '../datasets/DvsGesture/clean_dataset/' 14 | 15 | 16 | train_files, test_files = 'trials_to_train.txt', 'trials_to_test.txt' 17 | with open(path_dataset_src + train_files, 'r') as f: train_files = f.read().splitlines() 18 | with open(path_dataset_src + test_files, 'r') as f: test_files = f.read().splitlines() 19 | 20 | 21 | # Load and stor dataset event samples 22 | def store_samples(events_files, mode): 23 | for events_file in tqdm(events_files): 24 | if events_file == '': continue 25 | labels = pd.read_csv(path_dataset_src + events_file.replace('.aedat', '_labels.csv')) 26 | shape, events = load_events_from_file(path_dataset_src + events_file, parser=aermanager.parsers.parse_dvs_ibm) 27 | 28 | # Load user samples 29 | # Class 0 for non action 30 | time_segment_class = [] # [(t_init, t_end, class)] 31 | prev_event = 0 32 | for _,row in labels.iterrows(): 33 | if (row.startTime_usec-1 - prev_event) > 0: time_segment_class.append((prev_event, row.startTime_usec-1, 0, (row.startTime_usec-1 - prev_event)/1000)) 34 | if ((row.endTime_usec - row.startTime_usec)) > 0: time_segment_class.append((row.startTime_usec, row.endTime_usec, row['class'], (row.endTime_usec - row.startTime_usec)/1000)) 35 | prev_event = row.endTime_usec + 1 36 | time_segment_class.append((prev_event, np.inf, 0)) 37 | 38 | total_events = [] 39 | curr_event = [] 40 | # for e in tqdm(events): 41 | for i, e in enumerate(events): 42 | if e[2] >= time_segment_class[0][1]: 43 | # Store event 44 | if len(curr_event) > 1: total_events.append((time_segment_class[0], len(curr_event), np.array(curr_event))) 45 | else: print(' ** EVENT ERROR:', events_file.replace('.aedat','') + '_num{:02d}_label{:02d}.pckl'.format(i, time_segment_class[0][2]), time_segment_class[0], len(curr_event)) 46 | time_segment_class = time_segment_class[1:] 47 | curr_event = [] 48 | curr_event.append(list(e)) 49 | 50 | if len(curr_event) > 1: total_events.append((time_segment_class[0], len(curr_event), np.array(curr_event))) 51 | time_segment_class = time_segment_class[1:] 52 | curr_event = [] 53 | 54 | for i, (meta, _, events) in enumerate(total_events): 55 | pickle.dump((events, meta[2]), 56 | open(os.path.join(path_dataset_dst, mode, events_file.replace('.aedat','') + '_num{:02d}_label{:02d}.pckl'.format(i, meta[2])), 'wb')) 57 | 58 | 59 | store_samples(train_files, 'train') 60 | store_samples(test_files, 'test') 61 | 62 | -------------------------------------------------------------------------------- /dataset_scripts/sl_animals.py: -------------------------------------------------------------------------------- 1 | import os 2 | os.chdir('..') 3 | import pandas as pd 4 | import numpy as np 5 | import sparse 6 | import pickle 7 | 8 | import aermanager 9 | from aermanager.aerparser import load_events_from_file 10 | from sklearn.model_selection import train_test_split 11 | from tqdm import tqdm 12 | 13 | 14 | np.random.seed(0) 15 | 16 | chunk_len_ms = 2 17 | chunk_len_us = chunk_len_ms*1000 18 | height, width = 128, 128 19 | size = 0.25 20 | 21 | 22 | # Source data folder 23 | path_dataset = './datasets/SL_Animals/' 24 | files = os.listdir(path_dataset + 'allusers_aedat/') 25 | parser = aermanager.parsers.parse_dvs_128 26 | 27 | 28 | # Target data folder 29 | if not os.path.isdir(path_dataset + 'SL_animal_splits'): 30 | os.mkdir(path_dataset + 'SL_animal_splits') 31 | os.makedirs(path_dataset + 'SL_animal_splits/' + f'dataset_4sets_{chunk_len_us}/train') 32 | os.makedirs(path_dataset + 'SL_animal_splits/' + f'dataset_4sets_{chunk_len_us}/test') 33 | os.makedirs(path_dataset + 'SL_animal_splits/' + f'dataset_3sets_{chunk_len_us}/train') 34 | os.makedirs(path_dataset + 'SL_animal_splits/' + f'dataset_3sets_{chunk_len_us}/test') 35 | 36 | 37 | train_samples_4sets, test_samples_4sets = train_test_split(files, test_size=size, random_state=0, 38 | stratify=[ f[:-6].split('_')[-1] for f in files ]) 39 | 40 | train_samples_3sets, test_samples_3sets = train_test_split([ f for f in files if '_indoor' not in f ], test_size=size, random_state=0, 41 | stratify=[ f[:-6].split('_')[-1] for f in files if '_indoor' not in f]) 42 | 43 | 44 | for events_file in tqdm(files): 45 | shape, events = load_events_from_file(path_dataset + 'allusers_aedat/' + events_file, parser=parser) 46 | labels = pd.read_csv(path_dataset + 'tags_updated_19_08_2020/' + events_file.replace('.aedat', '.csv')) 47 | filename_dst = path_dataset + 'SL_animal_splits/' + f'dataset_{{}}_{chunk_len_us}/{{}}/' + \ 48 | events_file.replace('.aedat', '_{}_{}.pckl') 49 | 50 | for _,row in labels.iterrows(): 51 | 52 | sample_events = events[row.startTime_ev:row.endTime_ev] 53 | 54 | total_events = np.array([sample_events['x'], sample_events['y'], sample_events['t'], sample_events['p']]).transpose() 55 | 56 | total_chunks = [] 57 | while total_events.shape[0] > 0: 58 | end_t = total_events[-1][2] 59 | chunk_inds = np.where(total_events[:,2] >= end_t - chunk_len_us)[0] 60 | if len(chunk_inds) <= 4: 61 | pass 62 | else: 63 | total_chunks.append(total_events[chunk_inds]) 64 | total_events = total_events[:max(1, chunk_inds.min())-1] 65 | if len(total_chunks) == 0: continue 66 | total_chunks = total_chunks[::-1] 67 | 68 | 69 | total_frames = [] 70 | for chunk in total_chunks: 71 | frame = sparse.COO(chunk[:,[0,1,3]].transpose().astype('int32'), 72 | np.ones(chunk.shape[0]).astype('int32'), 73 | (height, width, 2)) # .to_dense() 74 | total_frames.append(frame) 75 | total_frames = sparse.stack(total_frames) 76 | 77 | total_frames = np.clip(total_frames, a_min=0, a_max=255) 78 | total_frames = total_frames.astype('uint8') 79 | 80 | if '_sunlight' in events_file: val_set = 'S4' # S4 indoors with frontal sunlight 81 | elif '_indoor' in events_file: val_set = 'S3' # S3 indoors neon light 82 | elif '_dc' in events_file: val_set = 'S2' # S2 natural side light 83 | elif '_imse' in events_file: val_set = 'S1' # S1 natural side light 84 | else: raise ValueError('Set not handled') 85 | 86 | if events_file in train_samples_3sets: 87 | pickle.dump(total_frames, open(filename_dst.format('3sets', 'train', val_set, row['class']), 'wb')) 88 | if events_file in test_samples_3sets: 89 | pickle.dump(total_frames, open(filename_dst.format('3sets', 'test', val_set, row['class']), 'wb')) 90 | if events_file in train_samples_4sets: 91 | pickle.dump(total_frames, open(filename_dst.format('4sets', 'train', val_set, row['class']), 'wb')) 92 | if events_file in test_samples_4sets: 93 | pickle.dump(total_frames, open(filename_dst.format('4sets', 'test', val_set, row['class']), 'wb')) 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /evaluation_stats.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from data_generation import Event_DataModule 3 | 4 | from pytorch_lightning.metrics import Accuracy 5 | import pandas as pd 6 | import json 7 | from tqdm import tqdm 8 | import time 9 | import numpy as np 10 | 11 | import evaluation_utils 12 | from trainer import EvNetModel 13 | 14 | 15 | device = 'cuda:0' 16 | # device = 'cpu' 17 | 18 | 19 | path_model = './pretrained_models/DVS128_10_24ms_dwn/' 20 | # path_model = './pretrained_models/DVS128_11_24ms_dwn/' 21 | # path_model = './pretrained_models/SLAnimals_4s_48ms_dwn/' 22 | # path_model = './pretrained_models/SLAnimals_3s_48ms_dwn/' 23 | # path_model = './pretrained_models/ASL_DVS_dwn/' 24 | 25 | 26 | path_weights = evaluation_utils.get_best_weigths(path_model, 'val_acc', 'max') 27 | evaluation_utils.plot_training_evolution(path_model) 28 | all_params = json.load(open(path_model + '/all_params.json', 'r')) 29 | model = EvNetModel.load_from_checkpoint(path_weights, map_location=torch.device('cpu'), **all_params).eval().to(device) 30 | 31 | def get_params(model): 32 | total_params = pd.DataFrame([ (n.split('.')[0],p.numel()/1000000) for n,p in model.backbone.named_parameters() if p.requires_grad ]).groupby(0).sum().sum().iloc[0] 33 | pos_encoding_params = pd.DataFrame([ (n.split('.')[0],p.numel()/1000000) for n,p in model.backbone.named_parameters() if p.requires_grad ]).groupby(0).sum().loc['pos_encoding'].iloc[0] 34 | stats = { 35 | 'total_params': total_params, 36 | 'backbone_params': total_params - pos_encoding_params, 37 | 'pos_encoding_params': pos_encoding_params 38 | } 39 | return stats 40 | 41 | print('\n\n ** Calculating parameter statistics') 42 | param_stats = get_params(model) 43 | 44 | # %% 45 | 46 | def get_complexity_stats(model, all_params): 47 | data_params = all_params['data_params'] 48 | data_params['batch_size'] = 1 49 | data_params['pin_memory'] = False 50 | data_params['sample_repetitions'] = 1 51 | dm = Event_DataModule(**data_params) 52 | dl = dm.val_dataloader() 53 | 54 | # https://github.com/sovrasov/flops-counter.pytorch 55 | from ptflops import get_model_complexity_info 56 | 57 | total_flops, total_macs, total_params, total_act_patches = [], [], [], [] 58 | total_time_flops = [] 59 | for polarity, pixels, labels in tqdm(dl): 60 | if polarity is None: continue 61 | polarity, pixels, labels = polarity.to(device), pixels.to(device), labels.to(device) 62 | 63 | for ts in range(len(polarity)): 64 | num_patches = sum(polarity[ts:ts+1].sum(-1).sum(0).sum(0) != 0) 65 | mask = polarity[ts:ts+1].sum(-1).sum(0).sum(0) != 0 66 | pol_t, pix_t = polarity[ts:ts+1][:,:,mask,:], pixels[ts:ts+1][:,:,mask,:] 67 | t = time.time() 68 | macs, params = get_model_complexity_info(model.backbone, 69 | ({'kv': pol_t, 'pixels': pix_t},), 70 | input_constructor=lambda x: x[0], 71 | as_strings=False, 72 | print_per_layer_stat=False, verbose=False) 73 | total_time_flops.append(time.time() - t) 74 | flops = 2*macs 75 | total_act_patches.append(num_patches.cpu()) 76 | total_flops.append(flops); total_macs.append(macs); total_params.append(params) 77 | 78 | return np.mean(total_flops), np.mean(total_act_patches) 79 | 80 | 81 | print('\n\n ** Calculating complexity statistics') 82 | flops, activated_patches = get_complexity_stats(model, all_params) 83 | 84 | 85 | # %% 86 | 87 | # ============================================================================= 88 | # Time analysis 89 | # ============================================================================= 90 | 91 | def get_time_accuracy_stats(model, all_params): 92 | data_params = all_params['data_params'] 93 | data_params['batch_size'] = 1 94 | data_params['pin_memory'] = False 95 | data_params['sample_repetitions'] = 1 96 | dm = Event_DataModule(**data_params) 97 | dl = dm.val_dataloader() 98 | 99 | total_time = [] 100 | y_true, y_pred = [], [] 101 | for polarity, pixels, labels in tqdm(dl): 102 | if polarity is None: continue 103 | polarity, pixels, labels = polarity.to(device), pixels.to(device), labels.to(device) 104 | t = time.time() 105 | embs, clf_logits = model(polarity, pixels) 106 | total_time.append((time.time() - t)/len(polarity)) 107 | 108 | y_true.append(labels[0]) 109 | y_pred.append(clf_logits.argmax()) 110 | y_true, y_pred = torch.stack(y_true).to("cpu"), torch.stack(y_pred).to("cpu") 111 | acc_score = Accuracy()(y_true, y_pred).item() 112 | 113 | logs = evaluation_utils.load_csv_logs_as_df(path_model) 114 | train_acc = logs[~logs['val_acc'].isna()]['val_acc'].max() 115 | 116 | return np.mean(total_time)*1000, train_acc, acc_score 117 | 118 | print('\n\n ** Calculating time and accuracy statistics') 119 | avg_time, train_acc, val_acc = get_time_accuracy_stats(model, all_params) 120 | 121 | 122 | # %% 123 | 124 | print(f' - Model parameters: {param_stats["total_params"]:.2f} M | pos_encoding_parameters: {param_stats["pos_encoding_params"]:.2f} M | backbone_parameters: {param_stats["backbone_params"]:.2f} M ') 125 | print(f' - Model FLOPs: {flops*1e-9:.2f} G') 126 | print(f' - Average activated patches in [{all_params["data_params"]["dataset_name"]}]: {activated_patches:.1f}') 127 | print(f' - Average processing time per time-window in device [{device}]: {avg_time:.4f} ms') 128 | print(f' - Validation accuracy reported during training: {train_acc*100:.2f} %') 129 | print(f' - Validation accuracy reported after training: {val_acc*100:.2f} %') 130 | 131 | 132 | -------------------------------------------------------------------------------- /evaluation_utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from data_generation import Event_DataModule 3 | 4 | from pytorch_lightning.metrics import Accuracy 5 | from sklearn.metrics import confusion_matrix 6 | import pandas as pd 7 | import json 8 | from tqdm import tqdm 9 | import time 10 | import numpy as np 11 | import pickle 12 | import matplotlib.pyplot as plt 13 | import os 14 | 15 | 16 | def get_best_weigths(path_model, metric, mode): 17 | assert mode in ['min', 'max'] 18 | mode = max if mode == 'max' else min 19 | w = os.listdir(os.path.join(path_model, 'weights')) 20 | path_weights = mode(w, key=lambda x: [ float(s[len(metric)+1:len(metric)+1+7]) for s in x.split('-') if s.startswith(metric) ][0]) 21 | return os.path.join(path_model, 'weights',path_weights) 22 | 23 | 24 | def load_csv_logs_as_df(path_model): 25 | log_file = path_model + '/train_log/version_0/metrics.csv' 26 | logs = pd.read_csv(log_file) 27 | for i, row in logs[logs.epoch.isna()].iterrows(): 28 | candidates = logs[(~logs.epoch.isna()) & (logs.step >= int(row.step))].epoch.min() 29 | logs.loc[i, 'epoch'] = candidates 30 | return logs 31 | 32 | def plot_training_evolution(path_model): 33 | 34 | logs = load_csv_logs_as_df(path_model) 35 | 36 | lr_col = [ c for c in logs.columns if 'lr' in c ][0] 37 | lr = logs[~logs[lr_col].isna()][lr_col] 38 | c = [ c for c in logs.columns if 'val_acc' in c ][0] 39 | val_acc = logs[~logs[c].isna()][c] 40 | 41 | fig, ax1 = plt.subplots(figsize=(12,6), dpi=200) 42 | ax2 = ax1.twinx() 43 | ax3 = ax1.twinx() 44 | 45 | for c in [ c for c in logs.columns if 'val_' in c and 'acc' not in c ]: 46 | loss = logs[~logs[c].isna()][c] 47 | ax1.plot(loss.values, label=c) 48 | 49 | ax2.plot(val_acc.values, 'g') 50 | ax3.plot(lr.values, 'r') 51 | 52 | if 'ASL' in path_model: ax2.set_ylim(0.95, 1) # Acc lims 53 | else: ax2.set_ylim(0.5, 1) # Acc lims 54 | 55 | ax1.set_ylabel('val_loss', color='b', fontsize=18) 56 | ax2.set_ylabel('val_acc', color='g', fontsize=18) 57 | ax3.set_ylabel('lr', color='r', fontsize=18) 58 | 59 | ax2.hlines(val_acc.max(), 0, len(val_acc.values), color='g', linestyle='--', alpha=0.7) 60 | ax1.hlines(logs[~logs['val_loss_total'].isna()]['val_loss_total'].min(), 0, len(val_acc.values), color='y', linestyle='--', alpha=0.7) 61 | 62 | 63 | ax3.spines['right'].set_position(('outward', 60)) 64 | fig.tight_layout() 65 | 66 | plt.title('{} | Acc.: {:.4f} | Loss: {:.4f}'.format(' | '.join(path_model.split('/')[-3:]), val_acc.max(), 67 | logs[~logs['val_loss_total'].isna()]['val_loss_total'].min()), fontsize=16) 68 | ax1.legend() 69 | 70 | plt.show() 71 | 72 | 73 | def get_evaluation_results(path_model, path_weights, skip_validation=False, force=False, device='cpu'): 74 | 75 | all_params = json.load(open(path_model + '/all_params.json', 'r')) 76 | stats_filename = path_model + '/stats_validation.json' 77 | cm_filename = path_model + '/confussion_matrix.pckl' 78 | if not force and os.path.isfile(stats_filename): 79 | df_cm = pickle.load(open(cm_filename, 'rb')) if os.path.isfile(cm_filename) else None 80 | return all_params, json.load(open(stats_filename, 'r')),df_cm 81 | 82 | stats = {} 83 | logs = load_csv_logs_as_df(path_model) 84 | c = [ c for c in logs.columns if 'val_acc' in c ][0] 85 | stats['training_val_acc'] = logs[~logs[c].isna()][c].max() 86 | stats['training_val_loss'] = logs[~logs['val_loss_total'].isna()]['val_loss_total'].min() 87 | stats['training_val_loss_total'] = logs[~logs['val_loss_total'].isna()]['val_loss_total'].min() 88 | stats['num_epochs'] = int(logs['epoch'].max()) 89 | data_params = all_params['data_params'] 90 | stats['chunk_len_ms'] = data_params['chunk_len_ms'] 91 | 92 | # Load model and logs 93 | if not skip_validation: 94 | from trainer import EvNetModel 95 | # model = EvNetModel.load_from_checkpoint(path_weights, map_location=torch.device('cpu')).eval().to(device) 96 | model = EvNetModel.load_from_checkpoint(path_weights, map_location=torch.device('cpu'), **all_params).eval().to(device) 97 | 98 | # Load data 99 | data_params['batch_size'] = 1 100 | data_params['pin_memory'] = False 101 | # data_params['workers'] = 1 102 | dm = Event_DataModule(**data_params) 103 | dl = dm.val_dataloader() 104 | print();print(' * Loading val data') 105 | val_data = [ d for d in tqdm(dl) ] 106 | 107 | # Get predictions and accuracy 108 | print();print(' * Evaluating...') 109 | t = time.time() 110 | y_true, y_pred = [], [] 111 | for polarity, pixels, labels in tqdm(val_data): 112 | polarity, pixels, label = polarity.to(device), pixels.to(device), labels.to(device) 113 | embs, clf_logits = model(polarity, pixels) 114 | y_true.append(label[0]) 115 | y_pred.append(clf_logits.argmax()) 116 | t = time.time() - t 117 | y_true, y_pred = torch.stack(y_true).to("cpu"), torch.stack(y_pred).to("cpu") 118 | acc_score = Accuracy()(y_true, y_pred).item() 119 | 120 | # Get stats 121 | total_time_ms = t*1000 122 | num_samples = len(val_data) 123 | total_chunks = [ d[0].shape[0] for d in val_data ] 124 | num_chunks = sum(total_chunks) 125 | total_events = [ d[0].shape[2] for d in val_data ] 126 | 127 | stats['validation_val_acc'] = acc_score 128 | stats['sequence_ms'] = total_time_ms/num_samples 129 | stats['chunk_ms'] = total_time_ms/num_chunks 130 | stats['events_per_chunk'] = {'mean': np.mean(total_events), 'median': np.median(total_events), 'p05': np.percentile(total_events, 5), 'p95': np.percentile(total_events, 95)} 131 | stats['ms/ms'] = stats['chunk_ms'] / data_params['chunk_len_ms'] 132 | 133 | print('*'*40) 134 | print('*'*40) 135 | print(stats) 136 | print('*'*40) 137 | print('*'*40) 138 | 139 | 140 | # Calculate confussion matrix 141 | class_mapping = dm.class_mapping 142 | class_mapping = { k:'{}. {}'.format(k,v) for k,v in class_mapping.items() } 143 | labels_mapping = { v:k for k,v in dl.dataset.unique_labels.items() } 144 | y_true_cm = [ class_mapping[l] for l in y_true.numpy() ] 145 | y_pred_cm = [ class_mapping[l] for l in y_pred.numpy() ] 146 | labels = sorted(set(y_true_cm), key=lambda x: int(x.split()[0][:-1])) 147 | cm = confusion_matrix(y_true_cm, y_pred_cm, normalize='true', labels=labels) 148 | df_cm = pd.DataFrame(cm, index = labels, columns = labels) 149 | pickle.dump(df_cm, open(cm_filename, 'wb')) 150 | print('*'*40) 151 | print('*'*40) 152 | print(df_cm) 153 | print('*'*40) 154 | print('*'*40) 155 | 156 | else: 157 | def_val = 0.0 158 | stats['validation_val_acc'] = def_val 159 | stats['sequence_ms'] = def_val 160 | stats['chunk_ms'] = def_val 161 | stats['events_per_chunk'] = def_val 162 | stats['ms/ms'] = def_val 163 | df_cm = None 164 | 165 | 166 | return all_params, stats, df_cm 167 | 168 | 169 | 170 | 171 | -------------------------------------------------------------------------------- /model_overview_v6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlbertoSabater/EventTransformer/7589d46427741fbaba72f27d694247fdfd2d00c8/model_overview_v6.png -------------------------------------------------------------------------------- /models/EvT.py: -------------------------------------------------------------------------------- 1 | from torch import nn 2 | import torch 3 | import torch.nn.functional as F 4 | from torch.distributions import normal 5 | 6 | import sys 7 | sys.path.append('../') 8 | from models.positional_encoding import fourier_features 9 | 10 | import os 11 | import copy 12 | 13 | 14 | 15 | 16 | # ============================================================================= 17 | # Token processing blocks 18 | # ============================================================================= 19 | 20 | # ============================================================================= 21 | # Processing blocks 22 | # X-attention input 23 | # Q/z_input -> (#latent_embs, batch_size, embed_dim) 24 | # K/V/x -> (#events, batch_size, embed_dim) 25 | # key_padding_mask -> (batch_size, #event) 26 | # output -> (#latent_embs, batch_size, embed_dim) 27 | # ============================================================================= 28 | class AttentionBlock(nn.Module): # PerceiverAttentionBlock 29 | def __init__(self, opt_dim, heads, dropout, att_dropout, **args): 30 | super(AttentionBlock, self).__init__() 31 | 32 | self.layer_norm_x = nn.LayerNorm([opt_dim]) 33 | self.layer_norm_1 = nn.LayerNorm([opt_dim]) 34 | self.layer_norm_att = nn.LayerNorm([opt_dim]) 35 | 36 | self.attention = nn.MultiheadAttention( 37 | opt_dim, # embed_dim 38 | heads, # num_heads 39 | dropout=att_dropout, 40 | bias=True, 41 | add_bias_kv=True, 42 | ) 43 | self.dropout = nn.Dropout(p=dropout) 44 | self.linear1 = nn.Linear(opt_dim, opt_dim) 45 | self.layer_norm_2 = nn.LayerNorm([opt_dim]) 46 | self.linear2 = nn.Linear(opt_dim, opt_dim) 47 | self.linear3 = nn.Linear(opt_dim, opt_dim) 48 | 49 | 50 | def forward(self, x, z_input, mask=None, q_mask=None, **args): 51 | x = self.layer_norm_x(x) 52 | z = self.layer_norm_1(z_input) 53 | 54 | z_att, _ = self.attention(z, x, x, key_padding_mask=mask, attn_mask=q_mask) # Q, K, V 55 | 56 | z_att = z_att + z_input 57 | z = self.layer_norm_att(z_att) 58 | 59 | z = self.dropout(z) 60 | z = self.linear1(z) 61 | z = torch.nn.GELU()(z) 62 | 63 | z = self.layer_norm_2(z) 64 | z = self.linear2(z) 65 | z = torch.nn.GELU()(z) 66 | z = self.dropout(z) 67 | z = self.linear3(z) 68 | 69 | return z + z_att 70 | 71 | 72 | class TransformerBlock(nn.Module): 73 | def __init__(self, opt_dim, latent_blocks, dropout, att_dropout, heads, cross_heads, **args): 74 | super(TransformerBlock, self).__init__() 75 | 76 | self.cross_attention = AttentionBlock(opt_dim=opt_dim, heads=cross_heads, dropout=dropout, att_dropout=att_dropout) 77 | self.latent_attentions = nn.ModuleList([ 78 | AttentionBlock(opt_dim=opt_dim, heads=heads, dropout=dropout, att_dropout=att_dropout) for _ in range(latent_blocks) 79 | ]) 80 | 81 | def forward(self, x_input, z, mask=None, q_mask=None, **args): 82 | z = self.cross_attention(x_input, z, mask=mask, q_mask=q_mask) 83 | for latent_attention in self.latent_attentions: 84 | z = latent_attention(z, z, q_mask=q_mask) 85 | return z 86 | 87 | 88 | 89 | # Feed Forward Net 90 | class MLPBlock(nn.Module): 91 | def __init__(self, ipt_dim, embed_dim, init_layers, 92 | add_x_input=False, dropout=0.0, **args): #, num_layers 93 | super(MLPBlock, self).__init__() 94 | self.embed_dim = embed_dim 95 | self.add_x_input = add_x_input 96 | self.dropout = dropout 97 | if self.dropout > 0.0: self.dropout = nn.Dropout(p=dropout) 98 | self.seq_init = self._get_sequential_block(init_layers, ipt_dim) 99 | 100 | 101 | 102 | def _get_sequential_block(self, layers, ipt_dim): 103 | seq = [] 104 | for l in layers: 105 | l_name, opt_dim, activation = l.split('_'); opt_dim = int(opt_dim) 106 | if opt_dim == -1: opt_dim = self.embed_dim 107 | if self.dropout: seq.append(self.dropout) 108 | # Layer type 109 | if l_name == 'ff': seq.append(nn.Linear(ipt_dim, opt_dim)) 110 | else: raise ValueError(f'MLPBlock l_name [{l_name}] not handled') 111 | # Layer activation 112 | if activation == 'rel': seq.append(nn.ReLU()) 113 | elif activation == 'gel': seq.append(nn.GELU()) 114 | else: raise ValueError(f'MLPBlock activation [{activation}] not handled') 115 | ipt_dim = opt_dim 116 | return nn.Sequential(*seq) 117 | 118 | # x_input -> (#events, batch_size, emb_dim) 119 | # mask -> (batch_size, #events) -> (#events, batch_size) 120 | def forward(self, x_input, mask=None, pos_embs=None, **args): 121 | x = self.seq_init(x_input) 122 | if mask is not None: 123 | mask = mask.reshape(mask.shape[1], mask.shape[0]) 124 | 125 | if self.add_x_input: x = x + x_input 126 | 127 | return x 128 | 129 | 130 | 131 | def get_block(name, params): 132 | if name == 'MLP': return MLPBlock(**params) 133 | elif name == 'TransformerBlock': return TransformerBlock(**params) 134 | else: raise ValueError(f'Block [{name}] not implemented') 135 | 136 | 137 | 138 | 139 | # Transforms a set of latent vectors/Q into a single descriptor 140 | class LatentEmbsCompressor(nn.Module): 141 | 142 | # Linear + compressor 143 | def __init__(self, opt_dim, clf_mode, params, embs_norm): 144 | super(LatentEmbsCompressor, self).__init__() 145 | self.clf_mode = clf_mode 146 | self.linear1 = nn.Linear(opt_dim, opt_dim) 147 | if embs_norm: self.layer_norm = nn.LayerNorm([opt_dim]) 148 | self.embs_norm = embs_norm 149 | 150 | # batch_size x num_latent x emb_dim 151 | def forward(self, z): 152 | if self.embs_norm: z = self.layer_norm(z) 153 | z = self.linear1(z) 154 | z = F.relu(z) 155 | if self.clf_mode == 'gap': 156 | # Average every latent 157 | z = z.mean(dim=0) 158 | else: raise ValueError('clf_mode [{}] nor handled'.format(self.clf_mode)) 159 | 160 | return z 161 | 162 | 163 | # ============================================================================= 164 | # Backbone 165 | # ============================================================================= 166 | class EvNetBackbone(nn.Module): 167 | def __init__(self, 168 | pos_encoding, # Positional encoding params -> {name, {params}} 169 | token_dim, # Size of the flattened patch_tokens 170 | embed_dim, # Dimensionality of the latent_vectors and patch tokens 171 | num_latent_vectors, # Number of latent vectors 172 | event_projection, # Event Pre-processing Net {name, {params}} 173 | preproc_events, # Event Pre-processing Net (after positional encoding) {name, {params}} 174 | proc_events, # Event Processing Net (with skip connection) {name, {params}} 175 | proc_memory, # Attention Layers {name, {params}} 176 | return_last_q, # Return processed latent vectors or updated ones 177 | proc_embs, # Latent Vectors summarization Net {clf_mode, params} 178 | downsample_pos_enc, # Minimize positional encoding size 179 | pos_enc_grad=False, # Learnable latent vectors? 180 | model_version=None, # Dummy 181 | # **qargs, # Remove 182 | ): 183 | super(EvNetBackbone, self).__init__() 184 | 185 | self.return_last_q = return_last_q 186 | 187 | self.num_latent_vectors = num_latent_vectors 188 | self.downsample_pos_enc = downsample_pos_enc 189 | self.memory_vertical = nn.Parameter(normal.Normal(0.0, 0.2).sample((num_latent_vectors, embed_dim)).clip(-2,2), requires_grad=True) 190 | 191 | # Positional encodings 192 | if pos_encoding is not None: 193 | if pos_encoding['name'] == 'fourier': 194 | if pos_encoding['params']['bands'] == -1: pos_encoding['params']['bands'] = embed_dim//4 195 | # frame_shape, fourier_bands 196 | pos_enc_params = copy.deepcopy(pos_encoding['params']) 197 | pos_enc_params['shape'] = (pos_encoding['params']['shape'][0]//downsample_pos_enc, pos_encoding['params']['shape'][1]//downsample_pos_enc) 198 | self.pos_encoding = nn.Parameter(fourier_features(**pos_enc_params).permute(1,2,0), requires_grad=pos_enc_grad) 199 | pos_emb_dim = self.pos_encoding.shape[2] 200 | self.pos_encoding = self.pos_encoding.type_as(self.memory_vertical) 201 | else: 202 | raise ValueError('Positional Encoding[{}] not implemented'.format(pos_encoding['name'])) 203 | else: 204 | self.pos_encoding = None 205 | print(' ** Not using pos_encoding') 206 | 207 | 208 | # Event pre-proc block -> Linear transformation on tokens 209 | event_projection['params']['embed_dim'] = embed_dim 210 | self.event_projection = get_block(event_projection['name'], {**event_projection['params'], **{'ipt_dim': token_dim}}) 211 | 212 | # Events preprocessing -> Linear transformation on tokens 213 | self.preproc_events = preproc_events 214 | preproc_events['params']['embed_dim'] = embed_dim 215 | self.preproc_block_events = get_block(preproc_events['name'], {**preproc_events['params'], 216 | **{'ipt_dim': int(event_projection['params']['init_layers'][-1].split('_')[1])+pos_emb_dim}}) 217 | 218 | # Transforms events at each level 219 | proc_events['params']['opt_dim'] = embed_dim 220 | proc_events['params']['ipt_dim'] = embed_dim 221 | proc_events['params']['embed_dim'] = embed_dim 222 | self.proc_event_blocks = nn.ModuleList([ get_block(proc_events['name'], proc_events['params']) ]) 223 | 224 | # Transforms latent embeddings at each level 225 | proc_memory['params']['opt_dim'] = embed_dim 226 | proc_memory['params']['embed_dim'] = embed_dim 227 | self.proc_memory_blocks = nn.ModuleList([ get_block(proc_memory['name'], proc_memory['params']) ]) 228 | 229 | proc_embs['opt_dim'] = embed_dim 230 | proc_embs['params']['embed_dim'] = embed_dim 231 | self.proc_embs_block = LatentEmbsCompressor(**proc_embs) 232 | 233 | 234 | # input -> (#timesteps, batch_size, #events, token_dim/event_xy) 235 | def forward(self, kv, pixels): 236 | 237 | pixels = pixels // self.downsample_pos_enc 238 | 239 | batch_size = kv.shape[1] 240 | num_time_steps = kv.shape[0] 241 | # True to ignore empty patches | (#timesteps, batch_size, #events) 242 | samples_mask = kv.sum(-1) == 0 # to ignore in the attention block 243 | samples_mask_time = kv.sum(-1).sum(-1) == 0 # to ignore when there is no events at some time-step -> in a short clip when it is left-padded 244 | 245 | # Linear projection 246 | kv = self.event_projection(kv) # (num_timesteps, batch_size, num_events, token_dim) 247 | 248 | # Add pos. encodings 249 | if self.pos_encoding is not None: 250 | pos_embs = self.pos_encoding[pixels[:,:,:,1], pixels[:,:,:,0],:] 251 | kv = torch.cat([kv, pos_embs], dim=-1) 252 | else: pos_embs = None 253 | kv = kv.permute(0,2,1,3) # (num_timesteps, num_events, batch_size, token_dim) 254 | 255 | # To embedding size 256 | kv = self.preproc_block_events(kv) # (num_timesteps, batch_size, token_dim, num_events) 257 | 258 | # Initial latent vectors 259 | latent_vectors = self.memory_vertical.unsqueeze(1) 260 | latent_vectors = latent_vectors.expand(-1, batch_size, -1) # (num_latent_vectors, batch_size, embed_dim) 261 | 262 | # Initialize inp_q 263 | inp_q = latent_vectors 264 | 265 | for t in range(num_time_steps): 266 | inp_kv = kv[t] # (num_events, batch_size, token_dim) 267 | mask_t = samples_mask[t] 268 | mask_time_t = samples_mask_time[t] 269 | pos_embs_t = pos_embs[t].reshape(pos_embs.shape[2], pos_embs.shape[1], pos_embs.shape[3]) if pos_embs is not None else None 270 | 271 | # Process events 272 | proc_event_block = self.proc_event_blocks[0] 273 | inp_kv = proc_event_block(x_input=inp_kv, z=inp_kv, mask=mask_t, pos_embs=pos_embs_t) 274 | 275 | # Process memory 276 | proc_memory_block = self.proc_memory_blocks[0] 277 | inp_q = proc_memory_block(inp_kv, inp_q, mask=mask_t) 278 | inp_q[:, mask_time_t] = latent_vectors[:, mask_time_t] 279 | 280 | # Update latent_vectors 281 | latent_vectors = inp_q + latent_vectors 282 | 283 | embs = inp_q if self.return_last_q else latent_vectors 284 | res = self.proc_embs_block(embs) 285 | 286 | return res 287 | 288 | 289 | # Classification backbone 290 | class CLFBlock(nn.Module): 291 | def __init__(self, ipt_dim, opt_classes, **args): 292 | super(CLFBlock, self).__init__() 293 | self.linear_1 = nn.Linear(ipt_dim, ipt_dim) 294 | self.linear_2 = nn.Linear(ipt_dim, opt_classes) 295 | 296 | # z -> (batch_size, emb dim) 297 | def forward(self, z): 298 | z = F.relu(self.linear_1(z)) 299 | z = self.linear_2(z) 300 | clf = F.log_softmax(z, dim=1) 301 | return clf 302 | 303 | 304 | 305 | 306 | -------------------------------------------------------------------------------- /models/positional_encoding.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import math 3 | from torch import nn 4 | 5 | 6 | # https://github.com/louislva/deepmind-perceiver/blob/eb668c818eceab957713091ad1e244b14f039f7e/perceiver/positional_encoding.py#L6 7 | # Example parameters: shape=(28, 28), bands=8 8 | # encoding_size = bands*2*2 9 | def fourier_features(shape, bands): 10 | # This first "shape" refers to the shape of the input data, not the output of this function 11 | dims = len(shape) 12 | 13 | # Every tensor we make has shape: (bands, dimension, x, y, etc...) 14 | 15 | # Pos is computed for the second tensor dimension 16 | # (aptly named "dimension"), with respect to all 17 | # following tensor-dimensions ("x", "y", "z", etc.) 18 | pos = torch.stack(list(torch.meshgrid( 19 | *(torch.linspace(-1.0, 1.0, steps=n) for n in list(shape)) 20 | ))) 21 | pos = pos.unsqueeze(0).expand((bands,) + pos.shape) 22 | 23 | # Band frequencies are computed for the first 24 | # tensor-dimension (aptly named "bands") with 25 | # respect to the index in that dimension 26 | band_frequencies = (torch.logspace( 27 | math.log(1.0), 28 | math.log(shape[0]/2), 29 | steps=bands, 30 | base=math.e 31 | )).view((bands,) + tuple(1 for _ in pos.shape[1:])).expand(pos.shape) 32 | 33 | # For every single value in the tensor, let's compute: 34 | # freq[band] * pi * pos[d] 35 | 36 | # We can easily do that because every tensor is the 37 | # same shape, and repeated in the dimensions where 38 | # it's not relevant (e.g. "bands" dimension for the "pos" tensor) 39 | result = (band_frequencies * math.pi * pos).view((dims * bands,) + shape) 40 | 41 | # Use both sin & cos for each band, and then add raw position as well 42 | # TODO: raw position 43 | result = torch.cat([ 44 | torch.sin(result), 45 | torch.cos(result), 46 | ], dim=0) 47 | 48 | return result 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aermanager==0.3.0 2 | numpy==1.20.3 3 | pandas==1.2.5 4 | scikit-image==0.18.2 5 | scikit-learn==0.24.2 6 | scipy==1.6.2 7 | sparse==0.12.0 8 | torch==1.9.0 9 | pytorch-lightning==1.3.8 10 | ptflops==0.6.6 -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | from trainer import train 2 | import json 3 | 4 | 5 | path_results = 'pretrained_models' 6 | 7 | # Load params with the parameters reported in the article for each dataset 8 | train_params = json.load(open('./pretrained_models/DVS128_10_24ms/all_params.json', 'r')) 9 | # train_params = json.load(open('./pretrained_models/DVS128_11_24ms/all_params.json', 'r')) 10 | # train_params = json.load(open('./pretrained_models/SLAnimals_3s_48ms/all_params.json', 'r')) 11 | # train_params = json.load(open('./pretrained_models/SLAnimals_4s_48ms/all_params.json', 'r')) 12 | 13 | train_params['logger_params']['csv']['save_dir'] = '{}' 14 | for k,v in train_params['callbacks_params']: 15 | if k != 'model_chck': continue 16 | v['dirpath'] = '{}/weights/' 17 | v['filename'] = '{epoch}-{val_loss_total:.5f}-{val_loss_clf:.5f}-{val_acc:.5f}' 18 | 19 | 20 | # train_params['data_params']['batch_size'] = 4 21 | 22 | path_model = train('/tests', path_results, 23 | data_params = train_params['data_params'], 24 | backbone_params = train_params['backbone_params'], 25 | clf_params = train_params['clf_params'], 26 | training_params = train_params['training_params'], 27 | optim_params = train_params['optim_params'], 28 | callback_params = train_params['callbacks_params'], 29 | logger_params = train_params['logger_params']) 30 | 31 | -------------------------------------------------------------------------------- /trainer.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from torch import nn 4 | import torch.nn.functional as F 5 | import torch 6 | 7 | import pytorch_lightning as pl 8 | 9 | from pytorch_lightning import Trainer, LightningModule 10 | from torch.optim import lr_scheduler 11 | 12 | from data_generation import Event_DataModule 13 | import evaluation_utils 14 | 15 | from pytorch_lightning.callbacks import EarlyStopping, LearningRateMonitor, ModelCheckpoint 16 | from pytorch_lightning.loggers import CSVLogger 17 | import training_utils 18 | import json 19 | import pandas as pd 20 | import numpy as np 21 | import copy 22 | from torch.optim import AdamW 23 | 24 | from models.EvT import CLFBlock, MLPBlock 25 | from models.EvT import EvNetBackbone 26 | 27 | 28 | 29 | class EvNetModel(LightningModule): 30 | 31 | def __init__(self, backbone_params, clf_params, optim_params, loss_weights=None): 32 | super().__init__() 33 | self.save_hyperparameters() 34 | 35 | self.backbone_params = backbone_params 36 | self.clf_params = clf_params 37 | self.optim_params = optim_params 38 | 39 | # Initialize Backbone 40 | self.backbone = EvNetBackbone(**backbone_params) 41 | # Initialize classifier 42 | self.clf_params['ipt_dim'] = self.backbone_params['embed_dim'] 43 | # TODO: move to single variable 44 | self.models_clf = nn.ModuleDict([ [str(0),CLFBlock(**self.clf_params)] ]) 45 | # self.models_clf = CLFBlock(**self.clf_params) 46 | 47 | self.loss_weights = loss_weights 48 | self.init_optimizers() 49 | 50 | 51 | def init_optimizers(self): 52 | self.criterion = nn.NLLLoss(weight = self.loss_weights) 53 | self.accuracy = pl.metrics.Accuracy() 54 | 55 | 56 | def forward(self, x, pixels): 57 | # Get updated latent vectors 58 | embs = self.backbone(x, pixels) 59 | # Get latent vectors classification 60 | clf_logits = torch.stack([ self.models_clf[str(0)](embs) ]).mean(axis=0) 61 | return embs, clf_logits 62 | 63 | 64 | def configure_optimizers(self): 65 | 66 | # Import base optimizer 67 | base_optim = AdamW 68 | optim = base_optim(self.parameters(), **self.optim_params['optim_params']) 69 | 70 | if 'scheduler' in self.optim_params: 71 | if self.optim_params['scheduler']['name'] == 'lr_on_plateau': 72 | sched = lr_scheduler.ReduceLROnPlateau(optim, **self.optim_params['scheduler']['params']) 73 | elif self.optim_params['scheduler']['name'] == 'one_cycle_lr': 74 | sched = lr_scheduler.OneCycleLR(optim, max_lr=self.optim_params['optim_params']['lr'], **self.optim_params['scheduler']['params']) 75 | return {'optimizer': optim, 'lr_scheduler': sched, 'monitor': self.optim_params['monitor']} 76 | return optim 77 | 78 | 79 | # Forward data and calculate loss and acc 80 | def step(self, polarity, pixels, y): 81 | embs, clf_logits = self(polarity, pixels) 82 | 83 | loss_clf, loss_contr = 0.0, 0.0 84 | logs = {} 85 | 86 | loss_clf = self.criterion(clf_logits, y) 87 | preds = torch.argmax(clf_logits, dim=-1) 88 | 89 | acc = self.accuracy(preds, y) 90 | 91 | logs['loss_clf'] = loss_clf 92 | logs['acc'] = acc 93 | 94 | 95 | logs['loss_total'] = loss_clf + loss_contr 96 | 97 | return logs 98 | 99 | 100 | def training_step(self, batch, batch_idx): 101 | # batch_data -> (#imesteps, batch_size, #events, 2) - (#imesteps, batch_size, #events, 2) - (batch_size) 102 | polarity, pixels, y = batch 103 | losses = self.step(polarity, pixels, y) 104 | for k,v in losses.items(): 105 | self.log(f'train_{k}', v, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True) 106 | 107 | return losses['loss_total'] 108 | 109 | 110 | def validation_step(self, batch, batch_idx): 111 | polarity, pixels, y = batch 112 | losses = self.step(polarity, pixels, y) 113 | for k,v in losses.items(): 114 | self.log(f'val_{k}', v, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True) 115 | 116 | 117 | return losses['loss_total'] 118 | 119 | 120 | 121 | 122 | def train(folder_name, path_results, data_params, backbone_params, clf_params, 123 | training_params, optim_params, callback_params, logger_params): 124 | 125 | # Create the folder where to store the training results 126 | path_model = training_utils.create_model_folder(path_results, folder_name) 127 | 128 | callbacks = [] 129 | for k, params in callback_params: 130 | if k == 'early_stopping': callbacks.append(EarlyStopping(**params)) 131 | if k == 'lr_monitor': callbacks.append(LearningRateMonitor(**params)) 132 | if k == 'model_chck': 133 | params['dirpath'] = params['dirpath'].format(path_model) 134 | callbacks.append(ModelCheckpoint(**params)) 135 | 136 | loggers = [] 137 | if 'csv' in logger_params: 138 | logger_params['csv']['save_dir'] = logger_params['csv']['save_dir'].format(path_model) 139 | loggers.append(CSVLogger(**logger_params['csv'])) 140 | 141 | 142 | # ============================================================================= 143 | # Train 144 | # ============================================================================= 145 | dm = Event_DataModule(**data_params) 146 | backbone_params['token_dim'] = dm.token_dim 147 | clf_params['opt_classes'] = dm.num_classes 148 | 149 | if 'pos_encoding' in backbone_params and backbone_params['pos_encoding']['params'].get('shape', -1) == -1: 150 | backbone_params['pos_encoding']['params']['shape'] = (dm.width, dm.height) 151 | if backbone_params['downsample_pos_enc'] == -1: backbone_params['downsample_pos_enc'] = data_params['patch_size'] 152 | 153 | if optim_params['scheduler']['name'] == 'one_cycle_lr': 154 | optim_params['scheduler']['params']['steps_per_epoch'] = 1 155 | 156 | model = EvNetModel(backbone_params=copy.deepcopy(backbone_params), 157 | clf_params=copy.deepcopy(clf_params), 158 | optim_params=copy.deepcopy(optim_params), 159 | loss_weights = None if not data_params['balance'] else dm.train_dataloader().dataset.get_class_weights() 160 | ) 161 | 162 | trainer = Trainer(**training_params, callbacks=callbacks, logger=loggers) 163 | 164 | # Save all params 165 | json.dump({'data_params': data_params, 'backbone_params': backbone_params, 'clf_params': clf_params, 166 | 'training_params': training_params, 167 | 'optim_params': optim_params, 'callbacks_params': callback_params, 'logger_params': logger_params}, 168 | open(path_model+'all_params.json', 'w')) 169 | 170 | 171 | trainer.fit(model, dm) 172 | 173 | print(' ** Train finished:', path_model) 174 | 175 | logs = evaluation_utils.load_csv_logs_as_df(path_model) 176 | val_acc = logs[~logs['val_acc'].isna()]['val_acc'] 177 | print(' - Max. Accuracy: {:.4f}'.format(val_acc.values.max())) 178 | 179 | for c in [ c for c in logs.columns if 'val_' in c and 'acc' not in c ]: 180 | v = logs[~logs[c].isna()][c] 181 | v = v.values.min() if len(v) > 0 else 0.0 182 | print(' - Min. [{}]: {:.4f}'.format(c, v)) 183 | print("path_model = '{}'".format(path_model)) 184 | 185 | return path_model 186 | 187 | 188 | -------------------------------------------------------------------------------- /training_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import datetime 3 | 4 | 5 | def create_folder_if_not_exists(folder_path): 6 | if not os.path.isdir(folder_path): os.makedirs(folder_path) 7 | 8 | def get_model_name(model_dir): 9 | folder_num = len(os.listdir(model_dir)) 10 | return '/{}_model_{}/'.format(datetime.datetime.today().strftime('%m%d_%H%M'), folder_num) 11 | 12 | def create_model_folder(path_results, folder_name): 13 | 14 | path_model = path_results + folder_name 15 | 16 | # Create logs and model main folder 17 | create_folder_if_not_exists(path_model) 18 | 19 | model_name = get_model_name(path_results + folder_name) 20 | path_model += model_name 21 | create_folder_if_not_exists(path_model) 22 | create_folder_if_not_exists(path_model + 'weights/') 23 | 24 | return path_model 25 | 26 | 27 | def update_params(original_params, new_params): 28 | for k,v in new_params.items(): 29 | # print(k,v) 30 | if type(v) == dict and k in original_params: v = update_params(original_params[k], new_params[k]) 31 | original_params[k] = v 32 | return original_params 33 | 34 | 35 | 36 | --------------------------------------------------------------------------------