├── models ├── __init__.py ├── get_topclass.py ├── get_mnist.py ├── get_cifar10.py ├── get_3d.py └── Models.py ├── mpi_learn ├── __init__.py ├── mpi │ ├── __init__.py │ ├── single_process.py │ └── manager.py ├── train │ ├── __init__.py │ ├── monitor.py │ ├── trace.py │ ├── algo.py │ ├── data.py │ ├── model.py │ └── optimizer.py ├── utils.py └── logger.py ├── .gitignore ├── docs └── downpour.png ├── my_model.py ├── Dockerfile ├── example_mnist.py ├── generatorTest.py ├── BuildModel.py ├── smpfrac.py ├── PytorchCNN.py ├── TorchModels.py ├── mpiLAPI.py ├── simple_train.py ├── README.md ├── MPIGDriver.py ├── MPIDriver.py └── License.md /models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /mpi_learn/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /mpi_learn/mpi/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /mpi_learn/train/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | *.json 4 | *.h5 5 | *.txt 6 | .DS_Store -------------------------------------------------------------------------------- /docs/downpour.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vlimant/mpi_learn/HEAD/docs/downpour.png -------------------------------------------------------------------------------- /my_model.py: -------------------------------------------------------------------------------- 1 | # Define your model here 2 | 3 | def get_model(): 4 | """Should return the model object (keras.models.Model or torch.nn.Module).""" 5 | raise NotImplementedError 6 | 7 | def get_name(): 8 | """String containing model name (optional).""" 9 | raise NotImplementedError 10 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM uber/horovod:0.14.0-tf1.10.0-torch0.4.0-py3.5 2 | 3 | RUN apt-get -y update 4 | 5 | RUN pip3 install mpi4py psutil gpustat scikit-optimize h5py==2.7.0 && \ 6 | ln -s /usr/bin/python3.5 /usr/bin/python3 7 | 8 | RUN apt-get -y install s3cmd 9 | 10 | RUN git clone "https://github.com/svalleco/mpi_learn.git" "/mpi_learn" 11 | 12 | WORKDIR "/mpi_learn" 13 | -------------------------------------------------------------------------------- /models/get_topclass.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | import sys 4 | 5 | dest='/bigdata/shared/LCDJets_Abstract_IsoLep_lt_20' 6 | import socket 7 | host = os.environ.get('HOST', os.environ.get('HOSTNAME',socket.gethostname())) 8 | if 'titan' in host: 9 | dest='/ccs/proj/csc291/DATA/LCDJets_Abstract_IsoLep_lt_20' 10 | train = glob.glob(dest+'/train/*.h5') 11 | test = glob.glob(dest+'/val/*.h5') 12 | 13 | N=10 14 | Nt=N/5 15 | if len(sys.argv)>=1: 16 | a = sys.argv[1] 17 | if a.isdigit(): 18 | N = int(a) 19 | Nt=N/5 20 | else: 21 | N,Nt = map(int, a.split(',')) 22 | 23 | 24 | open('train_topclass.list','w').write( '\n'.join(sorted( train[:N] ))) 25 | open('test_topclass.list','w').write( '\n'.join(sorted( test[:Nt] ))) 26 | -------------------------------------------------------------------------------- /example_mnist.py: -------------------------------------------------------------------------------- 1 | 2 | from models.Models import make_mnist_model 3 | 4 | get_model = make_mnist_model 5 | def get_name(): 6 | return 'mnist' 7 | 8 | def get_all(): 9 | import socket,os,glob 10 | host = os.environ.get('HOST',os.environ.get('HOSTNAME',socket.gethostname())) 11 | 12 | if 'daint' in host: 13 | all_list = glob.glob('/scratch/snx3000/vlimant/data/mnist/*.h5') 14 | elif 'titan' in host: 15 | all_list = glob.glob('/ccs/proj/csc291/DATA/mnist/*.h5') 16 | else: 17 | all_list = glob.glob('/bigdata/shared/mnist/*.h5') 18 | return all_list 19 | 20 | def get_train(): 21 | all_list = get_all() 22 | l = int( len(all_list)*0.70) 23 | train_list = all_list[:l] 24 | return train_list 25 | 26 | def get_val(): 27 | all_list = get_all() 28 | l = int( len(all_list)*0.70) 29 | val_list = all_list[l:] 30 | return val_list 31 | 32 | def get_features(): 33 | return 'features' 34 | 35 | def get_labels(): 36 | return 'labels' 37 | 38 | -------------------------------------------------------------------------------- /generatorTest.py: -------------------------------------------------------------------------------- 1 | import os, h5py 2 | import numpy as np 3 | import matplotlib 4 | import matplotlib.pyplot as plt 5 | import matplotlib.cm as cm 6 | from matplotlib.colors import LogNorm, Normalize 7 | plt.switch_backend('Agg') 8 | 9 | from EcalEnergyGan import generator as build_generator 10 | 11 | 12 | #gen_weights='/nfshome/svalleco/mpigan/m0_bs_train_mpi_learn_result.h5' 13 | gen_weights='weights/params_generator_epoch_029.hdf5' 14 | latent_space=200 15 | n_events=100 16 | batch_size=100 17 | np.random.seed() 18 | g = build_generator(latent_space, return_intermediate=False) 19 | g.load_weights(gen_weights) 20 | 21 | noise = np.random.normal(0, 1, (n_events, latent_space)) 22 | sampled_energies = np.random.uniform(0.1, 5,( batch_size,1 )) 23 | generator_in = np.multiply(sampled_energies, noise) 24 | generated_images = g.predict(generator_in) 25 | 26 | generated_images = generated_images.squeeze() 27 | print(generated_images.shape) 28 | 29 | fig = plt.figure(1) 30 | plt.imshow(generated_images[10, 12, :, :]) 31 | fig.show() 32 | fig.savefig('event1_yz_goodEx.png') 33 | fig1 = plt.figure(2) 34 | plt.imshow(generated_images[10, :, :, 12]) 35 | fig1.show() 36 | fig1.savefig('event1_xy_goodEx.png') 37 | -------------------------------------------------------------------------------- /BuildModel.py: -------------------------------------------------------------------------------- 1 | ### Builds one of the available models. 2 | # Saves model architecture to _arch.json 3 | # and model weights to _weights.h5 4 | 5 | import os 6 | os.environ['CUDA_VISIBLE_DEVICES']="" 7 | import argparse 8 | 9 | from models.Models import make_model 10 | 11 | if __name__ == '__main__': 12 | parser = argparse.ArgumentParser() 13 | parser.add_argument('model_name', help='model to construct') 14 | parser.add_argument('model_args', nargs='*', help='key=value to pass to the model',default=[]) 15 | args = parser.parse_args() 16 | model_name = args.model_name 17 | model_args = {} 18 | for kw in args.model_args: 19 | k,v = kw.split('=') 20 | try: 21 | v = int(v) 22 | except: 23 | v= float(v) 24 | model_args[k] = v 25 | if model_args: 26 | print ("passing",model_args,"to the model builder") 27 | model = make_model( model_name ,**model_args) 28 | else: 29 | model = make_model( model_name) 30 | weights_filename = "%s_weights.h5" % model_name 31 | arch_filename = "%s_arch.json" % model_name 32 | 33 | if not "torch" in model_name: 34 | model.summary() 35 | model.save_weights( weights_filename, overwrite=True ) 36 | print ("Saved model weights to {0}".format(weights_filename)) 37 | 38 | model_arch = model.to_json() 39 | with open( arch_filename, 'w' ) as arch_file: 40 | arch_file.write( model_arch ) 41 | print ("Saved model architecture to {0}".format(arch_filename)) 42 | else: 43 | import torch 44 | weights_filename = weights_filename.replace('h5','torch') 45 | arch_filename = arch_filename.replace('json','torch') 46 | torch.save(model.state_dict(), weights_filename) 47 | print ("Saved model weights to {0}".format(weights_filename)) 48 | torch.save(model, arch_filename) 49 | print ("Saved model architecture to {0}".format(arch_filename)) 50 | 51 | -------------------------------------------------------------------------------- /models/get_mnist.py: -------------------------------------------------------------------------------- 1 | ### This script downloads the MNIST dataset, unpacks it, splits it into four pieces, and saves 2 | # each piece in a separate h5 file. 3 | 4 | from numpy import array_split 5 | from keras.datasets import mnist 6 | from keras.utils import np_utils 7 | from keras import backend as K 8 | import h5py 9 | import sys 10 | 11 | (X_train, Y_train), (X_test, Y_test) = mnist.load_data() 12 | 13 | img_rows = 28 14 | img_cols = 28 15 | if K.image_dim_ordering() == 'th': 16 | X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols) 17 | X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols) 18 | input_shape = (1, img_rows, img_cols) 19 | else: 20 | X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) 21 | X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) 22 | input_shape = (img_rows, img_cols, 1) 23 | 24 | num_train_pieces = int(sys.argv[1]) if len(sys.argv)>1 else 24 25 | num_test_pieces = int(sys.argv[2]) if len(sys.argv)>1 else 4 26 | split_X_train = [ X.astype('float32') / 255 for X in array_split(X_train, num_train_pieces) ] 27 | split_Y_train = [ np_utils.to_categorical(Y,10) for Y in array_split(Y_train, num_train_pieces) ] 28 | split_X_test = [ X.astype('float32') / 255 for X in array_split(X_test, num_test_pieces) ] 29 | split_Y_test = [ np_utils.to_categorical(Y,10) for Y in array_split(Y_test, num_test_pieces) ] 30 | 31 | train_list = [] 32 | for i in range(num_train_pieces): 33 | train_name = "mnist_train_%d.h5" % i 34 | train_list.append(train_name+"\n") 35 | train_outfile = h5py.File( train_name, 'w' ) 36 | train_outfile.create_dataset( "features", data=split_X_train[i] ) 37 | train_outfile.create_dataset( "labels", data=split_Y_train[i] ) 38 | train_outfile.close() 39 | with open('train_mnist.list', 'w') as train_list_file: 40 | for f in train_list: 41 | train_list_file.write(f) 42 | 43 | test_list = [] 44 | for i in range(num_test_pieces): 45 | test_name = "mnist_test_%d.h5" % i 46 | test_list.append(test_name+"\n") 47 | test_outfile = h5py.File( test_name, 'w' ) 48 | test_outfile.create_dataset( "features", data=split_X_test[i] ) 49 | test_outfile.create_dataset( "labels", data=split_Y_test[i] ) 50 | test_outfile.close() 51 | with open('test_mnist.list', 'w') as test_list_file: 52 | for f in test_list: 53 | test_list_file.write(f) 54 | -------------------------------------------------------------------------------- /models/get_cifar10.py: -------------------------------------------------------------------------------- 1 | ### This script downloads the cifar10 dataset, unpacks it, splits it into four pieces, and saves 2 | # each piece in a separate h5 file. 3 | 4 | from numpy import array_split 5 | from keras.datasets import cifar10 6 | from keras.utils import np_utils 7 | from keras import backend as K 8 | import h5py 9 | import sys 10 | 11 | (X_train, Y_train), (X_test, Y_test) = cifar10.load_data() 12 | 13 | img_rows = 32 14 | img_cols = 32 15 | if K.image_dim_ordering() == 'th': 16 | X_train = X_train.reshape(X_train.shape[0], 3, img_rows, img_cols) 17 | X_test = X_test.reshape(X_test.shape[0], 3, img_rows, img_cols) 18 | input_shape = (3, img_rows, img_cols) 19 | else: 20 | X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 3) 21 | X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 3) 22 | input_shape = (img_rows, img_cols, 3) 23 | 24 | num_train_pieces = int(sys.argv[1]) if len(sys.argv)>1 else 24 25 | num_test_pieces = int(sys.argv[2]) if len(sys.argv)>1 else 4 26 | split_X_train = [ X.astype('float32') / 255 for X in array_split(X_train, num_train_pieces) ] 27 | split_Y_train = [ np_utils.to_categorical(Y,10) for Y in array_split(Y_train, num_train_pieces) ] 28 | split_X_test = [ X.astype('float32') / 255 for X in array_split(X_test, num_test_pieces) ] 29 | split_Y_test = [ np_utils.to_categorical(Y,10) for Y in array_split(Y_test, num_test_pieces) ] 30 | 31 | train_list = [] 32 | for i in range(num_train_pieces): 33 | train_name = "cifar10_train_%d.h5" % i 34 | train_list.append(train_name+"\n") 35 | train_outfile = h5py.File( train_name, 'w' ) 36 | train_outfile.create_dataset( "features", data=split_X_train[i] ) 37 | train_outfile.create_dataset( "labels", data=split_Y_train[i] ) 38 | train_outfile.close() 39 | with open('train_cifar10.list', 'w') as train_list_file: 40 | for f in train_list: 41 | train_list_file.write(f) 42 | 43 | test_list = [] 44 | for i in range(num_test_pieces): 45 | test_name = "cifar10_test_%d.h5" % i 46 | test_list.append(test_name+"\n") 47 | test_outfile = h5py.File( test_name, 'w' ) 48 | test_outfile.create_dataset( "features", data=split_X_test[i] ) 49 | test_outfile.create_dataset( "labels", data=split_Y_test[i] ) 50 | test_outfile.close() 51 | with open('test_cifar10.list', 'w') as test_list_file: 52 | for f in test_list: 53 | test_list_file.write(f) 54 | -------------------------------------------------------------------------------- /mpi_learn/utils.py: -------------------------------------------------------------------------------- 1 | ### Utilities for mpi_learn module 2 | import os 3 | import sys 4 | import numpy as np 5 | import logging 6 | 7 | class Error(Exception): 8 | pass 9 | 10 | def weights_from_shapes(weights_shapes): 11 | """Returns a list of numpy arrays representing the NN architecture""" 12 | return [ np.zeros( shape, dtype=np.float32 ) for shape in weights_shapes ] 13 | 14 | def shapes_from_weights(weights): 15 | """Returns a list of tuples indicating the array shape of each layer of the NN""" 16 | return [ w.shape for w in weights ] 17 | 18 | def get_num_gpus(): 19 | """Returns the number of GPUs available""" 20 | logging.debug("Determining number of GPUs...") 21 | from pycuda import driver 22 | driver.init() 23 | num_gpus = driver.Device.count() 24 | logging.debug("Number of GPUs: {}".format(num_gpus)) 25 | return num_gpus 26 | 27 | def get_device_name(dev_type, dev_num, backend='theano'): 28 | """Returns cpu/gpu device name formatted for 29 | theano or keras, as specified by the backend argument""" 30 | if backend == 'tensorflow': 31 | return "/%s:%d" % (dev_type, dev_num) 32 | else: 33 | if dev_type == 'cpu': 34 | return 'cpu' 35 | else: 36 | return dev_type+str(dev_num) 37 | 38 | def import_keras(tries=10): 39 | """There is an issue when multiple processes import Keras simultaneously -- 40 | the file .keras/keras.json is sometimes not read correctly. 41 | as a workaround, just try several times to import keras.""" 42 | for try_num in range(tries): 43 | try: 44 | stderr = sys.stderr 45 | sys.stderr = open(os.devnull, 'w') 46 | import keras 47 | sys.stderr = stderr 48 | return 49 | except ValueError: 50 | logging.warning("Unable to import keras. Trying again: {0:d}".format(try_num)) 51 | from time import sleep 52 | sleep(0.1) 53 | logging.error("Failed to import keras!") 54 | 55 | def load_model(filename=None, model=None, weights_file=None, custom_objects={}): 56 | """Loads model architecture from JSON and instantiates the model. 57 | filename: path to JSON file specifying model architecture 58 | model: (or) a Keras model to be cloned 59 | weights_file: path to HDF5 file containing model weights 60 | custom_objects: A Dictionary of custom classes used in the model keyed by name""" 61 | import_keras() 62 | from keras.models import model_from_json, clone_model 63 | if filename is not None: 64 | with open( filename ) as arch_f: 65 | json_str = arch_f.readline() 66 | new_model = model_from_json( json_str, custom_objects=custom_objects) 67 | if model is not None: 68 | new_model = clone_model(model) 69 | if weights_file is not None: 70 | new_model.load_weights( weights_file ) 71 | return new_model 72 | 73 | -------------------------------------------------------------------------------- /mpi_learn/mpi/single_process.py: -------------------------------------------------------------------------------- 1 | import os,sys,json 2 | import numpy as np 3 | import socket 4 | import time 5 | import logging 6 | 7 | from ..train.monitor import Monitor 8 | from ..utils import Error, weights_from_shapes, shapes_from_weights 9 | from .process import MPIWorker, MPIMaster 10 | 11 | class MPISingleWorker(MPIWorker): 12 | """This class trains its model with no communication to other processes""" 13 | def __init__(self, num_epochs, data, algo, model_builder, 14 | verbose, monitor, custom_objects, 15 | early_stopping, target_metric, 16 | checkpoint, checkpoint_interval): 17 | 18 | self.has_parent = False 19 | 20 | self.best_val_loss = None 21 | self.target_metric = (target_metric if type(target_metric)==tuple else tuple(map(lambda s : float(s) if s.replace('.','').isdigit() else s, target_metric.split(',')))) if target_metric else None 22 | self.patience = (early_stopping if type(early_stopping)==tuple else tuple(map(lambda s : float(s) if s.replace('.','').isdigit() else s, early_stopping.split(',')))) if early_stopping else None 23 | 24 | super(MPISingleWorker, self).__init__(data, algo, model_builder, process_comm=None, parent_comm=None, parent_rank=None, 25 | num_epochs=num_epochs, verbose=verbose, monitor=monitor, custom_objects=custom_objects, 26 | checkpoint=checkpoint, checkpoint_interval=checkpoint_interval) 27 | 28 | def train(self): 29 | self.check_sanity() 30 | 31 | for epoch in range(1, self.num_epochs + 1): 32 | logging.info("beginning epoch {:d}".format(self.epoch + epoch)) 33 | if self.monitor: 34 | self.monitor.start_monitor() 35 | epoch_metrics = np.zeros((1,)) 36 | i_batch = 0 37 | 38 | for i_batch, batch in enumerate(self.data.generate_data()): 39 | train_metrics = self.model.train_on_batch( x=batch[0], y=batch[1] ) 40 | if epoch_metrics.shape != train_metrics.shape: 41 | epoch_metrics = np.zeros( train_metrics.shape) 42 | epoch_metrics += train_metrics 43 | 44 | ###### 45 | self.update = self.algo.compute_update( self.weights, self.model.get_weights() ) 46 | self.weights = self.algo.apply_update( self.weights, self.update ) 47 | self.algo.set_worker_model_weights( self.model, self.weights ) 48 | ###### 49 | 50 | if self._short_batches and i_batch>self._short_batches: break 51 | 52 | if self.monitor: 53 | self.monitor.stop_monitor() 54 | epoch_metrics = epoch_metrics / float(i_batch+1) 55 | l = self.model.get_logs( epoch_metrics ) 56 | self.update_history( l ) 57 | 58 | if self.stop_training: 59 | break 60 | 61 | self.validate() 62 | self.save_checkpoint() 63 | 64 | logging.info("Signing off") 65 | if self.monitor: 66 | self.update_monitor( self.monitor.get_stats() ) 67 | 68 | self.data.finalize() 69 | 70 | def validate(self): 71 | return MPIMaster.validate_aux(self, self.weights, self.model) 72 | 73 | -------------------------------------------------------------------------------- /models/get_3d.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | try: 4 | import h5py 5 | pass 6 | except: 7 | print ("hum") 8 | import numpy as np 9 | import sys 10 | 11 | def get_data(datafile): 12 | #get data for training 13 | #print ('Loading Data from .....', datafile) 14 | f=h5py.File(datafile,'r') 15 | y=f.get('target') 16 | X=np.array(f.get('ECAL')) 17 | y=(np.array(y[:,1])) 18 | X[X < 1e-4] = 0 19 | X = np.expand_dims(X, axis=-1) 20 | X = X.astype(np.float32) 21 | y = y.astype(np.float32) 22 | y = y/100. 23 | ecal = np.squeeze(np.sum(X, axis=(1, 2, 3))) 24 | print (X.shape) 25 | print (y.shape) 26 | print (ecal.shape) 27 | 28 | f.close() 29 | return X, y, ecal 30 | 31 | dest='/data/shared/3DGAN/' 32 | import socket 33 | host = os.environ.get('HOST', os.environ.get('HOSTNAME',socket.gethostname())) 34 | if 'daint' in host: 35 | dest='/scratch/snx3000/vlimant/3DGAN/' 36 | if 'titan' in host: 37 | dest='/ccs/proj/csc291/DATA/3DGAN/' 38 | 39 | sub_split = int(sys.argv[1]) if len(sys.argv)>1 else 1 40 | 41 | for F in glob.glob('/bigdata/shared/LCD/NewV1/*scan/*.h5'): 42 | _,d,f = F.rsplit('/',2) 43 | if not 'Ele' in d: continue 44 | X = None 45 | if sub_split==1: 46 | nf = '%s/%s_%s.h5'%( dest,d,f) 47 | if os.path.isfile( nf) : 48 | continue 49 | print ("processing files",F,"into",nf) 50 | if X is None: 51 | X,y,ecal = get_data(F) 52 | o = h5py.File(nf,'w') 53 | o['X'] = X 54 | o.create_group("y") 55 | o['y']['a'] = np.ones(y.shape) 56 | o['y']['b'] = y 57 | o['y']['c'] = ecal 58 | o.close() 59 | else: 60 | for sub in range(sub_split): 61 | nf = '%s/%s_%s_sub%s.h5'%(dest, d,f,sub) 62 | if os.path.isfile( nf) : 63 | continue 64 | print ("processing files",F,"into",nf) 65 | if X is None: 66 | X,y,ecal = get_data(F) 67 | N = X.shape[0] 68 | splits = [i*N/sub_split for i in range(sub_split)]+[-1] 69 | o = h5py.File(nf,'w') 70 | o['X'] = X[splits[sub]:splits[sub+1],...] 71 | o.create_group("y") 72 | o['y']['a'] = np.ones(y[splits[sub]:splits[sub+1],...].shape) 73 | o['y']['b'] = y[splits[sub]:splits[sub+1],...] 74 | o['y']['c'] = ecal[splits[sub]:splits[sub+1],...] 75 | o.close() 76 | X = None 77 | 78 | if sub_split == 1: 79 | sub_files = lambda f:not 'sub' in f 80 | else: 81 | sub_files = lambda f:'sub' in f 82 | 83 | open('train_3d.list','w').write( '\n'.join(filter(sub_files,glob.glob(dest+'/*.h5')[:-4]))) 84 | open('test_3d.list','w').write( '\n'.join(filter(sub_files,glob.glob(dest+'/*.h5')[-4:]))) 85 | 86 | open('train_small_3d.list','w').write( '\n'.join(filter(sub_files,glob.glob(dest+'/*.h5')[:-4]))) 87 | open('test_small_3d.list','w').write( '\n'.join(filter(sub_files,glob.glob(dest+'/*.h5')[-4:]))) 88 | 89 | open('train_7_3d.list','w').write( '\n'.join(filter(sub_files,glob.glob(dest+'/*.h5')[:7]))) 90 | open('test_1_3d.list','w').write( '\n'.join(filter(sub_files,glob.glob(dest+'/*.h5')[-1:]))) 91 | 92 | -------------------------------------------------------------------------------- /mpi_learn/train/monitor.py: -------------------------------------------------------------------------------- 1 | ### Monitor class 2 | 3 | import os 4 | import logging 5 | from threading import Thread 6 | import psutil 7 | try: 8 | import pynvml 9 | except: 10 | logging.warning("pynvml does not load, no monitoring available") 11 | import time 12 | 13 | class Monitor(object): 14 | """ Class that monitors GPU utilization for a given time """ 15 | 16 | def __init__(self, sampling_rate=None, pid=None): 17 | self.sampling_rate = sampling_rate if sampling_rate is not None else 0.5 18 | self.pid = pid if pid is not None else os.getpid() 19 | 20 | self.gpu = None 21 | self.should_stop = False 22 | self.thread = None 23 | self.accounting_enabled = False 24 | self.stats = [] 25 | 26 | def _find_gpu(self): 27 | device_count = pynvml.nvmlDeviceGetCount() 28 | for i in range(device_count): 29 | handle = pynvml.nvmlDeviceGetHandleByIndex(i) 30 | gpu_processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle) 31 | for gpu_process in gpu_processes: 32 | if gpu_process.pid == self.pid: 33 | self.gpu = handle 34 | 35 | self.accounting_enabled = pynvml.nvmlDeviceGetAccountingMode(self.gpu) == pynvml.NVML_FEATURE_ENABLED 36 | 37 | # Clear accounting statistics (requires root privileges) 38 | #pynvml.nvmlDeviceSetAccountingMode(self.gpu, pynvml.NVML_FEATURE_DISABLED) 39 | #pynvml.nvmlDeviceSetAccountingMode(self.gpu, pynvml.NVML_FEATURE_ENABLED) 40 | 41 | def _monitor(self): 42 | pynvml.nvmlInit() 43 | self._find_gpu() 44 | current_sample = [] 45 | while not self.should_stop: 46 | used_cpu = None 47 | used_cpumem = None 48 | used_gpu = None 49 | used_gpumem = None 50 | 51 | cpu_process = psutil.Process(self.pid) 52 | used_cpu = cpu_process.cpu_percent() / psutil.cpu_count() # CPU utilization in % 53 | used_cpumem = cpu_process.memory_info().rss // (1024*1024) # Memory use in MB 54 | 55 | gpu_processes = pynvml.nvmlDeviceGetComputeRunningProcesses(self.gpu) 56 | for gpu_process in gpu_processes: 57 | if gpu_process.pid == self.pid: 58 | used_gpumem = gpu_process.usedGpuMemory // (1024*1024) # GPU memory use in MB 59 | break 60 | 61 | if self.accounting_enabled: 62 | try: 63 | stats = pynvml.nvmlDeviceGetAccountingStats(self.gpu, self.pid) 64 | used_gpu = stats.gpuUtilization 65 | except pynvml.NVMLError: # NVMLError_NotFound 66 | pass 67 | 68 | if not used_gpu: 69 | util = pynvml.nvmlDeviceGetUtilizationRates(self.gpu) 70 | used_gpu = util.gpu / len(gpu_processes) # Approximate based on number of processes 71 | 72 | current_sample.append((used_cpu, used_cpumem, used_gpu, used_gpumem)) 73 | 74 | time.sleep(self.sampling_rate) 75 | 76 | self.stats.append([round(sum(x) / len(x)) for x in zip(*current_sample)]) 77 | pynvml.nvmlShutdown() 78 | 79 | def start_monitor(self): 80 | self.should_stop = False 81 | self.thread = Thread(target=self._monitor) 82 | self.thread.start() 83 | 84 | def stop_monitor(self): 85 | self.should_stop = True 86 | self.thread.join() 87 | 88 | def get_stats(self): 89 | return self.stats 90 | 91 | -------------------------------------------------------------------------------- /smpfrac.py: -------------------------------------------------------------------------------- 1 | from os import path 2 | from ROOT import TLegend, TCanvas, TGraph, gStyle, TProfile, TMultiGraph, TPaveStats 3 | #from ROOT import gROOT, gBenchmark 4 | import h5py 5 | import numpy as np 6 | import matplotlib 7 | import matplotlib.pyplot as plt 8 | import matplotlib.cm as cm 9 | from array import array 10 | import time 11 | 12 | 13 | from mpi_learn.train.GanModel import GANModel 14 | gan_args = { 15 | 'tell': False, 16 | 'reversedorder' : True, 17 | 'heavycheck' : False, 18 | 'show_values' : False, 19 | 'gen_bn' : True, 20 | 'checkpoint' : False, 21 | 'onepass' : True, 22 | 'show_loss' : True, 23 | 'with_fixed_disc' : True ## could switch back to False and check 24 | } 25 | 26 | gm = GANModel(**gan_args) 27 | #gStyle.SetOptStat(0) 28 | gStyle.SetOptFit (1111) # superimpose fit results 29 | c=TCanvas("c" ,"Ecal/Ep versus Ep for Data and Generated Events" ,200 ,10 ,700 ,500) #make nice 30 | c.SetGrid() 31 | gStyle.SetOptStat(0) 32 | #c.SetLogx () 33 | Eprof = TProfile("Eprof", "Ratio of Ecal and Ep;Ep;Ecal/Ep", 100, 0, 500) 34 | num_events=1000 35 | latent = 200 36 | #gweight = 'gen_rootfit_2p1p1_ep33.hdf5' 37 | gweight1='m1_twopass_easgd_bs5_ep20_train_mpi_learn_result.h5' 38 | gweight2='m1_twopass_easgd_bs10_ep20_train_mpi_learn_result.h5' 39 | gweight3='m1_twopass_easgd_bs15_ep20_train_mpi_learn_result.h5' 40 | gweight4='m1_twopass_easgd_bs20_ep20_train_mpi_learn_result.h5' 41 | gweights = [gweight1, gweight2, gweight3,gweight4] 42 | label = ['1 gpu', '5 gpus', '10 gpus', '15 gpus', '20 gpus'] 43 | scales = [1, 1, 1,1] 44 | filename = 'ecal_ratio_multi.pdf' 45 | #Get Actual Data 46 | #d=h5py.File("/eos/project/d/dshep/LCD/V1/EleEscan/EleEscan_1_1.h5") 47 | d=h5py.File("/afs/cern.ch/work/g/gkhattak/public/Ele_v1_1_2.h5",'r') 48 | X=np.array(d.get('ECAL')[0:num_events], np.float64) 49 | Y=np.array(d.get('target')[0:num_events][:,1], np.float64) 50 | X[X < 1e-6] = 0 51 | Y = Y 52 | Data = np.sum(X, axis=(1, 2, 3)) 53 | 54 | for j in np.arange(num_events): 55 | Eprof.Fill(Y[j], Data[j]/Y[j]) 56 | Eprof.SetTitle("Ratio of Ecal and Ep") 57 | Eprof.GetXaxis().SetTitle("Ep") 58 | Eprof.GetYaxis().SetTitle("Ecal/Ep") 59 | Eprof.Draw() 60 | Eprof.GetYaxis().SetRangeUser(0, 0.03) 61 | color =2 62 | Eprof.SetLineColor(color) 63 | legend = TLegend(0.8, 0.8, 0.9, 0.9) 64 | legend.AddEntry(Eprof, "Data", "l") 65 | Gprof = [] 66 | for i, gweight in enumerate(gweights): 67 | #for i in np.arange(1): 68 | # gweight=gweights[i] 69 | Gprof.append( TProfile("Gprof" +str(i), "Gprof" + str(i), 100, 0, 500)) 70 | #Gprof[i].SetStates(0) 71 | #Generate events 72 | gm.combined.load_weights(gweight) 73 | noise = np.random.normal(0, 1, (num_events, latent)) 74 | generator_in = np.multiply(np.reshape(Y/100, (-1, 1)), noise) 75 | generated_images = gm.generator.predict(generator_in, verbose=False, batch_size=100) 76 | GData = np.sum(generated_images, axis=(1, 2, 3))/scales[i] 77 | 78 | print GData.shape 79 | for j in range(num_events): 80 | Gprof[i].Fill(Y[j], GData[j]/Y[j]) 81 | color = color + 2 82 | Gprof[i].SetLineColor(color) 83 | Gprof[i].Draw('sames') 84 | c.Modified() 85 | legend.AddEntry(Gprof[i], label[i], "l") 86 | legend.Draw() 87 | c.Update() 88 | c.Print(filename) 89 | print ' The plot is saved in.....{}'.format(filename) 90 | # request user action before ending (and deleting graphics window) 91 | raw_input('Press to end -> ') 92 | -------------------------------------------------------------------------------- /mpi_learn/logger.py: -------------------------------------------------------------------------------- 1 | from mpi4py import MPI 2 | import time 3 | import logging 4 | from os.path import abspath 5 | 6 | level_map = { 7 | 'debug': logging.DEBUG, 8 | 'info': logging.INFO, 9 | 'warn': logging.WARNING, 10 | 'error': logging.ERROR, 11 | } 12 | 13 | base_prefix = "{ptype} {world}:{parent}:{process}" 14 | file_handler = None 15 | stream_handler = None 16 | 17 | start_time = time.time() 18 | 19 | class ElapsedTimeFormatter(logging.Formatter): 20 | def formatTime(self, record, datefmt=None): 21 | global start_time 22 | total_millis = int(record.created - start_time) * 1000 + int(record.msecs) 23 | 24 | millis = total_millis%1000 25 | millis = int(millis) 26 | seconds=(total_millis/1000)%60 27 | seconds = int(seconds) 28 | minutes=(total_millis/(1000*60))%60 29 | minutes = int(minutes) 30 | hours=(total_millis/(1000*60*60))%24 31 | hours = int(hours) 32 | 33 | elapsed = "{:04d}:{:02d}:{:02d}.{:03d}".format(hours, minutes, seconds, millis) 34 | return elapsed 35 | 36 | class MPIFileHandler(logging.FileHandler): 37 | def __init__(self, 38 | filename, 39 | mode=MPI.MODE_WRONLY|MPI.MODE_CREATE|MPI.MODE_APPEND , 40 | encoding='utf-8', 41 | delay=False, 42 | comm=MPI.COMM_WORLD): 43 | self.baseFilename = abspath(filename) 44 | self.mode = mode 45 | self.encoding = encoding 46 | self.comm = comm.Dup() 47 | if delay: 48 | #We don't open the stream, but we still need to call the 49 | #Handler constructor to set level, formatter, lock etc. 50 | logging.Handler.__init__(self) 51 | self.stream = None 52 | else: 53 | logging.StreamHandler.__init__(self, self._open()) 54 | 55 | def _open(self): 56 | stream = MPI.File.Open( self.comm, self.baseFilename, self.mode ) 57 | stream.Set_atomicity(True) 58 | return stream 59 | 60 | def emit(self, record): 61 | try: 62 | msg = self.format(record) 63 | stream = self.stream 64 | stream.Write_shared((msg+self.terminator).encode(self.encoding)) 65 | #self.flush() 66 | except Exception: 67 | self.handleError(record) 68 | 69 | def close(self): 70 | if self.stream: 71 | self.stream.Sync() 72 | self.stream.Close() 73 | self.stream = None 74 | 75 | def initialize_logger(filename=None, file_level='info', stream=True, stream_level='info'): 76 | global file_handler 77 | global stream_handler 78 | level = get_log_level(file_level) 79 | logger = logging.getLogger() 80 | logger.setLevel(level) 81 | if filename is not None: 82 | file_handler = MPIFileHandler(filename) 83 | logger.addHandler(file_handler) 84 | if stream: 85 | stream_handler = logging.StreamHandler() 86 | logger.addHandler(stream_handler) 87 | set_logging_prefix(MPI.COMM_WORLD.rank) 88 | 89 | def get_log_level(levelstr='info'): 90 | levelstr = levelstr.lower() 91 | return level_map[levelstr] 92 | 93 | def set_logging_prefix(world_rank, parent_rank='-', process_rank='-', process_type='P'): 94 | global file_handler 95 | global stream_handler 96 | prefix = base_prefix.format(ptype=process_type, world=world_rank, parent=parent_rank, process=process_rank) 97 | formatter = ElapsedTimeFormatter('%(asctime)s ' + prefix + ' [%(levelname)s] %(message)s') 98 | if file_handler is not None: 99 | file_handler.setFormatter(formatter) 100 | if stream_handler is not None: 101 | stream_handler.setFormatter(formatter) 102 | 103 | def get_logger(): 104 | return logging.getLogger() 105 | -------------------------------------------------------------------------------- /PytorchCNN.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch.autograd import Variable 3 | import torch.nn as nn 4 | import torch.nn.parallel 5 | import torch.backends.cudnn as cudnn 6 | import torch.distributed as dist 7 | import torch.optim 8 | import torch.utils.data.distributed 9 | import torchvision.transforms as transforms 10 | import torchvision.datasets as datasets 11 | import torchvision.models as models 12 | import torch.nn.functional as F 13 | 14 | class MNistNet(torch.nn.Module): 15 | def __init__(self, **args): 16 | super(MNistNet, self).__init__() 17 | ks = args.get('kernel_size',5) 18 | do = args.get('dropout',0.5) 19 | dense = args.get('dense',50) 20 | self.conv1 = nn.Conv2d(1, 10, kernel_size=ks) 21 | self.conv2 = nn.Conv2d(10, 20, kernel_size=ks) 22 | self.conv2_drop = nn.Dropout2d(do) 23 | self.fc1 = nn.Linear(320, dense) 24 | self.fc2 = nn.Linear(dense, 10) 25 | 26 | def forward(self, x): 27 | x = x.permute(0,3,1,2).float() 28 | x = F.relu(F.max_pool2d(self.conv1(x), 2)) 29 | x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) 30 | x = x.view(-1, 320) 31 | x = F.relu(self.fc1(x)) 32 | x = F.dropout(x, training=self.training) 33 | x = self.fc2(x) 34 | #return F.log_softmax(x, dim=1) 35 | #return F.softmax(x) 36 | #return F.cross_entropy(x) 37 | return x 38 | 39 | 40 | 41 | ### Build a customized CNN with given hyperparameters 42 | class _ConvBlock(nn.Sequential): 43 | def __init__(self, conv_layers, dropout, in_ch=5): 44 | super().__init__() 45 | for i in range(conv_layers): 46 | channel_in = in_ch*((i+1)%5) 47 | channel_out = in_ch*((i+2)%5) 48 | if channel_in == 0: channel_in += 1 49 | if channel_out == 0: channel_out += 1 50 | self.add_module('convlayer%d'%(i), nn.Conv2d(channel_in, out_channels=channel_out,kernel_size=(3,3),stride=1, padding=1)) 51 | self.add_module('relu%d'%(i), nn.ReLU(inplace=True)) 52 | self.add_module('convlayer%d'%(conv_layers), nn.Conv2d(channel_out, out_channels=1, kernel_size=(3,3), stride=2, padding=1)) 53 | self.dropout = dropout 54 | 55 | def forward(self, x): 56 | x = super().forward(x) 57 | if self.dropout > 0: 58 | x = F.dropout(x, p=self.dropout, training=self.training) 59 | return x 60 | 61 | class _DenseBlock(nn.Sequential): 62 | def __init__(self, dense_layers, dropout ,base): 63 | super().__init__() 64 | for i in range(dense_layers): 65 | il = int(base//(2**i)) 66 | ol = int(base//(2**(i+1))) 67 | print (il,"=>",ol) 68 | self.add_module('denselayer%d'%(i), nn.Linear(il, ol)) 69 | self.add_module('relu%d'%(i), nn.ReLU(inplace=True)) 70 | self.dropout = dropout 71 | 72 | def forward(self, x): 73 | x = super().forward(x) 74 | if self.dropout > 0: 75 | x = F.dropout(x, p=self.dropout, training=self.training) 76 | return x 77 | 78 | class CNN(nn.Module): 79 | def __init__(self, conv_layers=2, dense_layers=2, dropout=0.5, classes=3, in_channels=5): 80 | super().__init__() 81 | self.build_net(conv_layers, dense_layers, dropout, classes, in_channels) 82 | 83 | def build_net(self,*args, **kwargs): 84 | base_2 = 10 85 | base = base_2**2 86 | self.conv_layers = _ConvBlock(args[0], args[2], args[4]) 87 | self.dense_layers = _DenseBlock(args[1], args[2], base) 88 | self.adapt_pool = nn.AdaptiveMaxPool2d((base_2,base_2)) 89 | il = int(base//(2**(args[1]))) 90 | ol = int(args[3]) 91 | print (il,"=>",ol) 92 | self.output = nn.Linear(il, ol) 93 | 94 | def forward(self, x): 95 | x = x.permute(0,3,1,2).float() 96 | x = self.conv_layers(x) 97 | x = self.adapt_pool(x) 98 | x = x.view(x.shape[0], -1) # flatten 99 | x = self.dense_layers(x) 100 | return self.output(x) 101 | 102 | 103 | -------------------------------------------------------------------------------- /TorchModels.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch.autograd import Variable 3 | import torch.nn as nn 4 | import torch.nn.parallel 5 | import torch.backends.cudnn as cudnn 6 | import torch.distributed as dist 7 | import torch.optim 8 | import torch.utils.data.distributed 9 | import torchvision.transforms as transforms 10 | import torchvision.datasets as datasets 11 | import torchvision.models as models 12 | import torch.nn.functional as F 13 | import numpy 14 | 15 | class MNistNet(nn.Module): 16 | def __init__(self, **args): 17 | super(MNistNet, self).__init__() 18 | ks = int(args.get('kernel_size',5)) 19 | do = float(args.get('dropout',0.5)) 20 | dense = int(args.get('dense',50)) 21 | print (dense, type(dense)) 22 | print (ks, type(ks)) 23 | self.conv1 = nn.Conv2d(1, 10, kernel_size=ks) 24 | self.conv2 = nn.Conv2d(10, 20, kernel_size=ks) 25 | self.conv2_drop = nn.Dropout2d(do) 26 | self.fc1 = nn.Linear(320, dense) 27 | self.fc2 = nn.Linear(dense, 10) 28 | 29 | def forward(self, x): 30 | x = x.permute(0,3,1,2).float() 31 | x = F.relu(F.max_pool2d(self.conv1(x), 2)) 32 | x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) 33 | x = x.view(-1, 320) 34 | x = F.relu(self.fc1(x)) 35 | x = F.dropout(x, training=self.training) 36 | x = self.fc2(x) 37 | #return F.log_softmax(x, dim=1) 38 | #return F.softmax(x) 39 | #return F.cross_entropy(x) 40 | return x 41 | 42 | 43 | 44 | ### Build a customized CNN with given hyperparameters 45 | class _ConvBlock(nn.Sequential): 46 | def __init__(self, conv_layers, dropout, in_ch=5): 47 | super().__init__() 48 | for i in range(conv_layers): 49 | channel_in = in_ch*((i+1)%5) 50 | channel_out = in_ch*((i+2)%5) 51 | if channel_in == 0: channel_in += 1 52 | if channel_out == 0: channel_out += 1 53 | self.add_module('convlayer%d'%(i), nn.Conv2d(channel_in, out_channels=channel_out,kernel_size=(3,3),stride=1, padding=1)) 54 | self.add_module('relu%d'%(i), nn.ReLU(inplace=True)) 55 | self.add_module('convlayer%d'%(conv_layers), nn.Conv2d(channel_out, out_channels=1, kernel_size=(3,3), stride=2, padding=1)) 56 | self.dropout = dropout 57 | 58 | def forward(self, x): 59 | x = super().forward(x) 60 | if self.dropout > 0: 61 | x = F.dropout(x, p=self.dropout, training=self.training) 62 | return x 63 | 64 | class _DenseBlock(nn.Sequential): 65 | def __init__(self, dense_layers, dropout ,base): 66 | super().__init__() 67 | for i in range(dense_layers): 68 | il = int(base//(2**i)) 69 | ol = int(base//(2**(i+1))) 70 | print (il,"=>",ol) 71 | self.add_module('denselayer%d'%(i), nn.Linear(il, ol)) 72 | self.add_module('relu%d'%(i), nn.ReLU(inplace=True)) 73 | self.dropout = dropout 74 | 75 | def forward(self, x): 76 | x = super().forward(x) 77 | if self.dropout > 0: 78 | x = F.dropout(x, p=self.dropout, training=self.training) 79 | return x 80 | 81 | class CNN(nn.Module): 82 | def __init__(self, conv_layers=2, dense_layers=2, dropout=0.5, classes=3, in_channels=5): 83 | super().__init__() 84 | self.build_net(conv_layers, dense_layers, dropout, classes, in_channels) 85 | 86 | def build_net(self,*args, **kwargs): 87 | base_2 = 10 88 | base = base_2**2 89 | self.conv_layers = _ConvBlock(args[0], args[2], args[4]) 90 | self.dense_layers = _DenseBlock(args[1], args[2], base) 91 | self.adapt_pool = nn.AdaptiveMaxPool2d((base_2,base_2)) 92 | il = int(base//(2**(args[1]))) 93 | ol = int(args[3]) 94 | print (il,"=>",ol) 95 | self.output = nn.Linear(il, ol) 96 | 97 | def forward(self, x): 98 | x = x.permute(0,3,1,2).float() 99 | x = self.conv_layers(x) 100 | x = self.adapt_pool(x) 101 | x = x.view(x.shape[0], -1) # flatten 102 | x = self.dense_layers(x) 103 | return self.output(x) 104 | 105 | 106 | -------------------------------------------------------------------------------- /mpiLAPI.py: -------------------------------------------------------------------------------- 1 | import os 2 | import keras 3 | import glob 4 | import h5py 5 | import hashlib 6 | import time 7 | 8 | class mpi_learn_api: 9 | def __init__(self, **args): 10 | args['check'] = time.mktime(time.gmtime()) 11 | hash = hashlib.md5(str(args).encode('utf-8')).hexdigest() 12 | #hl = hashlib.md5() 13 | #hl.update(str(args)) 14 | #hash = hl.hexdigest() 15 | #hash = hashlib.sha224(bytes(str(args))).hexdigest() 16 | #hash = 'whatthefuck' 17 | cache_dir = args.get('cache_dir','/tmp/') 18 | self.json_file = '%s/%s.json'%(cache_dir, hash) 19 | if os.path.isfile( self.json_file ) : 20 | print ("hash",hash,"cannot work") 21 | sys.exit(1) 22 | self.train_files = '%s/%s_train.list'%(cache_dir,hash) 23 | self.val_files = '%s/%s_val.list'%(cache_dir,hash) 24 | 25 | open(self.json_file,'w').write(args['model'].to_json()) 26 | if 'train_files' in args: 27 | open(self.train_files,'w').write( '\n'.join(args['train_files'])) 28 | elif 'train_pattern' in args: 29 | a_list = sorted(glob.glob( args['train_pattern'])) 30 | if args.get('check_file',False): a_list = self._check_files(a_list) 31 | open(self.train_files,'w').write( '\n'.join( a_list )) 32 | else: 33 | self.train_files = args['train_list'] 34 | 35 | if 'val_files' in args: 36 | open(self.val_files,'w').write( '\n'.join(args['val_files'])) 37 | elif 'val_pattern' in args: 38 | a_list = sorted(glob.glob(args['val_pattern'])) 39 | if args.get('check_file',False): a_list = self._check_files(a_list) 40 | open(self.val_files,'w').write( '\n'.join( a_list )) 41 | else: 42 | self.val_files = args['val_list'] 43 | 44 | def _check_files(self, a_list): 45 | for fn in sorted(a_list): 46 | try: 47 | f = h5py.File(fn) 48 | l = sorted(f.keys()) 49 | assert len(l)!=0 50 | f.close() 51 | except: 52 | print (fn,"not usable") 53 | a_list.remove(fn) 54 | return a_list 55 | 56 | def train(self, **args): 57 | hf = args.get('hostfile',None) 58 | base_mpi = ' --hostfile %s'%hf if hf else '' 59 | com = 'mpirun %s -n %d %s mpi_learn/MPIDriver.py %s %s %s'%( 60 | base_mpi, 61 | args.get('N', 2), 62 | "-host %s"%args.get('hosts') if args.get('hosts','') else "", 63 | self.json_file, 64 | self.train_files, 65 | self.val_files 66 | ) 67 | for option,default in { 'trial_name' : 'mpi_run', 68 | 'master_gpu' : True, 69 | 'features_name' : 'X', 70 | 'labels_name' : 'Y', 71 | 'epoch' : 100, 72 | 'batch' : 100, 73 | 'max_gpus' : 8, 74 | 'tf' :False 75 | }.items(): 76 | v = args.get(option,default) 77 | if type(v)==bool: 78 | com +=' --%s'%option.replace('_','-') if v else '' 79 | else: 80 | com+=' --%s %s'%(option.replace('_','-'), v) 81 | print (com) 82 | os.system( com ) 83 | 84 | 85 | if __name__ == "__main__": 86 | import sys 87 | args = {} 88 | for k in sys.argv: 89 | if '=' in k: 90 | key,v = k.split('=') 91 | args[key] = v 92 | 93 | from keras.models import model_from_json 94 | model = model_from_json( open('cnn.json').read()) 95 | 96 | mlapi = mpi_learn_api( model = model, 97 | train_pattern = '/bigdata/shared/Delphes/np_datasets_old2/3_way/MaxLepDeltaR_des/train/images/*_*.h5', 98 | val_pattern = '/bigdata/shared/Delphes/np_datasets_old2/3_way/MaxLepDeltaR_des/val/images/*_*.h5', 99 | #train_pattern = '/data/shared/Delphes/np_datasets_new/3_way/MaxLepDeltaR_des/train/images/*_*.h5', 100 | #val_pattern = '/data/shared/Delphes/np_datasets_new/3_way/MaxLepDeltaR_des/val/images/*_*.h5', 101 | check_file = True, 102 | cache_dir = '/nfshome/vlimant/.mpiLAPI/' 103 | ) 104 | mlapi.train(N=int(args.get('N',4)), 105 | trial_name = 'with_api', 106 | features_name = 'Images', 107 | labels_name = 'Labels', 108 | batch = 200, 109 | #tf = True, 110 | max_gpus = int(args.get('gpus',8)), 111 | hosts=args.get('host','')#mpi-culture-plate-sm,mpi-imperium-sm,mpi-passed-pawn-klmx' 112 | ) 113 | 114 | -------------------------------------------------------------------------------- /mpi_learn/train/trace.py: -------------------------------------------------------------------------------- 1 | import os 2 | import psutil 3 | import time 4 | import json 5 | from functools import wraps 6 | from mpi4py import MPI 7 | 8 | def trace(original_function=None, category=None, **decorator_kwargs): 9 | """Decorates a function. Can be called with or without additional arguments. Name of event is the name of decorated function. 10 | Params: 11 | category: Optional category of event (useful to show/hide category of events in trace viewer) 12 | decorator_kwargs: Additional arguments 13 | """ 14 | def _decorate(function): 15 | @wraps(function) 16 | def wrapped_function(*args, **kwargs): 17 | Trace.begin(function.__name__, category, **decorator_kwargs) 18 | if len(args) == 1 and not kwargs and callable(args[0]): 19 | ret_val = function()(args[0]) 20 | else: 21 | ret_val = function(*args, **kwargs) 22 | Trace.end(function.__name__, category, **decorator_kwargs) 23 | return ret_val 24 | 25 | return wrapped_function 26 | 27 | if original_function: 28 | return _decorate(original_function) 29 | 30 | return _decorate 31 | 32 | class Trace(object): 33 | """ Class that traces events to display on timeline """ 34 | _enabled = False 35 | _events = [] 36 | _process_name = os.getpid() 37 | _process_file = None 38 | _flush_every = 100 39 | 40 | @classmethod 41 | def _trace(cls, event_name, type, category=None, **kwargs): 42 | if cls._enabled: 43 | ts = int(round(time.time() * 1000000)) 44 | if category is None: category = "TRACE" 45 | tid = kwargs.get("tid", "Main") 46 | 47 | event = {"name": event_name, "cat": category, "ph": type, "pid": cls._process_name, "tid": tid, "ts": ts, "args": kwargs} 48 | 49 | cls._events.append(event) 50 | 51 | # Write events to process-specific file (in case collect() is never called) 52 | if cls._flush_every > 0 and len(cls._events) % cls._flush_every == 0: 53 | with open(cls._process_file, 'a+') as trace_file: 54 | trace_file.write(",\n".join(map(json.dumps, cls._events[-cls._flush_every:]))) 55 | 56 | @classmethod 57 | def begin(cls, name, category=None, **kwargs): 58 | """Marks the beginning of an event. 59 | Params: 60 | name: Name of event 61 | category: Optional category of event (useful to show/hide category of events in trace viewer) 62 | kwargs: Additional arguments 63 | """ 64 | cls._trace(name, "B", category, **kwargs) 65 | 66 | @classmethod 67 | def end(cls, name, category=None, **kwargs): 68 | """Marks the end of an event. 69 | Params: 70 | name: Name of event 71 | category: Optional category of event (useful to show/hide category of events in trace viewer) 72 | kwargs: Additional arguments 73 | """ 74 | cls._trace(name, "E", category, **kwargs) 75 | 76 | @classmethod 77 | def enable(cls, flush_file=None, flush_every=100): 78 | """Enables collection of trace events. 79 | Params: 80 | flush_file: name of per-process trace file to temporarily write events to, if None, 'str(os.getpid()) + _trace.json' is used 81 | flush_every: Number of events to collect before flushing them to temporary file. 0 disables writing. 82 | """ 83 | cls._enabled = True 84 | cls._process_file = flush_file or str(os.getpid()) + "_trace.json" 85 | cls._flush_every = flush_every 86 | 87 | @classmethod 88 | def set_process_name(cls, process_name): 89 | """Sets a user-defined name for the process in timeline, as opposed to using just pid of process 90 | Params: 91 | process_name: Name to use 92 | """ 93 | cls._process_name = process_name 94 | 95 | @classmethod 96 | def collect(cls, file_name=None, clean=False, comm=None): 97 | """Collects events from processes and writes them to a trace file. 98 | Params: 99 | file_name: name of trace file to write events to, if None, 'mpi_learn_trace.json' is used 100 | clean: If True, removes process-specific temporary trace files 101 | comm: MPI communicator to use, if None, MPI.COMM_WORLD is used 102 | """ 103 | if not cls._enabled: 104 | return 105 | 106 | comm = comm or MPI.COMM_WORLD 107 | all_events = comm.gather(cls._events, root=0) 108 | 109 | if (comm.Get_rank() == 0): 110 | with open(file_name or "mpi_learn_trace.json", 'w+') as master_file: 111 | master_file.write("[\n") 112 | flat_events = [] 113 | for events in all_events: 114 | flat_events.append(",\n".join(map(json.dumps, events))) 115 | master_file.write(",\n".join(flat_events)) 116 | master_file.write("\n]\n") 117 | 118 | if clean and os.path.isfile(cls._process_file): 119 | os.remove(cls._process_file) 120 | -------------------------------------------------------------------------------- /simple_train.py: -------------------------------------------------------------------------------- 1 | import optparse 2 | 3 | parser = optparse.OptionParser() 4 | parser.add_option('--restart',action='store_true') 5 | parser.add_option('--train',action='store_true') 6 | parser.add_option('--test',action='store_true') 7 | parser.add_option('--fresh',action='store_true') 8 | parser.add_option('--fom', action='store_true') 9 | parser.add_option('--tag',default='') 10 | parser.add_option('--max',type='int', default = 0) 11 | parser.add_option('--lr',type='float',default=0.0) 12 | parser.add_option('--epochs', type='int', default=3) 13 | parser.add_option('--cache',default=None) 14 | 15 | (options,args) = parser.parse_args() 16 | 17 | from mpi_learn.train.GanModel import GANModel 18 | from mpi_learn.train.data import H5Data 19 | import h5py 20 | import setGPU 21 | import json 22 | import time 23 | 24 | 25 | gan_args = { 26 | #'tell': False, 27 | #'reversedorder' : False, 28 | #'heavycheck' : False, 29 | #'show_values' : False, 30 | #'gen_bn' : True, 31 | #'checkpoint' : False, 32 | #'onepass' : False, 33 | #'show_loss' : True, 34 | #'with_fixed_disc' : True ## could switch back to False and check 35 | } 36 | 37 | gm = GANModel(**gan_args) 38 | 39 | restart = options.restart 40 | fresh = options.fresh 41 | tag = (options.tag+'_') if options.tag else '' 42 | lr = options.lr 43 | 44 | if restart: 45 | tag+='reload_' 46 | print ("Reloading") 47 | if lr: 48 | gm.compile( prop = False, lr=lr) 49 | tag+='sgd%s_'%lr 50 | else: 51 | gm.compile( prop = True) 52 | tag+='rmsprop_' 53 | 54 | ## start from an exiting model 55 | gm.generator.load_weights('FullRunApr3/simple_generator.h5') 56 | gm.discriminator.load_weights('FullRunApr3/simple_discriminator.h5') 57 | gm.combined.load_weights('FullRunApr3/simple_combined.h5') 58 | else: 59 | if lr: 60 | gm.compile(prop = False, lr=lr) 61 | tag+='sgd%s_'%lr 62 | else: 63 | gm.compile() 64 | tag+='rmsprop_' 65 | 66 | if not fresh: 67 | try: 68 | gm.generator.load_weights('simple_generator.h5') 69 | gm.discriminator.load_weights('simple_discriminator.h5') 70 | except: 71 | print ("fresh weights") 72 | else: 73 | tag+='fresh_' 74 | 75 | print (tag,"is the option") 76 | 77 | files = list(filter(None,open('train_3d.list').read().split('\n'))) 78 | data = H5Data( batch_size = 100, 79 | cache = options.cache, 80 | preloading=0, 81 | features_name='X', labels_name='y') 82 | data.set_file_names(files) 83 | """ 84 | 85 | if options.inmem: 86 | import os 87 | relocated = [] 88 | os.system('mkdir /dev/shm/vlimant/') 89 | for fn in files: 90 | relocate = '/dev/shm/vlimant/'+fn.split('/')[-1] 91 | if not os.path.isfile( relocate ): 92 | print ("copying %s to %s"%( fn , relocate)) 93 | if os.system('cp %s %s'%( fn ,relocate))==0: 94 | relocated.append( relocate ) 95 | files = relocated 96 | """ 97 | history = {} 98 | thistory = {} 99 | fhistory = {} 100 | etimes=[] 101 | start = time.mktime(time.gmtime()) 102 | 103 | 104 | train_me = options.train 105 | over_test= options.test 106 | max_batch = options.max 107 | ibatch=0 108 | def dump(): 109 | open('simple_train_%s.json'%tag,'w').write(json.dumps( 110 | { 111 | 'h':history, 112 | 'th':thistory, 113 | 'fh':fhistory, 114 | 'et':etimes, 115 | } )) 116 | 117 | nepochs = options.epochs 118 | 119 | histories={} 120 | for e in range(nepochs): 121 | history[e] = [] 122 | thistory[e] = [] 123 | fhistory[e] = [] 124 | e_start = time.mktime(time.gmtime()) 125 | for sub_X,sub_Y in data.generate_data(): 126 | ibatch+=1 127 | #print (ibatch,ibatch>max_batch,max_batch) 128 | if over_test or not train_me: 129 | t_losses = gm.test_on_batch(sub_X,sub_Y) 130 | l = gm.get_logs( t_losses ,val=True) 131 | gm.update_history( l , histories) 132 | t_losses = [list(map(float,l)) for l in t_losses] 133 | thistory[e].append( t_losses ) 134 | if train_me: 135 | losses = gm.train_on_batch(sub_X,sub_Y) 136 | l = gm.get_logs( losses ) 137 | gm.update_history( l , histories) 138 | losses = [list(map(float,l)) for l in losses] 139 | history[e].append( losses ) 140 | if max_batch and ibatch>max_batch: 141 | break 142 | 143 | #if options.fom: 144 | # fom = gm.figure_of_merit() 145 | # print ("figure of merit",fom) 146 | 147 | if options.fom: 148 | fom = gm.figure_of_merit() 149 | print ("figure of merit",fom) 150 | fhistory[e].append( fom ) 151 | gm.generator.save_weights('simple_generator_%s.h5'%tag) 152 | gm.discriminator.save_weights('simple_discriminator_%s.h5'%tag) 153 | gm.combined.save_weights('simple_combined_%s.h5'%tag) 154 | dump() 155 | if max_batch and ibatch>max_batch: 156 | break 157 | 158 | e_stop = time.mktime(time.gmtime()) 159 | print (e_stop - e_start,"[s] for epoch",e) 160 | etimes.append( e_stop - e_start) 161 | dump() 162 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mpi_learn 2 | Distributed learning with mpi4py 3 | 4 | Dependencies: [`OpenMPI`](https://www.open-mpi.org/) and [`mpi4py`](http://mpi4py.readthedocs.io/en/stable/) (v. >= 2.0.0), [`keras`](https://keras.io/) (v. >= 1.2.0) 5 | 6 | Test with the MNIST dataset: 7 | ``` 8 | git clone https://github.com/duanders/mpi_learn.git 9 | cd mpi_learn 10 | python BuildModel.py mnist 11 | python models/get_mnist.py 12 | mpirun -np 3 ./MPIDriver.py mnist_arch.json train_mnist.list test_mnist.list --loss categorical_crossentropy --epochs 3 13 | ``` 14 | 15 | ## Using MPIDriver.py to train your model 16 | 17 | `MPIDriver.py` will load a keras model of your choice and train it on the input data you provide. The script has three required arguments: 18 | - Path to JSON file specifying the Keras model (your model can be converted to JSON using the model's `to_json()` method) 19 | - File containing a list of training data. This should be a simple text file with one input data file per line. By default the script expects data stored in HDF5 format; see below for instructions for handling arbitrary input data. 20 | - File containing a list of validation data. This should be a simple text file with one input data file per line. 21 | 22 | See `MPIDriver.py` for supported optional arguments. Run the script via `mpirun` or `mpiexec`. It should automatically detect available NVIDIA GPUs and allocate them among the MPI worker processes. 23 | 24 | ## Customizing the training process 25 | 26 | The provided `MPIDriver.py` script handles the case of a model that is specified in JSON format and training data that is stored in HDF5 files. However, the construction of the model and the loading of input data are easily customized. 27 | 28 | #### Model 29 | 30 | Use the ModelBuilder class to specify how your model should be constructed: 31 | [mpi_learn/train/model.py](mpi_learn/train/model.py) 32 | 33 | To specify your model, create a new class deriving from ModelBuilder and override the `build_model()` method. This method should take no arguments and return the Keras model you wish to train. 34 | 35 | Provide an instance of ModelBuilder when you construct the MPIManager object (see below). At train time, the `build_model` method of the ModelBuilder will be called, constructing the model you specified. 36 | 37 | The provided ModelFromJson class is a specialized ModelBuilder that constructs a model from a JSON file (as produced by the `to_json()` method of a `keras` model). This is usually the easiest way to specify the model architecture. 38 | 39 | #### Training/Testing data 40 | 41 | Use the Data class to specify how batches of training data should be generated: 42 | [mpi_learn/train/data.py](mpi_learn/train/data.py) 43 | 44 | To specify your training data, create a new class deriving from Data and override the `generate_data()` method. The `generate_data` method should act as follows: 45 | - yield batches of training data in the form required for training with Keras, i.e. ( [x1, x2, ...], [y1, y2, ...] ) 46 | - stop yielding batches and return after one epoch's worth of training data has been generated. 47 | 48 | Provide an instance of the Data class when you construct the MPIManager (see below). During training, workers will iterate over the output of the `generate_data` method once per epoch, computing the gradient of the loss function on each batch. 49 | 50 | Note: `generate_data` should not continue to yield training batches forever; rather it should generate one epoch's worth of data before returning. 51 | 52 | #### Optimization Procedure 53 | 54 | Use the Algo class to configure the details of the training algorithm: 55 | [mpi_learn/train/algo.py](mpi_learn/train/algo.py) 56 | 57 | Provide an instance of the Algo class when you construct the MPIManager (see below). The Algo constructor takes several arguments that specify aspects of the training process: 58 | - `optimizer`: supported arguments are `'sgd'`, `'adadelta'`, `'rmsprop'`, and `'adam'`. For optimizers that have tunable parameters, please specify the values of those parameters as additional arguments (see [mpi_learn/train/optimizer.py](mpi_learn/train/optimizer.py) for details on the individual optimizers) 59 | - `loss`: loss function, specified as a string, e.g. 'categorical_crossentropy' 60 | - `validate_every`: number of gradient updates to process before performing validation. Set to 0 to disable validation. 61 | - `sync_every`: number of batches for workers to process between gradient updates (default 1) 62 | 63 | By default the training is performed using the Downpour SGD algorithm [1]. To instead use Elastic Averaging SGD [2], the following additional settings should be provided: 64 | - `mode`: specify `'easgd'` 65 | - `worker_optimizer`: learning algorithm used by individual worker processes 66 | - `elastic_force`, `elastic_lr`, `elastic_momentum`: force, learning rate, and momentum parameters for the EASGD algorithm 67 | 68 | ### Launching the training process 69 | 70 | Training is initiated by an instance of the MPIManager class, which initializes each MPI process as a worker or master and prepares the training procedure. The MPIManager is constructed using the following ingredients (see MPIDriver.py for example usage): 71 | - `comm`: MPI communicator object, usually `MPI.COMM_WORLD` 72 | - `data`, `algo`, `model_builder`: instances of the `Data`, `Algo`, and `ModelBuilder` classes (see above). These three elements determine most of the details of training. 73 | - `num_epochs`: number of training epochs 74 | - `train_list`, `val_list`: lists of inputs files to use for training and validation. Each MPI process should be able to access any/all of the input files; the MPIManager will split the input files among the available worker processes. 75 | - `callbacks`: list of `keras` callback objects, to be executed by the master process 76 | 77 | Other options are available as well: see [mpi_learn/mpi/manager.py](mpi_learn/mpi/manager.py) 78 | 79 | ### Training algorithm overview 80 | 81 | In the default training configuration, one MPI process (process 0) is initialized as 'Master' and all others are initialized as 'Workers'. The Master and each Worker have a copy of the model to be trained. Each Worker has access to a subset of the training data. 82 | 83 | During training, a Worker reads one batch of training data and computes the gradient of the loss function on that batch. The Worker sends the gradient to the Master, which uses it to update its model weights. The Master sends the updated model weights to the Worker, which then repeats the process with the next batch of training data. 84 | 85 | ![downpour](docs/downpour.png) 86 | 87 | ### References 88 | 89 | [1] Dean et al., Large Scale Distributed Deep Networks. https://research.google.com/archive/large_deep_networks_nips2012.html. 90 | 91 | [2] Zhang et al., Deep Learning with Elastic Averaging SGD. https://arxiv.org/abs/1412.6651 92 | -------------------------------------------------------------------------------- /mpi_learn/train/algo.py: -------------------------------------------------------------------------------- 1 | ### Algo class 2 | import os 3 | import numpy as np 4 | import logging 5 | from ast import literal_eval 6 | from .optimizer import get_optimizer, MultiOptimizer, OptimizerBuilder 7 | 8 | class Algo(object): 9 | """The Algo class contains all information about the training algorithm. 10 | Attributes: 11 | optimizer: instance of the Optimizer class used to compute training updates 12 | optimizer_name: name of the optimizer 13 | staleness: difference in time step between master and most recent worker's update 14 | worker_update_type: whether to send weights or gradients to parent process 15 | send_before_apply: whether to send weights before applying update 16 | step_counter: counts time steps to determine when to sync 17 | (used for Elastic Averaging SGD) 18 | See __init__ for list of other supported attributes 19 | """ 20 | 21 | # available options and their default values 22 | supported_opts = {'loss':'binary_crossentropy', 23 | 'validate_every':1000, 24 | 'sync_every':1, 25 | 'mode':'sgd', 26 | 'worker_optimizer':'sgd', 27 | 'worker_optimizer_params':'{}', 28 | 'elastic_force':None, 29 | 'elastic_lr':1.0, 30 | 'elastic_momentum':0, 31 | } 32 | 33 | def __init__(self, optimizer, **kwargs): 34 | """optimizer: string naming an optimization algorithm as defined in Optimizer.get_optimizer() 35 | Configuration options should be provided as keyword arguments. 36 | Available arguments are: 37 | loss: string naming the loss function to be used for training 38 | validate_every: number of time steps to wait between validations 39 | sync_every: number of time steps to wait before getting weights from parent 40 | mode: 'sgd', 'easgd' or 'gem' are supported 41 | worker_optimizer: string indicating which optimizer the worker should use. 42 | (note that if worker_optimizer is sgd and worker_lr is 1, the worker's 43 | updates will be the gradients computed at each time step, which is 44 | what is needed for many algorithms.) 45 | elastic_force: alpha constant in the Elastic Averaging SGD algorithm 46 | elastic_lr: EASGD learning rate for worker 47 | elastic_momentum: EASGD momentum for worker 48 | Optimizer configuration options should be provided as additional 49 | named arguments (check your chosen optimizer class for details).""" 50 | for opt in self.supported_opts: 51 | if opt in kwargs: 52 | setattr(self, opt, kwargs[opt]) 53 | else: 54 | setattr(self, opt, self.supported_opts[opt]) 55 | 56 | self.optimizer_name = optimizer 57 | if optimizer is not None: 58 | optimizer_args = { arg:val for arg,val in kwargs.items() 59 | if arg not in self.supported_opts } 60 | self.optimizer = get_optimizer( optimizer )(**optimizer_args) 61 | else: 62 | self.optimizer = None 63 | 64 | """Workers are only responsible for computing the gradient and 65 | sending it to the master, so we use ordinary SGD with learning rate 1 and 66 | compute the gradient as (old weights - new weights) after each batch.""" 67 | self.worker_optimizer_builder = OptimizerBuilder(self.worker_optimizer, literal_eval(self.worker_optimizer_params)) 68 | 69 | self.step_counter = 0 70 | if self.mode == 'gem': 71 | self.worker_update_type = 'gem' 72 | elif self.mode == 'easgd': 73 | self.worker_update_type = 'weights' 74 | self.send_before_apply = True 75 | else: 76 | self.worker_update_type = 'update' 77 | self.send_before_apply = False 78 | 79 | # Keep track if internal state was restored 80 | self.restore = False 81 | 82 | def reset(self): 83 | ## reset any caching running values 84 | if self.optimizer: 85 | self.optimizer.reset() 86 | 87 | def get_config(self): 88 | config = {} 89 | config['optimizer'] = str(self.optimizer_name) 90 | for opt in self.supported_opts: 91 | config[opt] = str(getattr(self, opt)) 92 | return config 93 | 94 | def __str__(self): 95 | strs = [ "optimizer: "+str(self.optimizer_name) ] 96 | strs += [ opt+": "+str(getattr(self, opt)) for opt in self.supported_opts ] 97 | return '\n'.join(strs) 98 | 99 | ### For Worker ### 100 | 101 | def compile_model(self, model): 102 | """Compile the model.""" 103 | model.compile( loss=self.loss, optimizer=self.worker_optimizer_builder, metrics=['accuracy'] ) 104 | 105 | def compute_update(self, cur_weights, new_weights): 106 | """Computes the update to be sent to the parent process""" 107 | if self.worker_update_type == 'gem': 108 | return self.optimizer.begin_compute_update(cur_weights, new_weights) 109 | elif self.worker_update_type == 'weights': 110 | return new_weights 111 | else: 112 | update = [] 113 | for cur_w, new_w in zip( cur_weights, new_weights ): 114 | if type(cur_w) == list: 115 | ## polymorph case 116 | update.append([]) 117 | for sub_c_w,sub_n_w in zip(cur_w, new_w): 118 | update[-1].append( np.subtract( sub_c_w,sub_n_w) ) 119 | else: 120 | update.append( np.subtract( cur_w, new_w ) ) 121 | return update 122 | 123 | def compute_update_worker(self, weights, update): 124 | """Compute the update on worker (for GEM)""" 125 | if self.mode == 'gem': # Only possible in GEM mode 126 | return self.optimizer.compute_update(weights, update) 127 | 128 | def set_worker_model_weights(self, model, weights): 129 | """Apply a new set of weights to the worker's copy of the model""" 130 | if self.mode == 'easgd': 131 | new_weights = self.get_elastic_update( model.get_weights(), weights ) 132 | model.set_weights( new_weights ) 133 | else: 134 | model.set_weights( weights ) 135 | 136 | def get_elastic_update(self, cur_weights, other_weights): 137 | """EASGD weights update""" 138 | new_weights = [] 139 | for m_w,om_w in zip( cur_weights, other_weights ): 140 | if type( m_w ) == list: 141 | new_weights.append( [] ) 142 | for cur_w,other_w in zip( m_w, om_w ): 143 | new_w = cur_w - self.elastic_force * np.subtract( cur_w, other_w ) 144 | new_weights[-1].append( new_w ) 145 | else: 146 | new_w = m_w - self.elastic_force * np.subtract( m_w, om_w ) 147 | new_weights.append( new_w ) 148 | return new_weights 149 | 150 | def should_sync(self): 151 | """Determine whether to pull weights from the master""" 152 | self.step_counter += 1 153 | return self.step_counter % self.sync_every == 0 154 | 155 | ### For Master ### 156 | 157 | def apply_update(self, weights, update): 158 | """Calls the optimizer to apply an update 159 | and returns the resulting weights""" 160 | if self.mode == 'easgd': 161 | return self.get_elastic_update( weights, update ) 162 | else: 163 | if type(weights[0]) == list: 164 | if type(self.optimizer)!= MultiOptimizer: 165 | self.optimizer = MultiOptimizer( self.optimizer, len(weights)) 166 | new_weights = self.optimizer.apply_update( weights, update ) 167 | return new_weights 168 | 169 | def save(self, fn=None): 170 | if self.optimizer: 171 | self.optimizer.save(fn) 172 | 173 | def load(self, fn): 174 | new_optimizer = self.optimizer.load(fn) 175 | if new_optimizer is not None: 176 | logging.info("Restored state from {}".format(fn)) 177 | self.optimizer = new_optimizer 178 | self.restore = True 179 | else: 180 | logging.warning("Failed to restore state from {}, starting srom scratch".format(fn)) 181 | -------------------------------------------------------------------------------- /models/Models.py: -------------------------------------------------------------------------------- 1 | ### Predefined Keras models 2 | 3 | #import setGPU 4 | #import numpy as np 5 | import sys 6 | try: 7 | from keras.models import Sequential, Model 8 | from keras.layers import Dense, Activation, Dropout, Flatten, Input, Permute 9 | from keras.layers import Convolution2D, MaxPooling2D, Conv2D 10 | import keras.backend as K 11 | except: 12 | print ("no keras support") 13 | 14 | try: 15 | import torch 16 | import torch.nn as nn 17 | import torch.nn.functional as F 18 | except: 19 | print ("no torch support") 20 | 21 | def model_function(model_name): 22 | """Constructs the Keras model indicated by model_name""" 23 | model_maker_dict = { 24 | 'example':make_example_model, 25 | 'mnist':make_mnist_model, 26 | 'cifar10':make_cifar10_model, 27 | 'mnist_torch':make_mnist_torch_model, 28 | 'topclass': make_topclass_model, 29 | 'topclass_torch':make_topclass_torch_model 30 | 31 | } 32 | return model_maker_dict[model_name] 33 | def make_model(model_name, **args): 34 | m_fn = model_function(model_name) 35 | if args and hasattr(m_fn,'parameter_range'): 36 | provided = set(args.keys()) 37 | accepted = set([a.name for a in m_fn.parameter_range]) 38 | if not provided.issubset( accepted ): 39 | print ("provided arguments",sorted(provided),"do not match the accepted ones",sorted(accepted)) 40 | sys.exit(-1) 41 | return model_function(model_name)(**args) 42 | 43 | def make_example_model(): 44 | """Example model from keras documentation""" 45 | model = Sequential() 46 | model.add(Dense(output_dim=64, input_dim=100)) 47 | model.add(Activation("relu")) 48 | model.add(Dense(output_dim=10)) 49 | model.add(Activation("softmax")) 50 | return model 51 | 52 | def make_topclass_model(**args): 53 | if args:print ("receiving arguments",args) 54 | conv_layers=args.get('conv_layers',2) 55 | dense_layers=args.get('dense_layers',2) 56 | dropout=args.get('dropout',0.2) 57 | kernel = args.get('kernel_size',3) 58 | classes=3 59 | in_channels=5 60 | in_ch = in_channels 61 | ## the trace in the input file is 750, 150, 94, 5 62 | input = Input( (150,94,in_ch)) 63 | ## convs 64 | c = input 65 | for i in range(conv_layers): 66 | channel_in = in_ch*((i+1)%5) 67 | channel_out = in_ch*((i+2)%5) 68 | if channel_in == 0: channel_in += 1 69 | if channel_out == 0: channel_out += 1 70 | c = Conv2D( filters=channel_out, kernel_size=(kernel,kernel) , strides=1, padding="same", activation = 'relu') (c) 71 | c = Conv2D(1, (kernel,kernel), activation = 'relu',strides=2, padding="same")(c) 72 | 73 | ## pooling 74 | pool = args.get('pool', 10) 75 | m = MaxPooling2D((pool,pool))(c) 76 | f = Flatten()(m) 77 | d = f 78 | base = args.get('hidden_factor',5)*100 79 | for i in range(dense_layers): 80 | N = int(base//(2**(i+1))) 81 | d = Dense( N, activation='relu')(d) 82 | if dropout: 83 | d = Dropout(dropout)(d) 84 | o = Dense(classes, activation='softmax')(d) 85 | 86 | model = Model(inputs=input, outputs=o) 87 | #model.summary() 88 | return model 89 | 90 | def make_cifar10_model(**args): 91 | if args:print ("receiving arguments",args) 92 | nb_classes = 10 93 | img_rows, img_cols = 32, 32 94 | 95 | # use 1 kernel size for all convolutional layers 96 | ks = args.get('kernel_size', 3) 97 | 98 | # tune the number of filters for each convolution layer 99 | nb_filters1 = args.get('nb_filters1', 48) 100 | nb_filters2 = args.get('nb_filters2', 96) 101 | nb_filters3 = args.get('nb_filters3', 192) 102 | 103 | # tune the pool size once 104 | ps = args.get('pool_size', 2) 105 | pool_size = (ps,ps) 106 | 107 | # tune the dropout rates independently 108 | do4 = args.get('dropout1', 0.25) 109 | do5 = args.get('dropout2', 0.5) 110 | 111 | # tune the dense layers independently 112 | dense1 = args.get('dense1', 512) 113 | dense2 = args.get('dense2', 256) 114 | 115 | if K.image_dim_ordering() == 'th': 116 | input_shape = (3, img_rows, img_cols) 117 | else: 118 | input_shape = (img_rows, img_cols, 3) 119 | 120 | #act = 'sigmoid' 121 | act = 'relu' 122 | 123 | i = Input( input_shape) 124 | l = Conv2D(nb_filters1,( ks, ks), padding='same', activation = act)(i) 125 | l = MaxPooling2D(pool_size=pool_size)(l) 126 | #l = Dropout(do1)(l) 127 | 128 | l = Conv2D(nb_filters2, (ks, ks), padding='same',activation=act)(l) 129 | #l = Conv2D(nb_filters2, (ks, ks))(l) 130 | l = MaxPooling2D(pool_size=pool_size)(l) 131 | #l = Dropout(do2)(l) 132 | 133 | l = Conv2D(nb_filters3, (ks, ks), padding='same',activation=act)(l) 134 | #l = Conv2D(nb_filters3, (ks, ks))(l) 135 | l = MaxPooling2D(pool_size=pool_size)(l) 136 | #l = Dropout(do3)(l) 137 | 138 | l = Flatten()(l) 139 | l = Dense(dense1,activation=act)(l) 140 | l = Dropout(do4)(l) 141 | l = Dense(dense2,activation=act)(l) 142 | l =Dropout(do5)(l) 143 | 144 | o = Dense(nb_classes, activation='softmax')(l) 145 | 146 | model = Model(inputs=i, outputs=o) 147 | #model.summary() 148 | 149 | return model 150 | 151 | def make_mnist_model(**args): 152 | """MNIST ConvNet from keras/examples/mnist_cnn.py""" 153 | #np.random.seed(1337) # for reproducibility 154 | if args:print ("receiving arguments",args) 155 | nb_classes = 10 156 | # input image dimensions 157 | img_rows, img_cols = 28, 28 158 | # number of convolutional filters to use 159 | nb_filters = args.get('nb_filters',32) 160 | # size of pooling area for max pooling 161 | ps = args.get('pool_size',2) 162 | 163 | # convolution kernel size 164 | ks = args.get('kernel_size',3) 165 | do = args.get('dropout', 0.25) 166 | dense = args.get('dense', 128) 167 | 168 | pool_size = (ps,ps) 169 | if K.image_dim_ordering() == 'th': 170 | input_shape = (1, img_rows, img_cols) 171 | else: 172 | input_shape = (img_rows, img_cols, 1) 173 | model = Sequential() 174 | model.add(Convolution2D(nb_filters, (ks, ks), 175 | border_mode='valid', 176 | input_shape=input_shape)) 177 | model.add(Activation('relu')) 178 | model.add(Convolution2D(nb_filters, (ks, ks))) 179 | model.add(Activation('relu')) 180 | model.add(MaxPooling2D(pool_size=pool_size)) 181 | model.add(Dropout(do)) 182 | model.add(Flatten()) 183 | model.add(Dense(dense)) 184 | model.add(Activation('relu')) 185 | model.add(Dropout(do)) 186 | model.add(Dense(nb_classes)) 187 | model.add(Activation('softmax')) 188 | return model 189 | 190 | def make_mnist_torch_model(**args): 191 | if args:print ("receiving arguments",args) 192 | from TorchModels import MNistNet 193 | model = MNistNet(**args) 194 | return model 195 | 196 | def make_topclass_torch_model(**args): 197 | if args:print ("receiving arguments",args) 198 | conv_layers=args.get('conv_layers',2) 199 | dense_layers=args.get('dense_layers',2) 200 | dropout=args.get('dropout',0.5) 201 | classes=3 202 | in_channels=5 203 | from TorchModels import CNN 204 | model = CNN(conv_layers=conv_layers, dense_layers=dense_layers, dropout=dropout, classes=classes, in_channels=in_channels) 205 | return model 206 | 207 | try: 208 | from skopt.space import Real, Integer, Categorical 209 | make_mnist_model.parameter_range = [ 210 | Integer(10,50, name='nb_filters'), 211 | Integer(2,10, name='pool_size'), 212 | Integer(2,10, name='kernel_size'), 213 | Integer(50,200, name='dense'), 214 | Real(0.0, 1.0, name='dropout') 215 | ] 216 | make_mnist_torch_model.parameter_range = [ 217 | Integer(2,10, name='kernel_size'), 218 | Integer(50,200, name='dense'), 219 | Real(0.0, 1.0, name='dropout') 220 | ] 221 | make_topclass_model.parameter_range = [ 222 | Integer(1,6, name='conv_layers'), 223 | Integer(1,6, name='dense_layers'), 224 | Integer(1,6, name='kernel_size'), 225 | Real(0.0, 1.0, name='dropout') 226 | ] 227 | make_topclass_torch_model.parameter_range = [ 228 | Integer(1,6, name='conv_layers'), 229 | Integer(1,6, name='dense_layers'), 230 | Real(0.0,1.0, name='dropout') 231 | ] 232 | make_cifar10_model.parameter_range = [ 233 | Integer(10,300, name='nb_filters1'), 234 | Integer(10,300, name='nb_filters2'), 235 | Integer(10,300, name='nb_filters3'), 236 | Integer(50,1000, name='dense1'), 237 | Integer(50,1000, name='dense2'), 238 | Real(0.0, 1.0, name='dropout1'), 239 | Real(0.0, 1.0, name='dropout2') 240 | ] 241 | except: 242 | pass 243 | 244 | -------------------------------------------------------------------------------- /MPIGDriver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | ### This script creates an MPIManager object and launches distributed training. 4 | 5 | import sys,os 6 | import numpy as np 7 | import argparse 8 | import json 9 | import re 10 | 11 | from mpi4py import MPI 12 | from time import time,sleep 13 | 14 | from mpi_learn.mpi.manager import MPIManager, get_device 15 | from mpi_learn.train.algo import Algo 16 | from mpi_learn.train.data import H5Data 17 | from mpi_learn.train.model import ModelFromJson, ModelTensorFlow 18 | from mpi_learn.utils import import_keras 19 | import socket 20 | 21 | if __name__ == '__main__': 22 | parser = argparse.ArgumentParser() 23 | parser.add_argument('--verbose',help='display metrics for each training batch',action='store_true') 24 | parser.add_argument('--profile',help='profile theano code',action='store_true') 25 | parser.add_argument('--monitor',help='Monitor cpu and gpu utilization', action='store_true') 26 | parser.add_argument('--tf', help='use tensorflow backend', action='store_true') 27 | 28 | # model arguments 29 | parser.add_argument('model_json', help='JSON file containing model architecture') 30 | parser.add_argument('--trial-name', help='descriptive name for trial', 31 | default='train', dest='trial_name') 32 | 33 | # training data arguments 34 | parser.add_argument('train_data', help='text file listing data inputs for training') 35 | parser.add_argument('val_data', help='text file listing data inputs for validation') 36 | parser.add_argument('--features-name', help='name of HDF5 dataset with input features', 37 | default='features', dest='features_name') 38 | parser.add_argument('--labels-name', help='name of HDF5 dataset with output labels', 39 | default='labels', dest='labels_name') 40 | parser.add_argument('--batch', help='batch size', default=100, type=int) 41 | parser.add_argument('--preload-data', help='Preload files as we read them', default=0, type=int, dest='data_preload') 42 | parser.add_argument('--cache-data', help='Cache the input files to a provided directory', default='', dest='caching_dir') 43 | 44 | # configuration of network topology 45 | parser.add_argument('--masters', help='number of master processes', default=1, type=int) 46 | parser.add_argument('--processes', help='number of processes per worker', default=1, type=int) 47 | parser.add_argument('--max-gpus', dest='max_gpus', help='max GPUs to use', 48 | type=int, default=-1) 49 | parser.add_argument('--master-gpu',help='master process should get a gpu', 50 | action='store_true', dest='master_gpu') 51 | parser.add_argument('--synchronous',help='run in synchronous mode',action='store_true') 52 | 53 | # configuration of training process 54 | parser.add_argument('--epochs', help='number of training epochs', default=1, type=int) 55 | parser.add_argument('--optimizer',help='optimizer for master to use',default='adam') 56 | parser.add_argument('--loss',help='loss function',default='binary_crossentropy') 57 | parser.add_argument('--early-stopping', default=None, 58 | dest='early_stopping', help='Configuration for early stopping') 59 | parser.add_argument('--target-metric', default=None, 60 | dest='target_metric', help='Passing configuration for a target metric') 61 | parser.add_argument('--worker-optimizer',help='optimizer for workers to use', 62 | dest='worker_optimizer', default='sgd') 63 | parser.add_argument('--worker-optimizer-params',help='worker optimizer parameters (string representation of a dict)', 64 | dest='worker_optimizer_params', default='{}') 65 | parser.add_argument('--sync-every', help='how often to sync weights with master', 66 | default=1, type=int, dest='sync_every') 67 | parser.add_argument('--easgd',help='use Elastic Averaging SGD',action='store_true') 68 | parser.add_argument('--elastic-force',help='beta parameter for EASGD',type=float,default=0.9) 69 | parser.add_argument('--elastic-lr',help='worker SGD learning rate for EASGD', 70 | type=float, default=1.0, dest='elastic_lr') 71 | parser.add_argument('--elastic-momentum',help='worker SGD momentum for EASGD', 72 | type=float, default=0, dest='elastic_momentum') 73 | parser.add_argument('--restore', help='pass a file to retore the variables from', default=None) 74 | 75 | args = parser.parse_args() 76 | model_name = os.path.basename(args.model_json).replace('.json','') 77 | 78 | with open(args.train_data) as train_list_file: 79 | train_list = [ s.strip() for s in train_list_file.readlines() ] 80 | with open(args.val_data) as val_list_file: 81 | val_list = [ s.strip() for s in val_list_file.readlines() ] 82 | 83 | comm = MPI.COMM_WORLD.Dup() 84 | 85 | model_weights = None 86 | 87 | if args.restore: 88 | args.restore = re.sub(r'\.algo$', '', args.restore) 89 | if not args.tf: 90 | model_weights = args.restore + '.model' 91 | 92 | # Theano is the default backend; use tensorflow if --tf is specified. 93 | # In the theano case it is necessary to specify the device before importing. 94 | device = get_device( comm, args.masters, gpu_limit=args.max_gpus, 95 | gpu_for_master=args.master_gpu) 96 | hide_device = True 97 | if args.tf: 98 | backend = 'tensorflow' 99 | if not args.optimizer.endswith("tf"): 100 | args.optimizer = args.optimizer + 'tf' 101 | if hide_device: 102 | os.environ['CUDA_VISIBLE_DEVICES'] = device[-1] if 'gpu' in device else '' 103 | print ('set to device',os.environ['CUDA_VISIBLE_DEVICES'],socket.gethostname()) 104 | else: 105 | backend = 'theano' 106 | os.environ['THEANO_FLAGS'] = "profile=%s,device=%s,floatX=float32" % (args.profile,device.replace('gpu','cuda')) 107 | os.environ['KERAS_BACKEND'] = backend 108 | 109 | print (backend) 110 | import_keras() 111 | import keras.backend as K 112 | if args.tf: 113 | gpu_options=K.tf.GPUOptions( 114 | per_process_gpu_memory_fraction=0.1, #was 0.0 115 | allow_growth = True, 116 | visible_device_list = device[-1] if 'gpu' in device else '') 117 | if hide_device: 118 | gpu_options=K.tf.GPUOptions( 119 | per_process_gpu_memory_fraction=0.0, 120 | allow_growth = True,) 121 | K.set_session( K.tf.Session( config=K.tf.ConfigProto( 122 | allow_soft_placement=True, 123 | #allow_soft_placement=False, 124 | #log_device_placement=True , # was false 125 | log_device_placement=False , # was false 126 | gpu_options=gpu_options 127 | ) ) ) 128 | 129 | if args.tf: 130 | #model_builder = ModelTensorFlow( comm, filename=args.model_json, device_name=device , weights=model_weights) 131 | from mpi_learn.train.GanModel import GANModelBuilder 132 | model_builder = GANModelBuilder( comm , device_name=device, tf= True, weights=model_weights) 133 | print ("Process {0} using device {1}".format(comm.Get_rank(), model_builder.device)) 134 | else: 135 | from mpi_learn.train.GanModel import GANModelBuilder 136 | model_builder = GANModelBuilder( comm , device_name=device, weights=model_weights) 137 | print ("Process {0} using device {1}".format(comm.Get_rank(),device)) 138 | os.environ['THEANO_FLAGS'] = "profile=%s,device=%s,floatX=float32" % (args.profile,device.replace('gpu','cuda')) 139 | # GPU ops need to be executed synchronously in order for profiling to make sense 140 | if args.profile: 141 | os.environ['CUDA_LAUNCH_BLOCKING'] = '1' 142 | 143 | 144 | data = H5Data( batch_size=args.batch, 145 | cache = args.caching_dir, 146 | preloading = args.data_preload, 147 | features_name=args.features_name, labels_name=args.labels_name ) 148 | # We initialize the Data object with the training data list 149 | # so that we can use it to count the number of training examples 150 | data.set_file_names( train_list ) 151 | validate_every = int(data.count_data()/args.batch ) 152 | 153 | # Some input arguments may be ignored depending on chosen algorithm 154 | if args.easgd: 155 | algo = Algo(None, loss=args.loss, validate_every=validate_every, 156 | mode='easgd', sync_every=args.sync_every, 157 | worker_optimizer=args.worker_optimizer, 158 | worker_optimizer_params=args.worker_optimizer_params, 159 | elastic_force=args.elastic_force/(comm.Get_size()-1), 160 | elastic_lr=args.elastic_lr, 161 | elastic_momentum=args.elastic_momentum) 162 | else: 163 | algo = Algo(args.optimizer, loss=args.loss, validate_every=validate_every, 164 | sync_every=args.sync_every, worker_optimizer=args.worker_optimizer, 165 | worker_optimizer_params=args.worker_optimizer_params) 166 | if args.restore: 167 | algo.load(args.restore) 168 | 169 | # Creating the MPIManager object causes all needed worker and master nodes to be created 170 | manager = MPIManager( comm=comm, data=data, algo=algo, model_builder=model_builder, 171 | num_epochs=args.epochs, train_list=train_list, val_list=val_list, 172 | num_masters=args.masters, num_processes=args.processes, 173 | synchronous=args.synchronous, 174 | verbose=args.verbose , monitor=args.monitor, 175 | early_stopping=args.early_stopping,target_metric=args.target_metric ) 176 | 177 | # Process 0 launches the training procedure 178 | if comm.Get_rank() == 0: 179 | print (algo) 180 | 181 | t_0 = time() 182 | histories = manager.process.train() 183 | delta_t = time() - t_0 184 | manager.free_comms() 185 | print ("Training finished in {0:.3f} seconds".format(delta_t)) 186 | 187 | json_name = '_'.join([model_name,args.trial_name,"history.json"]) 188 | manager.process.record_details(json_name, 189 | meta={"args":vars(args)}) 190 | print ("Wrote trial information to {0}".format(json_name)) 191 | -------------------------------------------------------------------------------- /mpi_learn/train/data.py: -------------------------------------------------------------------------------- 1 | ### Data class and associated helper methods 2 | 3 | import numpy as np 4 | import h5py 5 | import os 6 | import time 7 | from threading import Thread 8 | import itertools 9 | import logging 10 | 11 | class FilePreloader(Thread): 12 | def __init__(self, files_list, file_open,n_ahead=2): 13 | Thread.__init__(self) 14 | self.deamon = True 15 | self.n_concurrent = n_ahead 16 | self.files_list = files_list 17 | self.file_open = file_open 18 | self.loaded = {} ## a dict of the loaded objects 19 | self.should_stop = False 20 | 21 | def getFile(self, name): 22 | ## locks until the file is loaded, then return the handle 23 | return self.loaded.setdefault(name, self.file_open( name)) 24 | 25 | def closeFile(self,name): 26 | ## close the file and 27 | if name in self.loaded: 28 | self.loaded.pop(name).close() 29 | 30 | def run(self): 31 | while not self.files_list: 32 | time.sleep(1) 33 | for name in itertools.cycle(self.files_list): 34 | if self.should_stop: 35 | break 36 | n_there = len(self.loaded.keys()) 37 | if n_there< self.n_concurrent: 38 | logging.debug("preloading %s with %d",name,n_there) 39 | self.getFile( name ) 40 | else: 41 | time.sleep(5) 42 | 43 | def stop(self): 44 | logging.debug("Stopping FilePreloader") 45 | self.should_stop = True 46 | 47 | def data_class_getter(name): 48 | """Returns the specified Data class""" 49 | data_dict = { 50 | "H5Data":H5Data, 51 | } 52 | try: 53 | return data_dict[name] 54 | except KeyError: 55 | logging.warning("{0:s} is not a known Data class. Returning None...".format(name)) 56 | return None 57 | 58 | 59 | class Data(object): 60 | """Class providing an interface to the input training data. 61 | Derived classes should implement the load_data function. 62 | 63 | Attributes: 64 | file_names: list of data files to use for training 65 | batch_size: size of training batches 66 | """ 67 | 68 | def __init__(self, batch_size, cache=None, s3=None): 69 | """Stores the batch size and the names of the data files to be read. 70 | Params: 71 | batch_size: batch size for training 72 | """ 73 | self.batch_size = batch_size 74 | self.caching_directory = cache if cache else os.environ.get('GANINMEM','') 75 | self.use_s3 = s3 if s3 else os.environ.get('USES3','') 76 | self.fpl = None 77 | 78 | def set_caching_directory(self, cache): 79 | self.caching_directory = cache 80 | 81 | def set_file_names(self, file_names): 82 | ## hook to copy data in /dev/shm 83 | relocated = [] 84 | if self.caching_directory: 85 | goes_to = self.caching_directory 86 | goes_to += str(os.getpid()) 87 | os.system('mkdir %s '%goes_to) 88 | os.system('rm %s/* -f'%goes_to) ## clean first if anything 89 | for fn in file_names: 90 | relocate = goes_to+'/'+fn.split('/')[-1] 91 | if not os.path.isfile( relocate ): 92 | logging.info("copying %s to %s", fn , relocate) 93 | if (self.use_s3): 94 | if os.system('s3cmd get s3://gan-bucket/%s %s'%( fn ,relocate))==0: 95 | relocated.append( relocate ) 96 | else: 97 | logging.info("was unable to copy the file s3://ganbucket/%s to %s",fn,relocate) 98 | relocated.append( fn ) ## use the initial one 99 | else: 100 | if os.system('cp %s %s'%( fn ,relocate))==0: 101 | relocated.append( relocate ) 102 | else: 103 | logging.info("was enable to copy the file %s to %s",fn,relocate) 104 | relocated.append( fn ) ## use the initial one 105 | else: 106 | relocated.append( relocate ) 107 | 108 | self.file_names = relocated 109 | else: 110 | self.file_names = file_names 111 | 112 | if self.fpl: 113 | self.fpl.files_list = self.file_names 114 | 115 | def inf_generate_data(self): 116 | while True: 117 | try: 118 | for B in self.generate_data(): 119 | yield B 120 | except StopIteration: 121 | logging.warning("start over generator loop") 122 | 123 | def generate_data(self): 124 | """Yields batches of training data until none are left.""" 125 | leftovers = None 126 | for cur_file_name in self.file_names: 127 | cur_file_features, cur_file_labels = self.load_data(cur_file_name) 128 | # concatenate any leftover data from the previous file 129 | if leftovers is not None: 130 | cur_file_features = self.concat_data( leftovers[0], cur_file_features ) 131 | cur_file_labels = self.concat_data( leftovers[1], cur_file_labels ) 132 | leftovers = None 133 | num_in_file = self.get_num_samples( cur_file_features ) 134 | 135 | for cur_pos in range(0, num_in_file, self.batch_size): 136 | next_pos = cur_pos + self.batch_size 137 | if next_pos <= num_in_file: 138 | yield ( self.get_batch( cur_file_features, cur_pos, next_pos ), 139 | self.get_batch( cur_file_labels, cur_pos, next_pos ) ) 140 | else: 141 | leftovers = ( self.get_batch( cur_file_features, cur_pos, num_in_file ), 142 | self.get_batch( cur_file_labels, cur_pos, num_in_file ) ) 143 | 144 | def count_data(self): 145 | """Counts the number of data points across all files""" 146 | num_data = 0 147 | for cur_file_name in self.file_names: 148 | cur_file_features, cur_file_labels = self.load_data(cur_file_name) 149 | num_data += self.get_num_samples( cur_file_features ) 150 | return num_data 151 | 152 | def is_numpy_array(self, data): 153 | return isinstance( data, np.ndarray ) 154 | 155 | def get_batch(self, data, start_pos, end_pos): 156 | """Input: a numpy array or list of numpy arrays. 157 | Gets elements between start_pos and end_pos in each array""" 158 | if self.is_numpy_array(data): 159 | return data[start_pos:end_pos] 160 | else: 161 | return [ arr[start_pos:end_pos] for arr in data ] 162 | 163 | def concat_data(self, data1, data2): 164 | """Input: data1 as numpy array or list of numpy arrays. data2 in the same format. 165 | Returns: numpy array or list of arrays, in which each array in data1 has been 166 | concatenated with the corresponding array in data2""" 167 | if self.is_numpy_array(data1): 168 | return np.concatenate( (data1, data2) ) 169 | else: 170 | return [ self.concat_data( d1, d2 ) for d1,d2 in zip(data1,data2) ] 171 | 172 | def get_num_samples(self, data): 173 | """Input: dataset consisting of a numpy array or list of numpy arrays. 174 | Output: number of samples in the dataset""" 175 | if self.is_numpy_array(data): 176 | return len(data) 177 | else: 178 | return len(data[0]) 179 | 180 | def load_data(self, in_file): 181 | """Input: name of file from which the data should be loaded 182 | Returns: tuple (X,Y) where X and Y are numpy arrays containing features 183 | and labels, respectively, for all data in the file 184 | 185 | Not implemented in base class; derived classes should implement this function""" 186 | raise NotImplementedError 187 | 188 | class H5Data(Data): 189 | """Loads data stored in hdf5 files 190 | Attributes: 191 | features_name, labels_name: names of the datasets containing the features 192 | and labels, respectively 193 | """ 194 | def __init__(self, batch_size, 195 | cache=None, 196 | preloading=0, 197 | features_name='features', labels_name='labels'): 198 | """Initializes and stores names of feature and label datasets""" 199 | super(H5Data, self).__init__(batch_size,cache) 200 | self.features_name = features_name 201 | self.labels_name = labels_name 202 | ## initialize the data-preloader 203 | self.fpl = None 204 | if preloading: 205 | self.fpl = FilePreloader( [] , file_open = lambda n : h5py.File(n,'r'), n_ahead=preloading) 206 | self.fpl.start() 207 | 208 | 209 | def load_data(self, in_file_name): 210 | """Loads numpy arrays from H5 file. 211 | If the features/labels groups contain more than one dataset, 212 | we load them all, alphabetically by key.""" 213 | if self.fpl: 214 | h5_file = self.fpl.getFile( in_file_name ) 215 | else: 216 | h5_file = h5py.File( in_file_name, 'r' ) 217 | X = self.load_hdf5_data( h5_file[self.features_name] ) 218 | Y = self.load_hdf5_data( h5_file[self.labels_name] ) 219 | if self.fpl: 220 | self.fpl.closeFile( in_file_name ) 221 | else: 222 | h5_file.close() 223 | return X,Y 224 | 225 | def load_hdf5_data(self, data): 226 | """Returns a numpy array or (possibly nested) list of numpy arrays 227 | corresponding to the group structure of the input HDF5 data. 228 | If a group has more than one key, we give its datasets alphabetically by key""" 229 | if hasattr(data, 'keys'): 230 | out = [ self.load_hdf5_data( data[key] ) for key in sorted(data.keys()) ] 231 | else: 232 | out = data[:] 233 | return out 234 | 235 | def count_data(self): 236 | """This is faster than using the parent count_data 237 | because the datasets do not have to be loaded 238 | as numpy arrays""" 239 | num_data = 0 240 | for in_file_name in self.file_names: 241 | h5_file = h5py.File( in_file_name, 'r' ) 242 | X = h5_file[self.features_name] 243 | if hasattr(X, 'keys'): 244 | num_data += len(X[ X.keys()[0] ]) 245 | else: 246 | num_data += len(X) 247 | h5_file.close() 248 | return num_data 249 | 250 | def finalize(self): 251 | if self.fpl: 252 | self.fpl.stop() 253 | -------------------------------------------------------------------------------- /MPIDriver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | ### This script creates an MPIManager object and launches distributed training. 4 | 5 | import sys,os 6 | import numpy as np 7 | import argparse 8 | import json 9 | import re 10 | import logging 11 | 12 | from mpi4py import MPI 13 | from time import time,sleep 14 | 15 | from mpi_learn.mpi.manager import MPIManager, get_device 16 | from mpi_learn.train.algo import Algo 17 | from mpi_learn.train.data import H5Data 18 | from mpi_learn.train.model import ModelFromJson, ModelTensorFlow, ModelPytorch 19 | from mpi_learn.utils import import_keras 20 | from mpi_learn.train.trace import Trace 21 | from mpi_learn.logger import initialize_logger 22 | 23 | if __name__ == '__main__': 24 | parser = argparse.ArgumentParser() 25 | parser.add_argument('--verbose',help='display metrics for each training batch',action='store_true') 26 | parser.add_argument('--profile',help='profile theano code',action='store_true') 27 | parser.add_argument('--monitor',help='Monitor cpu and gpu utilization', action='store_true') 28 | parser.add_argument('--trace',help='Record timeline of activity', action='store_true') 29 | parser.add_argument('--tf', help='use tensorflow backend', action='store_true') 30 | parser.add_argument('--torch', help='use pytorch', action='store_true') 31 | parser.add_argument('--thread_validation', help='run a single process', action='store_true') 32 | 33 | # model arguments 34 | parser.add_argument('model', help='File containing model architecture (serialized in JSON/pickle, or provided in a .py file') 35 | parser.add_argument('--trial-name', help='descriptive name for trial', 36 | default='train', dest='trial_name') 37 | 38 | # training data arguments 39 | parser.add_argument('train_data', help='text file listing data inputs for training') 40 | parser.add_argument('val_data', help='text file listing data inputs for validation') 41 | parser.add_argument('--features-name', help='name of HDF5 dataset with input features', 42 | default='features', dest='features_name') 43 | parser.add_argument('--labels-name', help='name of HDF5 dataset with output labels', 44 | default='labels', dest='labels_name') 45 | parser.add_argument('--batch', help='batch size', default=100, type=int) 46 | parser.add_argument('--preload-data', help='Preload files as we read them', default=0, type=int, dest='data_preload') 47 | parser.add_argument('--cache-data', help='Cache the input files to a provided directory', default='', dest='caching_dir') 48 | 49 | # configuration of network topology 50 | parser.add_argument('--masters', help='number of master processes', default=1, type=int) 51 | parser.add_argument('--processes', help='number of processes per worker', default=1, type=int) 52 | parser.add_argument('--max-gpus', dest='max_gpus', help='max GPUs to use', 53 | type=int, default=-1) 54 | parser.add_argument('--master-gpu',help='master process should get a gpu', 55 | action='store_true', dest='master_gpu') 56 | parser.add_argument('--synchronous',help='run in synchronous mode',action='store_true') 57 | 58 | # configuration of training process 59 | parser.add_argument('--epochs', help='number of training epochs', default=1, type=int) 60 | parser.add_argument('--optimizer',help='optimizer for master to use',default='adam') 61 | parser.add_argument('--loss',help='loss function',default='binary_crossentropy') 62 | parser.add_argument('--early-stopping', default=None, 63 | dest='early_stopping', help='patience for early stopping') 64 | parser.add_argument('--target-metric', default=None, 65 | dest='target_metric', help='Passing configuration for a target metric') 66 | parser.add_argument('--worker-optimizer',help='optimizer for workers to use', 67 | dest='worker_optimizer', default='sgd') 68 | parser.add_argument('--worker-optimizer-params',help='worker optimizer parameters (string representation of a dict)', 69 | dest='worker_optimizer_params', default='{}') 70 | parser.add_argument('--sync-every', help='how often to sync weights with master', 71 | default=1, type=int, dest='sync_every') 72 | parser.add_argument('--mode',help='Mode of operation.' 73 | 'One of "sgd" (Stohastic Gradient Descent), "easgd" (Elastic Averaging SGD) or "gem" (Gradient Energy Matching)',default='sgd') 74 | parser.add_argument('--elastic-force',help='beta parameter for EASGD',type=float,default=0.9) 75 | parser.add_argument('--elastic-lr',help='worker SGD learning rate for EASGD', 76 | type=float, default=1.0, dest='elastic_lr') 77 | parser.add_argument('--elastic-momentum',help='worker SGD momentum for EASGD', 78 | type=float, default=0, dest='elastic_momentum') 79 | parser.add_argument('--gem-lr',help='learning rate for GEM',type=float,default=0.01, dest='gem_lr') 80 | parser.add_argument('--gem-momentum',help='momentum for GEM',type=float, default=0.9, dest='gem_momentum') 81 | parser.add_argument('--gem-kappa',help='Proxy amplification parameter for GEM',type=float, default=2.0, dest='gem_kappa') 82 | parser.add_argument('--restore', help='pass a file to retore the variables from', default=None) 83 | parser.add_argument('--checkpoint', help='Base name of the checkpointing file. If omitted no checkpointing will be done', default=None) 84 | parser.add_argument('--checkpoint-interval', help='Number of epochs between checkpoints', default=5, type=int, dest='checkpoint_interval') 85 | 86 | # logging configuration 87 | parser.add_argument('--log-file', default=None, dest='log_file', help='log file to write, in additon to output stream') 88 | parser.add_argument('--log-level', default='info', dest='log_level', help='log level (debug, info, warn, error)') 89 | 90 | args = parser.parse_args() 91 | 92 | initialize_logger(filename=args.log_file, file_level=args.log_level, stream_level=args.log_level) 93 | 94 | with open(args.train_data) as train_list_file: 95 | train_list = [ s.strip() for s in train_list_file.readlines() ] 96 | with open(args.val_data) as val_list_file: 97 | val_list = [ s.strip() for s in val_list_file.readlines() ] 98 | 99 | comm = MPI.COMM_WORLD.Dup() 100 | 101 | if args.trace: Trace.enable() 102 | 103 | model_weights = None 104 | 105 | if args.restore: 106 | args.restore = re.sub(r'\.algo$', '', args.restore) 107 | if os.path.isfile(args.restore + '.latest'): 108 | with open(args.restore + '.latest', 'r') as latest: 109 | args.restore = latest.read().splitlines()[-1] 110 | if not args.tf and os.path.isfile(args.restore + '.model'): 111 | model_weights = args.restore + '.model' 112 | if args.torch: 113 | model_weights += '_w' 114 | 115 | # Theano is the default backend; use tensorflow if --tf is specified. 116 | # In the theano case it is necessary to specify the device before importing. 117 | device = get_device( comm, args.masters, gpu_limit=args.max_gpus, 118 | gpu_for_master=args.master_gpu) 119 | hide_device = True 120 | if args.torch: 121 | logging.debug("Using pytorch") 122 | if not args.optimizer.endswith("torch"): 123 | args.optimizer = args.optimizer + 'torch' 124 | import torch 125 | if hide_device: 126 | os.environ['CUDA_VISIBLE_DEVICES'] = device[-1] if 'gpu' in device else '' 127 | logging.debug('set to device %s',os.environ['CUDA_VISIBLE_DEVICES']) 128 | else: 129 | if 'gpu' in device: 130 | torch.cuda.set_device(int(device[-1])) 131 | model_builder = ModelPytorch(comm, source=args.model, weights=model_weights, gpus=1 if 'gpu' in device else 0) 132 | else: 133 | if args.tf: 134 | logging.debug("Using TensorFlow") 135 | backend = 'tensorflow' 136 | if not args.optimizer.endswith("tf"): 137 | args.optimizer = args.optimizer + 'tf' 138 | if hide_device: 139 | os.environ['CUDA_VISIBLE_DEVICES'] = device[-1] if 'gpu' in device else '' 140 | logging.debug('set to device %s',os.environ['CUDA_VISIBLE_DEVICES']) 141 | else: 142 | logging.debug("Using Theano") 143 | backend = 'theano' 144 | os.environ['THEANO_FLAGS'] = "profile=%s,device=%s,floatX=float32" % (args.profile,device.replace('gpu','cuda')) 145 | os.environ['KERAS_BACKEND'] = backend 146 | 147 | import_keras() 148 | import keras.backend as K 149 | if args.tf: 150 | gpu_options=K.tf.GPUOptions( 151 | per_process_gpu_memory_fraction=0.1, #was 0.0 152 | allow_growth = True, 153 | visible_device_list = device[-1] if 'gpu' in device else '') 154 | if hide_device: 155 | gpu_options=K.tf.GPUOptions( 156 | per_process_gpu_memory_fraction=0.0, 157 | allow_growth = True,) 158 | K.set_session( K.tf.Session( config=K.tf.ConfigProto( 159 | allow_soft_placement=True, log_device_placement=False, 160 | gpu_options=gpu_options 161 | ) ) ) 162 | if args.tf: 163 | tf_device = device 164 | if hide_device: 165 | tf_device = 'gpu0' if 'gpu' in device else '' 166 | model_builder = ModelTensorFlow( comm, source=args.model, device_name=tf_device , weights=model_weights) 167 | logging.debug("Using device {}".format(model_builder.device)) 168 | else: 169 | model_builder = ModelFromJson( comm, args.model ,weights=model_weights) 170 | logging.debug("using device {}".format(device)) 171 | os.environ['THEANO_FLAGS'] = "profile=%s,device=%s,floatX=float32" % (args.profile,device.replace('gpu','cuda')) 172 | # GPU ops need to be executed synchronously in order for profiling to make sense 173 | if args.profile: 174 | os.environ['CUDA_LAUNCH_BLOCKING'] = '1' 175 | 176 | 177 | data = H5Data( batch_size=args.batch, 178 | cache = args.caching_dir, 179 | preloading = args.data_preload, 180 | features_name=args.features_name, labels_name=args.labels_name ) 181 | # We initialize the Data object with the training data list 182 | # so that we can use it to count the number of training examples 183 | data.set_file_names( train_list ) 184 | validate_every = int(data.count_data()/args.batch) 185 | 186 | # Some input arguments may be ignored depending on chosen algorithm 187 | if args.mode == 'easgd': 188 | algo = Algo(None, loss=args.loss, validate_every=validate_every, 189 | mode='easgd', sync_every=args.sync_every, 190 | worker_optimizer=args.worker_optimizer, 191 | worker_optimizer_params=args.worker_optimizer_params, 192 | elastic_force=args.elastic_force/(comm.Get_size()-1), 193 | elastic_lr=args.elastic_lr, 194 | elastic_momentum=args.elastic_momentum) 195 | elif args.mode == 'gem': 196 | algo = Algo('gem', loss=args.loss, validate_every=validate_every, 197 | mode='gem', sync_every=args.sync_every, 198 | worker_optimizer=args.worker_optimizer, 199 | worker_optimizer_params=args.worker_optimizer_params, 200 | learning_rate=args.gem_lr, momentum=args.gem_momentum, kappa=args.gem_kappa) 201 | else: 202 | algo = Algo(args.optimizer, loss=args.loss, validate_every=validate_every, 203 | sync_every=args.sync_every, worker_optimizer=args.worker_optimizer, 204 | worker_optimizer_params=args.worker_optimizer_params) 205 | if args.restore: 206 | algo.load(args.restore) 207 | 208 | # Creating the MPIManager object causes all needed worker and master nodes to be created 209 | manager = MPIManager( comm=comm, data=data, algo=algo, model_builder=model_builder, 210 | num_epochs=args.epochs, train_list=train_list, val_list=val_list, 211 | num_masters=args.masters, num_processes=args.processes, 212 | synchronous=args.synchronous, 213 | verbose=args.verbose, monitor=args.monitor, 214 | early_stopping=args.early_stopping, 215 | target_metric=args.target_metric, 216 | thread_validation = args.thread_validation, 217 | checkpoint=args.checkpoint, checkpoint_interval=args.checkpoint_interval) 218 | 219 | 220 | # Process 0 launches the training procedure 221 | if comm.Get_rank() == 0: 222 | logging.debug('Training configuration: %s', algo.get_config()) 223 | 224 | t_0 = time() 225 | histories = manager.process.train() 226 | delta_t = time() - t_0 227 | manager.free_comms() 228 | logging.info("Training finished in {0:.3f} seconds".format(delta_t)) 229 | 230 | if args.model.endswith('.py'): 231 | module = __import__(args.model.replace('.py','')) 232 | try: 233 | model_name = module.get_name() 234 | except: 235 | model_name = os.path.basename(args.model).replace('.py','') 236 | else: 237 | model_name = os.path.basename(args.model).replace('.json','') 238 | 239 | json_name = '_'.join([model_name,args.trial_name,"history.json"]) 240 | manager.process.record_details(json_name, 241 | meta={"args":vars(args)}) 242 | logging.info("Wrote trial information to {0}".format(json_name)) 243 | 244 | comm.barrier() 245 | logging.info("Terminating") 246 | if args.trace: Trace.collect(clean=True) 247 | -------------------------------------------------------------------------------- /mpi_learn/train/model.py: -------------------------------------------------------------------------------- 1 | ### ModelBuilder class and associated helper methods 2 | 3 | from mpi_learn.utils import load_model, get_device_name 4 | from .optimizer import OptimizerBuilder 5 | import numpy as np 6 | import copy 7 | import sys 8 | import six 9 | import logging 10 | 11 | def session(f): 12 | def wrapper(*args, **kwargs): 13 | self_obj = args[0] 14 | if hasattr(self_obj, 'session'): 15 | with self_obj.graph.as_default(): 16 | with self_obj.session.as_default(): 17 | return f(*args, **kwargs) 18 | else: 19 | return f(*args, **kwargs) 20 | return wrapper 21 | 22 | class MPIModel(object): 23 | """Class that abstract all details of the model 24 | """ 25 | def __init__(self, model=None, models=None): 26 | self.model = model 27 | self.models = models 28 | self.histories = {} 29 | if model and models: 30 | raise Exception("Cannot specify single and multiple models") 31 | 32 | @session 33 | def print_metrics(self, metrics): 34 | if self.model: 35 | names = self.model.metrics_names 36 | for name, metric in zip( names, metrics ): 37 | logging.info("{0}: {1:.3f}".format(name,metric)) 38 | else: 39 | for im,m in enumerate(self.models): 40 | names = m.metrics_names 41 | ametric = metrics[im,...] 42 | logging.info('model {0} {1}'.format( im ,m.name)) 43 | for name, metric in zip( names,ametric): 44 | logging.info("{0}: {1:.3f}".format(name,metric)) 45 | 46 | @session 47 | def get_logs(self, metrics, val=False): 48 | if self.model: 49 | if val: 50 | return { 'val_'+name:np.asscalar(metric) for name, metric in 51 | zip( self.model.metrics_names, metrics ) } 52 | else: 53 | return { name:np.asscalar(metric) for name, metric in 54 | zip( self.model.metrics_names, metrics ) } 55 | else: 56 | logs = [] 57 | for im,m in enumerate(self.models): 58 | ametrics = metrics[im,...] 59 | if val: 60 | logs.append({ 'val_'+name:np.asscalar(metric) for name, metric in 61 | zip(m.metrics_names, ametrics ) }) 62 | else: 63 | logs.append({ name:np.asscalar(metric) for name, metric in 64 | zip(m.metrics_names, ametrics ) }) 65 | return logs 66 | 67 | @session 68 | def update_history(self, items, arg_hist): 69 | if self.model: 70 | for m,v in items.items(): 71 | arg_hist.setdefault(m,[]).append(v) 72 | else: 73 | for im,(m,it) in enumerate(zip(self.models, items)): 74 | m_name = "model%s"%im 75 | try: 76 | m_name = m.name 77 | except: 78 | logging.warning("no name attr") 79 | for m,v in it.items(): 80 | arg_hist.setdefault(m_name,{}).setdefault(m,[]).append(v) 81 | self.histories = arg_hist 82 | 83 | @session 84 | def format_update(self): 85 | if self.model: 86 | return [ np.zeros( w.shape, dtype=np.float32 ) for w in self.model.get_weights() ] 87 | else: 88 | up = [] 89 | for m in self.models: 90 | up.append( [ np.zeros( w.shape, dtype=np.float32 ) for w in m.get_weights() ] ) 91 | return up 92 | 93 | @session 94 | def get_weights(self): 95 | if self.model: 96 | return self.model.get_weights() 97 | else: 98 | l_weights = [] 99 | for m in self.models: 100 | l_weights.append( m.get_weights() ) 101 | return l_weights 102 | 103 | @session 104 | def set_weights(self, w ): 105 | if self.model: 106 | self.model.set_weights( w ) 107 | else: 108 | for m,mw in zip(self.models, w ): 109 | m.set_weights( mw ) 110 | 111 | #def history(self): 112 | # if self.model: 113 | # return self.model.history.history 114 | # else: 115 | # return [m.history.history for m in self.models] 116 | 117 | #def set_history(self, h): 118 | # if self.model: 119 | # self.model.history = h() 120 | # else: 121 | # for m in self.models: 122 | # m.history = h() 123 | 124 | @session 125 | def compile(self, **args): 126 | if 'optimizer' in args and isinstance(args['optimizer'], OptimizerBuilder): 127 | opt_builder = args['optimizer'] 128 | else: 129 | opt_builder = None 130 | if self.model: 131 | if opt_builder: 132 | args['optimizer'] = opt_builder.build() 133 | self.model.compile( **args ) 134 | else: 135 | for m in self.models: 136 | if opt_builder: 137 | args['optimizer'] = opt_builder.build() 138 | m.compile( **args ) 139 | 140 | @session 141 | def train_on_batch(self, **args): 142 | if self.model: 143 | return np.asarray(self.model.train_on_batch( **args )) 144 | else: 145 | h = [] 146 | for m in self.models: 147 | h.append(m.train_on_batch( **args )) 148 | return np.asarray(h) 149 | 150 | @session 151 | def test_on_batch(self, **args): 152 | if self.model: 153 | return np.asarray(self.model.test_on_batch( **args )) 154 | else: 155 | h= [] 156 | for m in self.models: 157 | h.append(m.test_on_batch( **args )) 158 | return np.asarray(h) 159 | 160 | @session 161 | def figure_of_merit(self, **args): 162 | ## runs like predict trace, and provides a non differentiable figure of merit for hyper-opt 163 | ## can of course be the validation loss 164 | if self.model: 165 | ## return a default value from the validation history 166 | return (1.-self.histories['val_acc'][-1]) 167 | #return self.histories['val_loss'][-1] 168 | else: 169 | return 0. 170 | 171 | 172 | @session 173 | def save(self, *args,**kwargs): 174 | if self.model: 175 | self.model.save( *args, **kwargs ) 176 | else: 177 | for im,m in enumerate(self.models): 178 | fn = 'm%d_%s'%( im, args[0]) 179 | m.save( fn, **kwargs ) 180 | 181 | def close(self): 182 | if hasattr(self, 'session'): 183 | self.session.close() 184 | 185 | class MPITModel(MPIModel): 186 | """ 187 | adapter of a torch model to fit in the mpi_learn interface 188 | """ 189 | def __init__(self, model=None, gpus=0): 190 | MPIModel.__init__(self,model = model) 191 | self.gpus = gpus 192 | self.metrics_names = ["loss"] 193 | self.loss = None 194 | self.optimizer = None 195 | self.metrics = [] 196 | self.loss_functions = None 197 | 198 | if self.gpus>0: 199 | self.model = self.model.cuda() 200 | if self.gpus >1: 201 | import torch.nn as nn 202 | self.model = nn.DataParallel(self.model) 203 | setattr(self.model, 'metrics_names', self.metrics_names) 204 | 205 | def format_update(self): 206 | ws = self.get_weights() 207 | return [ np.zeros( w.shape, dtype=np.float32 ) for w in ws] 208 | 209 | def get_weights(self): 210 | if self.gpus > 0: 211 | return copy.deepcopy([i.data.cpu().numpy() for i in list(self.model.parameters())]) 212 | else: 213 | return copy.deepcopy([i.data.numpy() for i in list(self.model.parameters())]) 214 | 215 | def set_weights(self, weights=[]): 216 | import torch # Don't put it outside because it will break Tensorflow 217 | for i,weight in enumerate(weights): 218 | list(self.model.parameters())[i].data.copy_(torch.from_numpy(weight)) 219 | 220 | def compile(self, **kwargs): 221 | import torch.nn 222 | import torch.optim 223 | 224 | ### need to map the loss string into the relevant torch object 225 | self.loss = self._build_loss(kwargs['loss']) 226 | for metric in kwargs['metrics']: 227 | if metric.lower() == 'acc' or metric.lower() == 'accuracy': 228 | self.metrics_names.append('acc') 229 | ## we need a mapping of the kwargs into what is the optimizer that is getting used 230 | opt_builder = kwargs.get('optimizer') 231 | if opt_builder is None: 232 | self.optimizer = torch.optim.SGD(self.model.parameters(), 1.) 233 | else: 234 | self.optimizer = opt_builder.build_torch(self.model) 235 | 236 | def _build_loss(self, loss): 237 | import torch.nn 238 | if loss and loss.endswith('Loss'): 239 | loss = loss[:-4] 240 | lookup = { 241 | # Keras mapped losses 242 | 'categorical_crossentropy': torch.nn.CrossEntropyLoss, 243 | 'mean_squared_error' : torch.nn.MSELoss, 244 | 'mean_absolute_error' : torch.nn.L1Loss, 245 | # PyTorch losses 246 | 'L1': torch.nn.L1Loss, 247 | 'MSE': torch.nn.MSELoss, 248 | 'CrossEntropy': torch.nn.CrossEntropyLoss, 249 | #'CTC': torch.nn.CTCLoss, 250 | 'NLL': torch.nn.NLLLoss, 251 | 'PoissonNLL': torch.nn.PoissonNLLLoss, 252 | 'KLDiv': torch.nn.KLDivLoss, 253 | 'BCE': torch.nn.BCELoss, 254 | 'BCEWithLogits': torch.nn.BCEWithLogitsLoss, 255 | 'MarginRanking': torch.nn.MarginRankingLoss, 256 | 'HingeEmbedding': torch.nn.HingeEmbeddingLoss, 257 | 'MultiLabelMargin': torch.nn.MultiLabelMarginLoss, 258 | 'SmoothL1': torch.nn.SmoothL1Loss, 259 | 'SoftMargin': torch.nn.SoftMarginLoss, 260 | 'MultiLabelSoftMargin': torch.nn.MultiLabelSoftMarginLoss, 261 | 'CosineEmbedding': torch.nn.CosineEmbeddingLoss, 262 | 'MultiMargin': torch.nn.MultiMarginLoss, 263 | 'TripletMargin': torch.nn.TripletMarginLoss 264 | } 265 | if loss in lookup: 266 | return lookup[loss]() 267 | else: 268 | logger.warning("No loss mapping found, using CrossEntropyLoss") 269 | return torch.nn.CrossEntropyLoss() 270 | 271 | def _accuracy(self, output, target, topk=(1,)): 272 | """Computes the precision@k for the specified values of k""" 273 | maxk = max(topk) 274 | batch_size = target.size(0) 275 | _, pred = output.topk(maxk, 1, True, True) 276 | pred = pred.t() 277 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 278 | 279 | res = [] 280 | for k in topk: 281 | correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) 282 | res.append(correct_k.mul_(1. / batch_size)) 283 | return res 284 | def _convert_to_tensor(self, data ): 285 | import torch 286 | return torch.from_numpy(data) 287 | #if hasattr(data, 'keys'): 288 | # out = [torch.from_numpy(data[key]) for key in sorted(data.keys())] 289 | #else: 290 | # out = torch.from_numpy(data) 291 | #return out 292 | 293 | def train_on_batch(self, x=None, y=None, *args, **kwargs): 294 | '''Perform a single gradient update on a single batch of data. 295 | Attributes: 296 | x: Pytorch tensor of training data 297 | y: Pytorch tensor of target data 298 | 299 | Return: 300 | A list of scalar training loss and a metric specified in the compile method. 301 | ''' 302 | from torch.autograd import Variable 303 | x = self._convert_to_tensor(x) 304 | y = self._convert_to_tensor(y) 305 | self.model.train() 306 | self.optimizer.zero_grad() 307 | target = y.long().max(1)[1] # Pytorch doesn't need 1-hot encoded label. Only the indices of classes. 308 | #target = y.long() 309 | if self.gpus>0: 310 | x = x.cuda() 311 | target = target.cuda() 312 | x = Variable(x) 313 | pred = self.model.forward(x) 314 | loss = self.loss(pred, Variable(target)) 315 | loss.backward() 316 | self.optimizer.step() 317 | l_data = loss.data.numpy() if self.gpus == 0 else loss.data.cpu().numpy() 318 | self.metrics = [l_data] if l_data.shape==() else [l_data[0]] 319 | if 'acc' in self.metrics_names: # compute the accuracy 320 | acc = self._accuracy(pred.data, target, topk=(1,))[0] 321 | if self.gpus > 0: acc = acc.cpu() 322 | self.metrics.append(acc.numpy()[0]) 323 | return np.asarray(self.metrics) 324 | 325 | 326 | def test_on_batch(self, x=None, y=None, *args, **kwargs): 327 | '''Test the model on a single batch of samples. No gradient update is performed. 328 | Attributes: 329 | x: Pytorch tensor of test data 330 | y: Pytorch tensor of target data 331 | 332 | Return: 333 | A list of scalar training loss and a metric specified in the compile method. 334 | ''' 335 | from torch.autograd import Variable 336 | x = self._convert_to_tensor(x) 337 | y = self._convert_to_tensor(y) 338 | self.model.eval() 339 | target = y.long().max(1)[1] # Pytorch doesn't need 1-hot encoded label. Only the indices of classes. 340 | #target =y.long() 341 | if self.gpus > 0: 342 | x = x.cuda() 343 | target = target.cuda() 344 | pred = self.model.forward(Variable(x, volatile=True)) 345 | loss = self.loss(pred, Variable(target, volatile=True)) 346 | l_data = loss.data.numpy() if self.gpus == 0 else loss.data.cpu().numpy() 347 | self.metrics = [l_data] if l_data.shape==() else [l_data[0]] 348 | if 'acc' in self.metrics_names: # compute the accuracy 349 | acc = self._accuracy(pred.data, target, topk=(1,))[0] 350 | if self.gpus > 0: acc = acc.cpu() 351 | self.metrics.append(acc.numpy()[0]) 352 | return np.asarray(self.metrics) 353 | 354 | def save(self, *args,**kwargs): 355 | import torch 356 | weights_filename = args[0]+'_w' 357 | arch_filename = args[0] 358 | torch.save( self.model.state_dict(), weights_filename) 359 | torch.save( self.model, arch_filename) 360 | 361 | class ModelBuilder(object): 362 | """Class containing instructions for building neural net models. 363 | Derived classes should implement the build_model and get_backend_name 364 | functions. 365 | 366 | Attributes: 367 | comm: MPI communicator containing all running MPI processes 368 | """ 369 | 370 | def __init__(self, comm): 371 | """Arguments: 372 | comm: MPI communicator 373 | """ 374 | self.comm = comm 375 | 376 | def get_device_name(self, device): 377 | """Should return a device name under a desired convention""" 378 | return device 379 | 380 | def build_model(self): 381 | """Should return an uncompiled Keras model.""" 382 | raise NotImplementedError 383 | 384 | def get_backend_name(self): 385 | """Should return the name of backend framework.""" 386 | raise NotImplementedError 387 | 388 | class ModelFromJson(ModelBuilder): 389 | """ModelBuilder class that builds from model architecture specified 390 | in a JSON file. 391 | Attributes: 392 | filename: path to JSON file specifying model architecture 393 | """ 394 | 395 | def __init__(self, comm, filename=None, custom_objects={}, weights=None): 396 | self.filename = filename 397 | self.weights = weights 398 | self.custom_objects = custom_objects 399 | super(ModelFromJson, self).__init__(comm) 400 | 401 | def build_model(self, local_session=True): 402 | if type(self.filename) == list: 403 | models = [] 404 | for fn in self.filename: 405 | models.append(load_model(filename=fn)) 406 | return MPIModel(models = models) 407 | else: 408 | return MPIModel(model=load_model(filename=self.filename, custom_objects=self.custom_objects, weights_file=self.weights)) 409 | 410 | def get_backend_name(self): 411 | return 'keras' 412 | 413 | class ModelTensorFlow(ModelBuilder): 414 | """ModelBuilder class that builds from model architecture specified 415 | in a JSON file. Uses Tensorflow and builds the model on the 416 | specified GPU. 417 | Attributes: 418 | source: path to JSON file specifying model architecture 419 | or Keras model to be cloned 420 | device: name of the device to use (ex: "/gpu:2") 421 | """ 422 | 423 | def __init__(self, comm, source, device_name='cpu', 424 | custom_objects={}, weights=None): 425 | if isinstance(source, six.string_types): 426 | if source.endswith('.py'): 427 | module = __import__(source.replace('.py','')) 428 | self.model = module.get_model() 429 | self.filename = None 430 | else: 431 | self.filename = source 432 | self.model = None 433 | else: 434 | self.filename = None 435 | self.model = source 436 | self.weights = weights 437 | self.custom_objects = custom_objects 438 | self.device = self.get_device_name(device_name) 439 | super(ModelTensorFlow, self).__init__(comm) 440 | 441 | def get_device_name(self, device): 442 | """Returns a TF-style device identifier for the specified device. 443 | input: 'cpu' for CPU and 'gpuN' for the Nth GPU on the host""" 444 | if device == 'cpu': 445 | dev_num = 0 446 | dev_type = 'cpu' 447 | elif device.startswith('gpu'): 448 | try: 449 | dev_num = int(device[3:]) 450 | dev_type = 'gpu' 451 | except ValueError: 452 | logging.warning("GPU number could not be parsed from {}; using CPU".format(device)) 453 | dev_num = 0 454 | dev_type = 'cpu' 455 | else: 456 | logging.warning("Please specify 'cpu' or 'gpuN' for device name; using CPU") 457 | dev_num = 0 458 | dev_type = 'cpu' 459 | return get_device_name(dev_type, dev_num, backend='tensorflow') 460 | 461 | def build_model_aux(self): 462 | import keras.backend as K 463 | 464 | with K.tf.device(self.device): 465 | if type(self.filename) == list: 466 | models = [] 467 | self.weights = self.weights.split(',') if self.weights else [None]*len(self.filename) 468 | for fn,w in zip(self.filename, self.weights): 469 | models.append(load_model(filename=fn, weights_file=w)) 470 | return MPIModel(models = models) 471 | else: 472 | model = load_model(filename=self.filename, model=self.model, 473 | custom_objects=self.custom_objects, weights_file=self.weights) 474 | return MPIModel(model = model) 475 | 476 | 477 | def build_model(self, local_session = True): 478 | import keras.backend as K 479 | 480 | if local_session: 481 | graph = K.tf.Graph() 482 | session = K.tf.Session(graph=graph, config=K.tf.ConfigProto( 483 | allow_soft_placement=True, log_device_placement=False, 484 | gpu_options=K.tf.GPUOptions( 485 | per_process_gpu_memory_fraction=1./self.comm.Get_size()) ) ) 486 | 487 | with graph.as_default(): 488 | with session.as_default(): 489 | import keras.backend as K 490 | ret_model = self.build_model_aux() 491 | ret_model.session = session 492 | ret_model.graph = graph 493 | return ret_model 494 | else: 495 | K.set_session( K.tf.Session( config=K.tf.ConfigProto( 496 | allow_soft_placement=True, log_device_placement=False, 497 | gpu_options=K.tf.GPUOptions( 498 | per_process_gpu_memory_fraction=1./self.comm.Get_size()) ) ) ) 499 | return self.build_model_aux() 500 | 501 | def get_backend_name(self): 502 | return 'tensorflow' 503 | 504 | class ModelPytorch(ModelBuilder): 505 | def __init__(self, comm, source, 506 | weights = None, 507 | gpus=0): 508 | super(ModelPytorch,self).__init__(comm) 509 | if isinstance(source, six.string_types): 510 | if source.endswith('.py'): 511 | module = __import__(source.replace('.py','')) 512 | self.model = module.get_model() 513 | self.filename = None 514 | else: 515 | self.filename = source 516 | self.model = None 517 | else: 518 | self.filename = None 519 | self.model = source 520 | self.weights = weights 521 | self.gpus=gpus 522 | 523 | def build_model(self, local_session=True): 524 | import torch 525 | if self.filename is not None: 526 | model = torch.load(self.filename) 527 | elif self.model is not None: 528 | model = copy.deepcopy(self.model) 529 | if self.weights: 530 | wd = torch.load(self.weights) 531 | model.load_state_dict(wd) 532 | return MPITModel(model=model, gpus=self.gpus) 533 | 534 | def get_backend_name(self): 535 | return 'pytorch' 536 | 537 | -------------------------------------------------------------------------------- /mpi_learn/mpi/manager.py: -------------------------------------------------------------------------------- 1 | ### MPIManager class and associated functions 2 | 3 | from __future__ import division 4 | import math 5 | from mpi4py import MPI 6 | import numpy as np 7 | import time 8 | import json 9 | import logging 10 | 11 | from ..train.data import H5Data 12 | from ..utils import get_num_gpus 13 | 14 | def get_groups(comm, num_masters=1, num_processes=1): 15 | masters = list(range(0,num_masters)) # index 0 is the uber master, the other one asre sub-masters 16 | n_active_master = max(num_masters-1,1) 17 | groups = [set() for _ in range(n_active_master)] 18 | instances_ranks = list(range(num_masters, comm.Get_size(), num_processes)) 19 | processes = [None]*len(instances_ranks) 20 | for ir,i_rank in enumerate(instances_ranks): 21 | _,ig = divmod( ir, n_active_master ) 22 | groups[ig].add( i_rank ) 23 | groups[ig].add( masters[-1-ig] ) 24 | processes[ir] = list(range(i_rank,min(i_rank+num_processes, comm.Get_size()))) 25 | 26 | groups = [sorted(g) for g in groups] 27 | return masters, groups, processes 28 | 29 | def get_device(comm, num_masters=1, gpu_limit=-1, gpu_for_master=False): 30 | """Arguments: 31 | comm: MPI intracommunicator containing all processes 32 | num_masters: number of processes that will be assigned as masters 33 | gpu_limit: maximum number of gpus to use on one host 34 | gpu_for_master: whether master processes should be given a gpu 35 | Returns device name 'cpu' or 'gpuN' appropriate for use with theano""" 36 | def get_gpu_list(mem_lim = 2000): 37 | import gpustat 38 | stats = gpustat.GPUStatCollection.new_query() 39 | ids = list(map(lambda gpu: int(gpu.entry['index']), stats)) 40 | ratios = map(lambda gpu: float(gpu.entry['memory.used'])/float(gpu.entry['memory.total']), stats) 41 | #used = list(map(lambda gpu: float(gpu.entry['memory.used']), stats)) 42 | #unused_gpu = filter(lambda x: x[1] < 100.0, zip(ids, used)) 43 | free = list(map(lambda gpu: float(gpu.entry['memory.total'])-float(gpu.entry['memory.used']), stats)) 44 | unused_gpu = list(filter(lambda x: x[1] > mem_lim, zip(ids, free))) 45 | return [x[0] for x in unused_gpu] 46 | 47 | # Get the ranks of the other processes that share the same host 48 | # and determine which GPU to take on the host 49 | if gpu_limit==0: 50 | logging.info("required to not use gpu") 51 | dev = 'cpu' 52 | return dev 53 | 54 | rank = comm.Get_rank() 55 | host = MPI.Get_processor_name() 56 | hosts = comm.allgather(host) 57 | workers_sharing_host = [ i for i in range(comm.Get_size()) if hosts[i] == host ] 58 | if rank in workers_sharing_host: 59 | worker_id = workers_sharing_host.index( rank ) 60 | else: 61 | worker_id = -1 62 | 63 | for inode in range( comm.Get_size()): 64 | if rank == inode: 65 | gpu_list = get_gpu_list() 66 | if gpu_limit>=0: 67 | gpu_list = gpu_list[:gpu_limit] #limit the number of gpu 68 | if len(gpu_list) == 0: 69 | logging.info("No free GPU available. Using CPU instead.") 70 | dev = 'cpu' 71 | elif worker_id<0: 72 | ## alone on that machine 73 | logging.info("Alone on the node and taking the last gpu") 74 | dev = 'gpu%d' % (gpu_list[-1]) 75 | else: 76 | logging.debug("Sharing a node and taking on the gpu") 77 | dev = 'gpu%d' % (gpu_list[worker_id%len(gpu_list)]) 78 | logging.debug("rank %d can have %s",rank,dev) 79 | comm.Barrier() 80 | return dev 81 | 82 | 83 | class MPIManager(object): 84 | """The MPIManager class defines the topology of the MPI process network 85 | and creates master and worker objects for each process accordingly. 86 | 87 | Two configurations are available: 88 | 1) one master supervising other masters, each controlling some workers 89 | 2) one master and N-1 workers, where N is the number of MPI processes 90 | 91 | Attributes: 92 | process: the MPI worker or master object running on this process 93 | data: Data object containing information used for training/validation 94 | algo: Algo object containing training algorithm configuration options 95 | model_builder: ModelBuilder object 96 | num_masters: integer indicating the number of master processes. 97 | If num_masters > 1, an additional master will be created to supervise all masters. 98 | num_workers: integer indicating the number of worker processes 99 | worker_id: ID of worker node, used for indexing training data files 100 | num_epochs (integer): number of times to iterate over the training data 101 | comm_block: MPI intracommunicator used for message passing between master and workers. 102 | Process 0 is the master and the other processes are workers. 103 | comm_masters: MPI intracommunicator used for message passing between masters. 104 | (It will be None if there is only one master.) 105 | train_list: list of training data file names 106 | val_list: list of validation data file names 107 | is_master: boolean determining if this process is a master 108 | should_validate: boolean determining if this process should run training validation 109 | synchronous: whether or not to syncronize workers after each update 110 | verbose: whether to make MPIProcess objects verbose 111 | """ 112 | 113 | def __init__(self, comm, data, algo, model_builder, num_epochs, train_list, 114 | val_list, num_masters=1, num_processes=1, synchronous=False, 115 | verbose=False, custom_objects={}, early_stopping=None,target_metric=None, 116 | monitor=False, thread_validation=False, checkpoint=None, checkpoint_interval=5): 117 | """Create MPI communicator(s) needed for training, and create worker 118 | or master object as appropriate. 119 | 120 | Params: 121 | comm: MPI intracommunicator containing all processes 122 | data: Data object containing information used for training/validation 123 | algo: Algo object containing training algorithm configuration options 124 | model_builder: ModelBuilder object 125 | num_masters: number of master processes 126 | num_processes: number of processes that make up a worker/master (gpu allreduce) 127 | num_epochs: number of times to iterate over the training data 128 | train_list: list of training data files 129 | val_list: list of validation data files 130 | synchronous: true if masters should operate in synchronous mode 131 | verbose: whether to make MPIProcess objects verbose 132 | monitor: whether to monitor per-process resource (CPU/GPU) usage 133 | """ 134 | self.data = data 135 | self.algo = algo 136 | self.model_builder = model_builder 137 | self.num_masters = num_masters 138 | self.num_processes = num_processes 139 | if comm.Get_size() != 1: 140 | n_instances,remainder = divmod(comm.Get_size()-self.num_masters, self.num_processes) 141 | else: 142 | n_instances,remainder = 1,0 143 | if remainder: 144 | logging.info("The accounting is not correct, %d nodes are left behind",remainder) 145 | self.num_workers = n_instances # - self.num_masters 146 | self.worker_id = -1 147 | 148 | self.num_epochs = num_epochs 149 | self.train_list = train_list 150 | self.val_list = val_list 151 | self.synchronous = synchronous 152 | self.verbose = verbose 153 | self.monitor = monitor 154 | self.comm_block = None 155 | self.comm_masters = None 156 | self.comm_instance = None 157 | self.is_master = None 158 | self.should_validate = None 159 | self.custom_objects=custom_objects 160 | self.early_stopping = early_stopping 161 | self.target_metric = target_metric 162 | self.thread_validation = thread_validation 163 | self.checkpoint = checkpoint 164 | self.checkpoint_interval = checkpoint_interval 165 | self.make_comms(comm) 166 | 167 | def make_comms(self,comm): 168 | """Define the network topology by creating communicators linking masters with their slaves. 169 | Set comm_block to contain one master and all of its workers. 170 | Set comm_masters to contain all masters, including the "super-master" supervising them. 171 | Set comm_instance to contain the nodes contributing to the woker/master instance 172 | Define a master or worker object as appropriate for each process. 173 | If a worker is created, it is assigned some data files to train on. 174 | """ 175 | # For masters we let child_comm be the communicator used to message the node's 176 | # children, and parent_comm be that used to message the node's parents. 177 | 178 | self.parent_rank = 0 179 | self.is_master = False 180 | rank = comm.Get_rank() 181 | masters, groups, processes = get_groups( comm, self.num_masters, self.num_processes) 182 | 183 | logging.debug("masters %s", str(masters)) 184 | if len(masters)>1: 185 | self.comm_masters = comm.Create( comm.Get_group().Incl( masters )) 186 | if rank in masters: 187 | ## make the communicator for masters 188 | self.is_master = True 189 | if rank ==0 : 190 | self.should_validate = True 191 | 192 | 193 | logging.debug("groups %s", str(groups)) 194 | for igr,gr in enumerate(groups): 195 | if rank in gr: 196 | self.comm_block = comm.Split( igr ) 197 | break 198 | 199 | if self.comm_block is None: 200 | _ = comm.Split( len(groups)) 201 | 202 | if not self.is_master and self.comm_block: 203 | self.worker_id = self.comm_block.Get_rank() 204 | 205 | logging.debug("processes %s", str(processes)) 206 | for ipr,pr in enumerate(processes): 207 | if rank in pr and len(pr)>1: 208 | ## make the communicator for that process group 209 | self.comm_instance = comm.Split(ipr) 210 | break 211 | 212 | if not self.comm_instance: 213 | _ = comm.Split( len(processes) ) 214 | 215 | 216 | if self.comm_instance: 217 | ids = self.comm_instance.allgather( self.worker_id ) 218 | self.worker_id = list(filter(lambda i:i!=-1, ids))[0] 219 | 220 | logging.debug("master comm",self.comm_masters.Get_size() if self.comm_masters else "N/A") 221 | logging.debug("block comm",self.comm_block.Get_size() if self.comm_block else "N/A") 222 | logging.debug("instance comm",self.comm_instance.Get_size() if self.comm_instance else "N/A") 223 | 224 | # Case (1) 225 | if self.num_masters > 1: 226 | if self.is_master: 227 | parent_comm = self.comm_masters 228 | #if rank==0: 229 | if self.comm_masters.Get_rank() == 0: 230 | child_comm = self.comm_masters 231 | self.parent_rank = None 232 | else: 233 | child_comm = self.comm_block 234 | else: 235 | if self.is_master: 236 | parent_comm = self.comm_block 237 | child_comm = self.comm_block 238 | self.parent_rank = None 239 | 240 | # Process initialization 241 | if comm.Get_size() != 1: 242 | from .process import MPIWorker, MPIMaster 243 | if self.is_master: 244 | self.set_val_data() 245 | num_sync_workers = self.get_num_sync_workers(child_comm) 246 | self.process = MPIMaster( parent_comm, parent_rank=self.parent_rank, 247 | data=self.data, algo=self.algo, model_builder=self.model_builder, 248 | child_comm=child_comm, num_epochs=self.num_epochs, 249 | num_sync_workers=num_sync_workers, 250 | verbose=self.verbose, custom_objects=self.custom_objects, 251 | early_stopping = self.early_stopping, target_metric = self.target_metric, 252 | threaded_validation = self.thread_validation, 253 | checkpoint=self.checkpoint, checkpoint_interval=self.checkpoint_interval 254 | ) 255 | else: 256 | self.set_train_data() 257 | self.process = MPIWorker( data=self.data, algo=self.algo, 258 | model_builder=self.model_builder, 259 | process_comm = self.comm_instance, 260 | parent_comm=self.comm_block, 261 | parent_rank=self.parent_rank, 262 | num_epochs=self.num_epochs, 263 | verbose=self.verbose, 264 | monitor=self.monitor, 265 | custom_objects=self.custom_objects, 266 | checkpoint=self.checkpoint, checkpoint_interval=self.checkpoint_interval 267 | ) 268 | else: #Single Process mode 269 | from .single_process import MPISingleWorker 270 | self.set_val_data() 271 | self.set_train_data(use_all=True) 272 | self.process = MPISingleWorker(data=self.data, algo=self.algo, 273 | model_builder=self.model_builder, 274 | num_epochs=self.num_epochs, 275 | verbose=self.verbose, 276 | monitor=self.monitor, 277 | custom_objects=self.custom_objects, 278 | early_stopping = self.early_stopping, 279 | target_metric = self.target_metric, 280 | checkpoint=self.checkpoint, checkpoint_interval=self.checkpoint_interval) 281 | 282 | 283 | def figure_of_merit(self): 284 | ##if (self.comm_masters and self.comm_masters.Get_rank() == 0) or (self.comm_block.Get_rank() == 0): 285 | if self.parent_rank is None: 286 | ## only the uber-master returns a valid fom 287 | return self.process.model.figure_of_merit() 288 | else: 289 | return None 290 | 291 | def train(self): 292 | if self.parent_rank is None: 293 | ## start the uber master, as all over masters are self-started 294 | ## check MPIProcess.__init__ 295 | #if self.parent_rank is not None: 296 | # self.bcast_weights( self.parent_comm ) 297 | # self.train() 298 | return self.process.train() 299 | else: 300 | return None 301 | 302 | def get_num_sync_workers(self, comm): 303 | """Returns the number of workers the master should wait for 304 | at each training time step. Currently set to 95% of the 305 | number of workers (or 1 if running asynchronously). 306 | comm should be the master's child communicator.""" 307 | if self.synchronous: 308 | return int( math.ceil( 0.95 * (comm.Get_size() - 1) ) ) 309 | return 1 310 | 311 | def set_train_data(self, use_all=False): 312 | """Sets the training data files to be used by the current process""" 313 | logging.debug("number of workers %d",self.num_workers) 314 | logging.debug("number of files %d",len(self.train_list)) 315 | if use_all: 316 | files_for_this_worker = self.train_list 317 | else: 318 | files_for_this_worker = [fn for (i,fn) in enumerate(self.train_list) if i%self.num_workers==(self.worker_id-1)] 319 | 320 | logging.debug("Files for worker id{}, rank {}:{}".format(self.worker_id,self.comm_block.Get_rank() if self.comm_block else "N/A", 321 | self.comm_instance.Get_rank() if self.comm_instance else "N/A") 322 | ) 323 | if not files_for_this_worker: 324 | ## this is bad and needs to make it abort 325 | logging.debug("There are no files for training, this is a fatal issue") 326 | import sys 327 | sys.exit(13) 328 | 329 | for f in files_for_this_worker: 330 | logging.debug(" {0}".format(f)) 331 | self.data.set_file_names( files_for_this_worker ) 332 | 333 | def set_val_data(self): 334 | """Sets the validation data files to be used by the current process 335 | (only the master process has validation data associated with it)""" 336 | if not self.should_validate: return None 337 | logging.debug("Files for validation:" ) 338 | if not self.val_list: 339 | ## this is bad and needs to make it abort 340 | logging.error("There are no files for validating, this is a fatal issue") 341 | import sys 342 | sys.exit(13) 343 | 344 | for f in self.val_list: 345 | logging.debug(" {0}".format(f)) 346 | self.data.set_file_names( self.val_list ) 347 | 348 | # def make_comms_many(self,comm): 349 | # """Create MPI communicators# (Case 1): 350 | # Rank 0 of comm_block is# the master, other ranks are workers. 351 | # Rank 0 of comm_master i#s the super-master, other ranks are sub-masters. 352 | # Sets is_master and work#er_id attributes.""" 353 | # 354 | # # Create a communicator containing all processes except the first. 355 | # # Then divide that communicator into blocks, each with one master 356 | # ranks_excludefirstprocess = range(1,comm.Get_size()) 357 | # comm_excludefirstprocess = comm.Create( comm.Get_group().Incl( ranks_excludefirstprocess ) ) 358 | # if comm.Get_rank() in ranks_excludefirstprocess: 359 | # size_block = (comm.Get_size()-1) // (self.num_masters-1) 360 | # color_block = comm_excludefirstprocess.Get_rank() // size_block 361 | # self.comm_block = comm_excludefirstprocess.Split( color_block ) 362 | # comm_excludefirstprocess.Free() 363 | # else: 364 | # self.comm_block = None 365 | # # Create a communicator containing all masters 366 | # ranks_mastergroup = get_master_ranks( comm, self.num_masters ) 367 | # self.comm_masters = comm.Create( comm.Get_group().Incl(ranks_mastergroup) ) 368 | # self.is_master = ( comm.Get_rank() in ranks_mastergroup ) 369 | # self.should_validate = ( comm.Get_rank() == 0 ) 370 | # # Get the worker ID 371 | # ranks_workergroup = get_worker_ranks( comm, self.num_masters ) 372 | # if not self.is_master: 373 | # self.worker_id = ranks_workergroup.index( comm.Get_rank() ) 374 | # 375 | # def make_comm_single(self,comm): 376 | # """Create MPI communicator (Case 2): Rank 0 is master, all others are workers 377 | # Sets is_master and worker_id attributes""" 378 | # self.comm_block = comm 379 | # self.is_master = ( self.comm_block.Get_rank() == 0 ) 380 | # self.should_validate = self.is_master 381 | # if not self.is_master: 382 | # self.worker_id = self.comm_block.Get_rank() - 1 383 | # 384 | def free_comms(self): 385 | """Free active MPI communicators""" 386 | if self.process.process_comm is not None: 387 | logging.debug("holding on %d",self.process.process_comm.Get_size()) 388 | self.process.process_comm.Barrier() 389 | if self.model_builder.get_backend_name() == 'pytorch': 390 | import horovod.torch as hvd 391 | else: 392 | import horovod.keras as hvd 393 | logging.debug("Shutting down Horovod") 394 | hvd.shutdown() 395 | if self.comm_block is not None: 396 | self.comm_block.Free() 397 | if self.comm_masters is not None: 398 | self.comm_masters.Free() 399 | if self.comm_instance is not None: 400 | self.comm_instance.Free() 401 | 402 | 403 | class MPIKFoldManager(MPIManager): 404 | def __init__( self, NFolds, comm, data, algo, model_builder, num_epochs, train_list, 405 | val_list, num_masters=1, 406 | num_process=1, 407 | synchronous=False, 408 | verbose=False, custom_objects={}, 409 | early_stopping=None,target_metric=None, 410 | monitor=False, 411 | checkpoint=None, checkpoint_interval=5): 412 | self.comm_world = comm 413 | self.comm_fold = None 414 | self.fold_num = None 415 | if NFolds == 1: 416 | ## make a regular MPIManager 417 | self.manager = MPIManager(comm, data, algo, model_builder, num_epochs, train_list, 418 | val_list, num_masters,num_process, 419 | synchronous, 420 | verbose, custom_objects, 421 | early_stopping,target_metric, 422 | monitor, 423 | checkpoint=checkpoint, checkpoint_interval=checkpoint_interval) 424 | return 425 | 426 | if int(comm.Get_size() / float(NFolds))<=1: 427 | logging.warning("There is less than one master+one worker per fold, this isn't going to work") 428 | 429 | ## actually split further the work in folds 430 | rank = comm.Get_rank() 431 | fold_num = int(rank * NFolds / comm.Get_size()) 432 | self.fold_num = fold_num 433 | self.comm_fold = comm.Split(fold_num) 434 | logging.debug("For node {}, with block rank {}, send in fold {}".format(MPI.COMM_WORLD.Get_rank(), rank, fold_num)) 435 | self.manager = None 436 | 437 | if val_list: 438 | logging.warning("MPIKFoldManager would not expect to be given a validation list") 439 | all_files = train_list+val_list 440 | from sklearn.model_selection import KFold 441 | folding = KFold(n_splits = NFolds) 442 | folds = list(folding.split( all_files )) 443 | train, test = folds[ fold_num ] 444 | train_list_on_fold = list(np.asarray(all_files)[ train ]) 445 | val_list_on_fold = list(np.asarray(all_files)[ test ]) 446 | self.manager = MPIManager(self.comm_fold, data, algo, model_builder, num_epochs, train_list_on_fold, 447 | val_list_on_fold, num_masters,num_process, 448 | synchronous, 449 | verbose, custom_objects, 450 | early_stopping,target_metric,monitor, 451 | checkpoint=checkpoint, checkpoint_interval=checkpoint_interval) 452 | 453 | def free_comms(self): 454 | self.manager.free_comms() 455 | 456 | def train(self): 457 | self.manager.train() 458 | 459 | def figure_of_merit(self): 460 | fom = self.manager.figure_of_merit() 461 | if self.comm_fold is not None: 462 | foms = self.comm_world.allgather( fom ) 463 | # filter out the None values 464 | foms = list(filter( None, foms)) 465 | ## make the average and rms 466 | avg_fom = np.mean( foms ) 467 | std_fom = np.std( foms ) 468 | if self.comm_fold.Get_rank()==0: 469 | logging.info("Figure of merits over {} folds is {}+/-{}".format( len(foms), avg_fom, std_fom)) 470 | return avg_fom 471 | else: 472 | if fom is not None: 473 | logging.info("Figure of merits from single value {}".format( fom )) 474 | return fom 475 | -------------------------------------------------------------------------------- /mpi_learn/train/optimizer.py: -------------------------------------------------------------------------------- 1 | ### Optimizers used to update master process weights 2 | 3 | import numpy as np 4 | import copy 5 | import pickle 6 | import os 7 | import re 8 | import logging 9 | 10 | from ..utils import weights_from_shapes 11 | 12 | class Optimizer(object): 13 | """Base class for optimization algorithms. 14 | Currently doesn't do anything.""" 15 | 16 | def __init__(self): 17 | pass 18 | 19 | def reset(self): 20 | pass 21 | 22 | def apply_update(self, weights, gradient): 23 | raise NotImplementedError 24 | 25 | def save(self, fn = None): 26 | if fn is None: 27 | fn = 'master-opt-{}.algo'.format( os.getpid()) 28 | d= open(fn,'wb') 29 | pickle.dump(self, d) 30 | d.close() 31 | logging.info("Saved state to %s", fn) 32 | 33 | def load(self, fn = 'algo_.pkl'): 34 | if not fn.endswith('.algo'): 35 | fn = fn + '.algo' 36 | try: 37 | d = open(fn, 'rb') 38 | new_self = pickle.load( d ) 39 | d.close() 40 | except: 41 | new_self = None 42 | return new_self 43 | 44 | class MultiOptimizer(Optimizer): 45 | def __init__(self, opt, s): 46 | self.opts = [copy.deepcopy(opt) for i in range(s)] 47 | 48 | def reset(self): 49 | for o in self.opts: 50 | o.reset() 51 | 52 | def apply_update(self, weights, gradient): 53 | r = [] 54 | for o,w,g in zip(self.opts, weights, gradient): 55 | r.append( o.apply_update(w,g) ) 56 | return r 57 | 58 | class VanillaSGD(Optimizer): 59 | """Stochastic gradient descent with no extra frills. 60 | learning_rate: learning rate parameter for SGD""" 61 | 62 | def __init__(self, learning_rate=0.01): 63 | super(VanillaSGD, self).__init__() 64 | self.learning_rate = learning_rate 65 | 66 | def apply_update(self, weights, gradient): 67 | """Move weights in the direction of the gradient, by the amount of the 68 | learning rate.""" 69 | new_weights = [] 70 | for w, g in zip(weights, gradient): 71 | if type(w) == list: 72 | new_weights.append( [] ) 73 | for ww, gg in zip(w,g): 74 | new_weights[-1].append( np.subtract( ww, self.learning_rate*gg) ) 75 | else: 76 | new_weights.append(np.subtract(w, self.learning_rate*g)) 77 | return new_weights 78 | 79 | class RunningAverageOptimizer(Optimizer): 80 | """Base class for AdaDelta, Adam, and RMSProp optimizers. 81 | rho (tunable parameter): decay constant used to compute running parameter averages 82 | epsilon (tunable parameter): small constant used to prevent division by zero 83 | running_g2: running average of the squared gradient, where squaring is done componentwise""" 84 | 85 | def __init__(self, rho=0.95, epsilon=1e-8): 86 | super(RunningAverageOptimizer, self).__init__() 87 | self.init_rho = rho 88 | self.init_epsilon = epsilon 89 | RunningAverageOptimizer.reset(self) 90 | 91 | def reset(self): 92 | super(RunningAverageOptimizer, self).reset() 93 | self.epsilon = self.init_epsilon 94 | self.rho = self.init_rho 95 | self.running_g2 = None 96 | 97 | def running_average_square_np(self, previous, update): 98 | """Computes and returns the running average of the square of a numpy array. 99 | previous (numpy array): value of the running average in the previous step 100 | update (numpy array): amount of the update""" 101 | try: 102 | new_contribution = (1-self.rho) * np.square(update) 103 | old_contribution = self.rho * previous 104 | return new_contribution + old_contribution 105 | except Exception as e: 106 | logging.error("FAILED TO COMPUTE THE RUNNING AVG SQUARE due to %s",str(e)) 107 | logging.debug("rho %d",self.rho) 108 | logging.debug("min update %d",np.min(update)) 109 | logging.debug("max update %d",np.max(update)) 110 | logging.debug("min previous %d",np.min(previous)) 111 | logging.debug("max previous %d",np.max(previous)) 112 | return previous 113 | 114 | def running_average_square(self, previous, update): 115 | """Returns the running average of the square of a quantity. 116 | previous (list of numpy arrays): value of the running average in the previous step 117 | update (list of numpy arrays): amount of the update""" 118 | if previous == 0: 119 | previous = [ np.zeros_like(u) for u in update ] 120 | result = [] 121 | for prev, up in zip(previous, update): 122 | result.append( self.running_average_square_np( prev, up ) ) 123 | return result 124 | 125 | def sqrt_plus_epsilon(self, value): 126 | """Computes running RMS from the running average of squares. 127 | value: numpy array containing the running average of squares""" 128 | return np.sqrt( np.add(value, self.epsilon) ) 129 | 130 | class Adam(RunningAverageOptimizer): 131 | """Adam optimizer. 132 | Note that the beta_2 parameter is stored internally as 'rho' 133 | and "v" in the algorithm is called "running_g2" 134 | for consistency with the other running-average optimizers 135 | Attributes: 136 | learning_rate: base learning rate 137 | beta_1: decay rate for the first moment estimate 138 | m: running average of the first moment of the gradient 139 | t: time step 140 | """ 141 | 142 | def __init__(self, learning_rate=0.001, beta_1=0.9, beta_2=0.999, 143 | epsilon=1e-8): 144 | super(Adam, self).__init__(rho=beta_2, epsilon=epsilon) 145 | self.init_learning_rate = learning_rate 146 | self.init_beta_1 = beta_1 147 | Adam.reset(self) 148 | 149 | def reset(self): 150 | super(Adam, self).reset() 151 | self.beta_1 = self.init_beta_1 152 | self.learning_rate = self.init_learning_rate 153 | self.t = 0 154 | self.m = None 155 | 156 | def running_average_np(self, previous, update): 157 | """Computes and returns the running average of a numpy array. 158 | Parameters are the same as those for running_average_square_np""" 159 | try: 160 | new_contribution = (1-self.beta_1) * update 161 | old_contribution = self.beta_1 * previous 162 | return new_contribution + old_contribution 163 | except Exception as e: 164 | logging.error("FAILED TO UPDATE THE RUNNING AVERAGE due to %s",str(e)) 165 | logging.debug("beta_1 %d",self.beta_1) 166 | logging.debug("min update %d",np.min(update)) 167 | logging.debug("max update %d",np.max(update)) 168 | logging.debug("min previous %d",np.min(previous)) 169 | logging.debug("max previous %d",np.max(previous)) 170 | return previous 171 | 172 | 173 | def running_average(self, previous, update): 174 | """Returns the running average of the square of a quantity. 175 | Parameters are the same as those for running_average_square_np""" 176 | result = [] 177 | for prev, up in zip(previous, update): 178 | result.append( self.running_average_np( prev, up ) ) 179 | return result 180 | 181 | def apply_update(self, weights, gradient): 182 | """Update the running averages of the first and second moments 183 | of the gradient, and compute the update for this time step""" 184 | if self.running_g2 is None: 185 | self.running_g2 = [ np.zeros_like(g) for g in gradient ] 186 | if self.m is None: 187 | self.m = [ np.zeros_like(g) for g in gradient ] 188 | 189 | self.t += 1 190 | self.m = self.running_average( self.m, gradient ) 191 | self.running_g2 = self.running_average_square( self.running_g2, gradient ) 192 | alpha_t = self.learning_rate * (1 - self.rho**self.t)**(0.5) / (1 - self.beta_1**self.t) 193 | new_weights = [] 194 | for w, g, g2 in zip(weights, self.m, self.running_g2): 195 | try: 196 | update = alpha_t * g / ( np.sqrt(g2) + self.epsilon ) 197 | except Exception as e: 198 | logging.error("FAILED TO MAKE A WEIGHT UPDATE due to %s",str(e)) 199 | logging.debug("alpha_t %d",alpha_t) 200 | logging.debug("beta_1 %d",self.beta_1) 201 | logging.debug("t %d",self.t) 202 | logging.debug("learning rate %d",self.learning_rate) 203 | logging.debug("rho %d",self.rho) 204 | logging.debug("epsilon %d",self.epsilon) 205 | logging.debug("min gradient %d",np.min( g )) 206 | logging.debug("max gradient %d",np.max( g )) 207 | logging.debug("min gradient 2 %d",np.min( g2 )) 208 | logging.debug("max gradient 2 %d",np.max( g2 )) 209 | try: 210 | update = alpha_t * g / ( np.sqrt(g2) + self.epsilon ) 211 | try: 212 | new_weights.append( w - update ) 213 | except: 214 | logging.debug("no sub") 215 | except: 216 | try: 217 | update = g / ( np.sqrt(g2) + self.epsilon ) 218 | logging.debug("min b %d",np.min( update )) 219 | logging.debug("max b %d",np.max( update )) 220 | logging.debug("min |b| %d",np.min(np.fabs( update))) 221 | #update *= alpha_t 222 | except: 223 | try: 224 | update = 1./ ( np.sqrt(g2) + self.epsilon ) 225 | except: 226 | try: 227 | update = 1./ ( g2 + self.epsilon ) 228 | except: 229 | pass 230 | update = 0 231 | new_weights.append( w - update ) 232 | return new_weights 233 | 234 | class AdaDelta(RunningAverageOptimizer): 235 | """ADADELTA adaptive learning rate method. 236 | running_dx2: running average of squared parameter updates 237 | """ 238 | 239 | def __init__(self, rho=0.95, epsilon=1e-8): 240 | super(AdaDelta, self).__init__(rho, epsilon) 241 | AdaDelta.reset(self) 242 | 243 | def reset(self): 244 | super(AdaDelta, self).reset() 245 | self.running_dx2 = None 246 | 247 | def apply_update(self, weights, gradient): 248 | """Update the running averages of gradients and weight updates, 249 | and compute the Adadelta update for this step.""" 250 | if self.running_g2 is None: 251 | self.running_g2 = [ np.zeros_like(g) for g in gradient ] 252 | if self.running_dx2 is None: 253 | self.running_dx2 = [ np.zeros_like(g) for g in gradient ] 254 | 255 | self.running_g2 = self.running_average_square( self.running_g2, gradient ) 256 | new_weights = [] 257 | updates = [] 258 | for w, g, g2, dx2 in zip(weights, gradient, self.running_g2, self.running_dx2): 259 | update = np.multiply( np.divide( self.sqrt_plus_epsilon(dx2), self.sqrt_plus_epsilon(g2) ), g ) 260 | new_weights.append( np.subtract( w, update ) ) 261 | updates.append(update) 262 | self.running_dx2 = self.running_average_square( self.running_dx2, updates ) 263 | return new_weights 264 | 265 | class RMSProp(RunningAverageOptimizer): 266 | """RMSProp adaptive learning rate method. 267 | learning_rate: base learning rate, kept constant 268 | """ 269 | 270 | def __init__(self, rho=0.9, epsilon=1e-8, learning_rate=0.001): 271 | super(RMSProp, self).__init__(rho, epsilon) 272 | self.init_learning_rate = learning_rate 273 | self.reset() 274 | 275 | def reset(self): 276 | super(RMSProp, self).reset() 277 | self.learning_rate = self.init_learning_rate 278 | 279 | def apply_update(self, weights, gradient): 280 | """Update the running averages of gradients, 281 | and compute the update for this step.""" 282 | if self.running_g2 is None: 283 | self.running_g2 = [ np.zeros_like(g) for g in gradient ] 284 | 285 | self.running_g2 = self.running_average_square( self.running_g2, gradient ) 286 | new_weights = [] 287 | for w, g, g2 in zip(weights, gradient, self.running_g2): 288 | update = np.multiply( np.divide( self.learning_rate, self.sqrt_plus_epsilon(g2) ), g ) 289 | new_weights.append( np.subtract( w, update ) ) 290 | return new_weights 291 | 292 | class TFOptimizer(Optimizer): 293 | def __init__(self, **kwargs): 294 | for k, v in kwargs.items(): 295 | setattr(self, k, v) 296 | 297 | self.sess = None 298 | self.saver = None 299 | self.load_fn = None 300 | self.tf_optimizer = None 301 | 302 | self.reset() 303 | 304 | def reset(self): 305 | import tensorflow as tf 306 | 307 | if self.sess: 308 | self.sess.close() #free resources from previous execution 309 | 310 | self.sess = tf.Session() 311 | self.do_reset = True 312 | 313 | def save(self, fn='train_history'): 314 | fn = re.sub(r'\.algo$', '', fn) 315 | if not fn.startswith('./'): 316 | fn = './' + fn 317 | path = self.saver.save(self.sess, fn) 318 | logging.info("Saved state to %s", path) 319 | 320 | def setup_update(self, weights): 321 | import tensorflow as tf 322 | 323 | """Setup the tf computational graph. Should be run once for each model 324 | Receives the weights in order to know the shapes to use 325 | """ 326 | self.gradient = [ tf.placeholder(dtype=tf.float32, shape=w.shape, name="gradient") for w in weights ] 327 | self.weights = [ tf.Variable(w, dtype=tf.float32, name="weights_{}".format(i)) for i, w in enumerate(weights) ] 328 | 329 | var_list = zip(self.gradient, self.weights) 330 | 331 | self.tf_time = tf.Variable(1, dtype=tf.float32, name="time") 332 | 333 | self.optimizer_op = self.tf_optimizer.apply_gradients( 334 | grads_and_vars=var_list, 335 | global_step=self.tf_time, 336 | name='optimizer_op' # We may need to create uniqie name 337 | ) 338 | 339 | self.saver = tf.train.Saver(max_to_keep=None) 340 | 341 | if self.load_fn: 342 | self.saver.restore(self.sess, self.load_fn) 343 | else: 344 | self.sess.run(tf.global_variables_initializer()) 345 | 346 | def load(self, fn='train_history'): 347 | load_fn = re.sub(r'\.algo$', '', fn) 348 | if os.path.isfile(load_fn + '.meta'): 349 | self.load_fn = load_fn 350 | self.do_reset = True 351 | return self 352 | else: 353 | return None 354 | 355 | def apply_update(self, weights, gradient): 356 | if self.do_reset: 357 | self.setup_update(weights) 358 | self.do_reset = False 359 | 360 | gradient_dict = {placeholder : value for placeholder, value in zip(self.gradient, gradient)} 361 | 362 | #Trace.begin("tf_optimizer") 363 | self.sess.run(self.optimizer_op, feed_dict=gradient_dict) 364 | #Trace.end("tf_optimizer") 365 | 366 | #Trace.begin("tf_get_weights") 367 | res = self.sess.run(self.weights) 368 | #Trace.end("tf_get_weights") 369 | 370 | return res 371 | 372 | class GradientDescentTF(TFOptimizer): 373 | def __init__(self, learning_rate=0.01): 374 | super(GradientDescentTF, self).__init__(learning_rate=learning_rate) 375 | 376 | def setup_update(self, weights): 377 | import tensorflow as tf 378 | 379 | self.tf_optimizer = tf.train.GradientDescentOptimizer( 380 | learning_rate=self.learning_rate, 381 | use_locking=False, 382 | name='SGDMaster' # We may need to create uniqie name 383 | ) 384 | 385 | super(GradientDescentTF, self).setup_update(weights) 386 | 387 | class AdaDeltaTF(TFOptimizer): 388 | def __init__(self, learning_rate=0.001, rho=0.95, epsilon=1e-8): 389 | super(AdaDeltaTF, self).__init__(learning_rate=learning_rate, rho=rho, epsilon=epsilon) 390 | 391 | def setup_update(self, weights): 392 | import tensorflow as tf 393 | 394 | self.tf_optimizer = tf.train.AdadeltaOptimizer( 395 | learning_rate=self.learning_rate, 396 | rho=self.rho, 397 | epsilon=self.epsilon, 398 | use_locking=False, 399 | name='AdaDeltaMaster' # We may need to create uniqie name 400 | ) 401 | 402 | super(AdaDeltaTF, self).setup_update(weights) 403 | 404 | class RMSPropTF(TFOptimizer): 405 | def __init__(self, learning_rate=0.001, decay=0.9, momentum=0.0, epsilon=1e-10): 406 | super(RMSPropTF, self).__init__(learning_rate=learning_rate, decay=decay, 407 | momentum=momentum, epsilon=epsilon) 408 | 409 | def setup_update(self, weights): 410 | import tensorflow as tf 411 | 412 | self.tf_optimizer = tf.train.RMSPropOptimizer( 413 | learning_rate=self.learning_rate, 414 | decay=self.decay, 415 | momentum=self.momentum, 416 | epsilon=self.epsilon, 417 | use_locking=False, 418 | name='RMSPropMaster' # We may need to create uniqie name 419 | ) 420 | 421 | super(RMSPropTF, self).setup_update(weights) 422 | 423 | class AdamTF(TFOptimizer): 424 | def __init__(self, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8): 425 | super(AdamTF, self).__init__(learning_rate=learning_rate, 426 | beta_1=beta_1, beta_2=beta_2, epsilon=epsilon) 427 | 428 | def setup_update(self, weights): 429 | import tensorflow as tf 430 | 431 | self.tf_optimizer = tf.train.AdamOptimizer( 432 | learning_rate=self.learning_rate, 433 | beta1=self.beta_1, 434 | beta2=self.beta_2, 435 | epsilon=self.epsilon, 436 | use_locking=False, 437 | name='AdamMaster' # We may need to create uniqie name 438 | ) 439 | 440 | super(AdamTF, self).setup_update(weights) 441 | 442 | class TorchOptimizer(Optimizer): 443 | def __init__(self, **kwargs): 444 | for k, v in kwargs.items(): 445 | setattr(self, k, v) 446 | 447 | self.parameters = None 448 | self.torch_optimizer = None 449 | self.state = None 450 | 451 | self.reset() 452 | 453 | def reset(self): 454 | self.do_reset = True 455 | 456 | def apply_update(self, weights, gradient): 457 | import torch 458 | if self.do_reset: 459 | self.setup_update(weights) 460 | if self.state is not None: 461 | self.torch_optimizer.load_state_dict(self.state) 462 | self.do_reset = False 463 | 464 | for p, w, g in zip (self.parameters, weights, gradient): 465 | p.data.copy_(torch.from_numpy(w)) 466 | p.grad.data.copy_(torch.from_numpy(g)) 467 | 468 | self.torch_optimizer.step() 469 | return [i.data.cpu().numpy() for i in list(self.parameters)] 470 | 471 | def setup_update(self, weights): 472 | import torch 473 | if self.parameters is not None: 474 | for p in self.parameters: 475 | del p 476 | else: 477 | self.parameters = [None] * len(weights) 478 | for i, w in enumerate(weights): 479 | p = torch.from_numpy(w).cuda() 480 | g = torch.from_numpy(w).cuda() 481 | var = torch.autograd.Variable(p, requires_grad=True) 482 | var.grad = torch.autograd.Variable(g) 483 | self.parameters[i] = var 484 | 485 | def save(self, fn=None): 486 | if fn is None: 487 | fn = 'master-opt-{}.algo'.format( os.getpid()) 488 | 489 | state = self.torch_optimizer.state_dict() 490 | with open(fn, 'wb') as out_file: 491 | pickle.dump(state, out_file) 492 | logging.info("Saved state to %s", fn) 493 | 494 | def load(self, fn = 'algo_.pkl'): 495 | if not fn.endswith('.algo'): 496 | fn = fn + '.algo' 497 | with open(fn, 'rb') as in_file: 498 | self.state = pickle.load(in_file) 499 | return self 500 | 501 | class SGDTorch(TorchOptimizer): 502 | def __init__(self, lr=0.01, momentum=0, dampening=0, weight_decay=0, nesterov=False): 503 | super(SGDTorch, self).__init__(lr=lr, momentum=momentum, 504 | dampening=dampening, weight_decay=weight_decay, nesterov=nesterov) 505 | 506 | def setup_update(self, weights): 507 | super(SGDTorch, self).setup_update(weights) 508 | import torch.optim as topt 509 | self.torch_optimizer = topt.SGD(self.parameters, self.lr, self.momentum, self.dampening, 510 | self.weight_decay, self.nesterov) 511 | 512 | class AdaDeltaTorch(TorchOptimizer): 513 | def __init__(self, lr=1.0, rho=0.9, eps=1e-06, weight_decay=0): 514 | super(AdaDeltaTorch, self).__init__(lr=lr, rho=rho, eps=eps, weight_decay=weight_decay) 515 | 516 | def setup_update(self, weights): 517 | super(AdaDeltaTorch, self).setup_update(weights) 518 | import torch.optim as topt 519 | self.torch_optimizer = topt.Adadelta(self.parameters, self.lr, self.rho, self.eps, self.weight_decay) 520 | 521 | class RMSPropTorch(TorchOptimizer): 522 | def __init__(self, lr=0.01, alpha=0.99, eps=1e-08, weight_decay=0, momentum=0, centered=False): 523 | super(RMSPropTorch, self).__init__(lr=lr, alpha=alpha, eps=eps, weight_decay=weight_decay, 524 | momentum=momentum, centered=centered) 525 | 526 | def setup_update(self, weights): 527 | super(RMSPropTorch, self).setup_update(weights) 528 | import torch.optim as topt 529 | self.torch_optimizer = topt.RMSprop(self.parameters, self.lr, self.alpha, self.eps, 530 | self.weight_decay, self.momentum, self.centered) 531 | 532 | class AdamTorch(TorchOptimizer): 533 | def __init__(self, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0): 534 | super(AdamTorch, self).__init__(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) 535 | 536 | def setup_update(self, weights): 537 | super(AdamTorch, self).setup_update(weights) 538 | import torch.optim as topt 539 | self.torch_optimizer = topt.Adam(self.parameters, self.lr, self.betas, self.eps, 540 | self.weight_decay) 541 | 542 | class GEM(Optimizer): 543 | """GEM optimizer 544 | learning_rate: base learning rate, kept constant 545 | momentum: momentum term, constant 546 | kappa: Proxy amplification. Experimental results show 2 is a good value. 547 | """ 548 | 549 | def __init__(self, learning_rate=0.01, momentum=0.9, kappa=1.0): 550 | super(GEM, self).__init__() 551 | self.learning_rate = learning_rate 552 | self.momentum = momentum 553 | self.kappa = kappa 554 | self.epsilon = 10e-13 555 | 556 | self.central_variable_moment = None 557 | self.stale = None 558 | self.moment = None 559 | 560 | self.tensors_initialized = False 561 | 562 | def init_tensors(self, weights): 563 | if not self.tensors_initialized: 564 | self.central_variable_moment = [ np.zeros_like(w) for w in weights ] 565 | self.stale = [ np.zeros_like(w) for w in weights ] 566 | self.moment = [ np.zeros_like(w) for w in weights ] 567 | 568 | self.tensors_initialized = True 569 | 570 | def begin_compute_update(self, cur_weights, new_weights): 571 | self.init_tensors(cur_weights) 572 | 573 | update = [] 574 | 575 | for idx, (cur_w, new_w) in enumerate(zip(cur_weights, new_weights)): 576 | update.append( np.subtract( cur_w, new_w )) 577 | update[idx] *= -self.learning_rate 578 | # Update the states with the current gradient. 579 | self.moment[idx] *= self.momentum 580 | self.moment[idx] += update[idx] 581 | 582 | return update 583 | 584 | def gradient_energy_matching(self, gradient): 585 | Pi = [] # Pi tensors for all parameters. 586 | 587 | for idx, g in enumerate(gradient): 588 | proxy = self.kappa * np.abs(self.moment[idx]) 589 | central_variable = np.abs(self.central_variable_moment[idx]) 590 | update = np.abs(g + self.epsilon) 591 | pi = (proxy - central_variable) / update 592 | np.clip(pi, 0., 5., out=pi) # For numerical stability. 593 | Pi.append(pi) 594 | 595 | return Pi 596 | 597 | def compute_update(self, weights, gradient): 598 | for idx, w in enumerate(weights): 599 | self.central_variable_moment[idx] = (w - self.stale[idx]) 600 | self.stale[idx] = np.copy(w) 601 | 602 | update = [] 603 | 604 | pi = self.gradient_energy_matching(gradient) 605 | # Apply the scalars to the update. 606 | for idx, g in enumerate(gradient): 607 | update.append(np.multiply(g, pi[idx])) 608 | 609 | return update 610 | 611 | def apply_update(self, weights, update): 612 | """Add the update to the weights.""" 613 | new_weights = [] 614 | for w, u in zip(weights, update): 615 | new_weights.append(np.add(w, u)) 616 | return new_weights 617 | 618 | def get_optimizer(name): 619 | """Get optimizer class by string identifier""" 620 | lookup = { 621 | # Native optimizers 622 | 'sgd': VanillaSGD, 623 | 'adadelta': AdaDelta, 624 | 'rmsprop': RMSProp, 625 | 'adam': Adam, 626 | 'gem': GEM, 627 | # Wrappers around TF's optimizers 628 | 'sgdtf': GradientDescentTF, 629 | 'adadeltatf': AdaDeltaTF, 630 | 'rmsproptf': RMSPropTF, 631 | 'adamtf': AdamTF, 632 | # Wrappers arount Torch's optimizers 633 | 'sgdtorch': SGDTorch, 634 | 'adadeltatorch': AdaDeltaTorch, 635 | 'rmsproptorch': RMSPropTorch, 636 | 'adamtorch': AdamTorch, 637 | } 638 | return lookup[name] 639 | 640 | class OptimizerBuilder(object): 641 | """Builds a new Keras or Torch optimizer and optionally wraps it in horovod DistributedOptimizer.""" 642 | 643 | def __init__(self, name, config=None, horovod_wrapper=False): 644 | self.name = name 645 | self.config = config 646 | if self.config is None: 647 | self.config = {} 648 | if self.name == 'sgd' and 'lr' not in self.config: 649 | logging.warning("Learning rate for SGD not set, using 1.0.") 650 | self.config['lr'] = 1. 651 | self.horovod_wrapper = horovod_wrapper 652 | 653 | def build(self): 654 | from keras.optimizers import deserialize 655 | opt_config = {'class_name': self.name, 'config': self.config} 656 | opt = deserialize(opt_config) 657 | if self.horovod_wrapper: 658 | import horovod.keras as hvd 659 | if hasattr(opt, 'lr'): 660 | opt.lr *= hvd.size() 661 | opt = hvd.DistributedOptimizer(opt) 662 | return opt 663 | 664 | def build_torch(self, model): 665 | import torch 666 | lookup = { 667 | 'sgd': torch.optim.SGD, 668 | 'adadelta': torch.optim.Adadelta, 669 | 'rmsprop': torch.optim.RMSprop, 670 | 'adam': torch.optim.Adam 671 | } 672 | if self.name not in lookup: 673 | logging.warning("No optimizer '{}' found, using SGD instead".format(self.name)) 674 | self.name = 'sgd' 675 | opt = lookup[self.name](model.parameters(), **self.config) 676 | if self.horovod_wrapper: 677 | import horovod.torch as hvd 678 | opt = hvd.DistributedOptimizer(opt, named_parameters=model.named_parameters()) 679 | return opt 680 | -------------------------------------------------------------------------------- /License.md: -------------------------------------------------------------------------------- 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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | --------------------------------------------------------------------------------