Package: gloro
gloroLibrary for training provably-robust neural networks.This repository implements the method described in thispaper(appearing in ICML 2021), and is maintained by the authors, Klas Leino, Zifan Wang, and Matt Fredrikson. If you use this code, please use the following citation:@INPROCEEDINGS{leino21gloro,title={Globally-Robust Neural Networks},author={Klas Leino and Zifan Wang and Matt Fredrikson},booktitle={International Conference on Machine Learning (ICML)},year={2021},}Thegloro/relaxationsdirectory implements the extensions described in thispaper(appearing in NIPS 2021). If you use code from this directory, please additionally cite:@INPROCEEDINGS{leino2021relaxing,title={Relaxing Local Robustness},author={Klas Leino and Matt Fredrikson},booktitle={Neural Information Processing Systems (NIPS)},year={2021}}Best ResultsFor quick reference, we include our current best VRA (verified-robust accuracy) results here (these are more up-to-date and may surpass the results reported in the original paper). These results currently represent the state-of-the-art for deterministic L2 robustness certification. Seetoolsfor scripts to reproduce these results.datasetradiusarchitectureVRAMNIST0.32C2F0.957MNIST1.584C3F0.628CIFAR-100.1416C2F0.600Tiny-Imagenet0.1418C2F0.224ResourcesFor more on the theory behind GloRo Nets, check out ourblog postfor a high-level introduction, or read ouroriginal paperfor the technical details and proofs.
For interactive examples of this library in action, see our notebooks ontraining GloRo Netsandusing relaxed robustness.InstallationSimply install via pip:pip install gloroAlternatively, you can install from the source repository:Clone therepositoryand change into its root directory.Install from source viapip install -e .UsageExamplesExample training scripts can be found in thetrainingdirectory undertoolsConstructing GloRo NetsTheGloroNetclass subclassestf.keras.models.Model.
It can be built similarly to a keras model, except that it takes an additional parameter,epsilon, which specifies the robustness radius certified by the GloroNet.
For example:fromgloroimportGloroNetx=Input(5)z=Dense(6)(x)z=Activation('relu')(z)z=Dense(7)(z)z=Activation('relu')(z)y=Dense(3)(z)gloronet=GloroNet(x,y,epsilon=0.5)AGloroNetcan also be constructed from an existing model.
The model is assumed to havelogitoutputs (i.e., there is no softmax at the last layer).
For example:fromgloroimportGloroNetx=Input(5)z=Dense(6)(x)z=Activation('relu')(z)z=Dense(7)(z)z=Activation('relu')(z)y=Dense(3)(z)f=Model(x,y)gloronet=GloroNet(model=f,epsilon=0.5)Training GloRo NetsGloroNetmodels can be trained similarly to a standard KerasModelusing thefitmethod.
Thegloro.trainingpackage provides several useful modules for training GloRo Nets.
An example of training aGloroNetmodel is given below:fromgloro.training.callbacksimportUpdatePowerIteratesfromgloro.training.lossesimportCrossentropyfromgloro.training.metricsimportclean_accfromgloro.training.metricsimportvragloronet.compile(optimizer='adam',# This is the same as standard categorical crossentropy, except that (1) it# assumes it is operating on logits rather than probits, and (2) it adds an# extra column of zeros to the true labels.loss=Crossentropy(),metrics=[# As the name suggests, this calculates the clean accuracy of the# GloRo Net.clean_acc,# This is the same as Keras' 'acc' metric, but it is named to indicate# what it conceptually represents.vra,])gloronet.fit(X,Y,epochs=10,batch_size=16,callbacks=[# You should typically include this callback when training a `GloroNet`# model. This allows the model to maintain the state of the power# method iterates over training, and ensures that the computed# Lipschitz constant has converged prior to the start of each epoch and# at the end of training. When calling `fit` on a `GloroNet`, this is# included by default, but it can also be added explicitly, like in# this example, or it can be disabled by passing# `update_iterates=False` to `fit`.UpdatePowerIterates(),])Thecompilemethod is set up to also accept string shorthands for the loss and metrics, so the above code can be written more concisely and with fewer imports:gloronet.compile(optimizer='adam',loss='crossentropy',metrics=['clean_acc','vra'])gloronet.fit(X,Y,epochs=10,batch_size=16)Seegloro.training.losses.getfor the available loss shorthands.GloRo Nets can also be trained using TRADES loss.
TheTradesloss function takes a parameter,lam, that represents the weight given to the robust part of the objective.
An example is shown below.fromgloro.training.callbacksimportTradesSchedulerfromgloro.training.lossesimportTradesfromgloro.training.metricsimportclean_accfromgloro.training.metricsimportvragloronet.compile(optimizer='adam',loss=Trades(2.),metrics=[clean_acc,vra,])gloronet.fit(X,Y,epochs=10,batch_size=16,callbacks=[# It is often useful to begin with a small TRADES parameter and# increase it over time so that the GloRo Net learns to make accurate# predictions in addition to robust ones.TradesScheduler('linear')])Scheduler CallbacksThegloro.trainingpackage also provides several useful callbacks for scheduling the learning rate, TRADES parameter, etc., during training.
Seegloro.training.callbacksfor the available scheduling callbacks, andgloro.training.schedulesfor the available schedule shorthands.More about theGloroNetClassSaving and LoadingGloroNetmodels can be saved using the standard Keras model serialization API; however, to load a GloroNet,GloroNet.load_modelshould be used instead ofkeras.models.load_model.
For example:fromgloroimportGloroNet# The `gloro` library saves models with a '.gloronet' extension. This file# contains the underlying model instrumented by the GloRo Net, as well as# metadata associated with the `GloroNet` object.gloronet.save('my_model.gloronet')loaded_gloronet=GloroNet.load_model('my_model.gloronet')GloroNetProperties and MethodsTheGloronetclass provides some properties and methods that may be useful.
These properties are described below.epsilonThe robustness radius certified by this GloRo Net. This property is settable, so it can be changed to certify a different robustness radius.fThe underlying model instrumented by the GloRo Net. This property is read-only.lipschitz_constant()Gives the Lipschitz constant of for each pair of classes. The value in the diagonal is-1to signify that this value should be ignored.predict_clean(*args, **kwargs)Gets the predictions without the added bottom class.freeze_lipschitz_constant()Converges the power-method iterates and then hard-codes the Lipschitz constant such that it no longer needs to be computed from the model parameters. The frozen model will make more efficient predictions, but it can no longer be trained.refresh_iterates()Refreshes and converges the power-method iterates. This should be called before test-time certification. If the model was trained with theUpdatePowerIteratescallback, this will have been called automatically at the end of training.Main ContributersKlas LeinoZifan WangMatt Fredrikson