PrivacyRaven: Privacy Testing for Deep Learning

repository·master·Indexed 42 days ago

https://github.com/trailofbits/privacyraven

A framework-agnostic privacy testing library for deep learning systems designed to evaluate susceptibility to attacks such as model extraction and membership inference. It provides tools for running CopyCat and CloudLeak attacks, custom synthesizer registration, and fidelity measurement via label agreement. Version 0.1.0.

Tokens
10.5K
Snippets
34
Records
38
Agent score
52%

What's inside PrivacyRaven

  1. How PrivacyRaven attacks work

    master

    PrivacyRaven partitions each attack into multiple customizable and optimizable phases. It provides several interfaces:

    1. Core Interface: The fundamental interface used to build attacks.
    2. Wrappers: Pre-configured attack settings based on existing literature.
    3. Run-all-attacks: A feature to execute multiple attack types sequentially.

    Because the primary requirement for a victim model is simply a query function, PrivacyRaven is framework-agnostic and can attack models regardless of whether they are PyTorch, TensorFlow, or other distributions.

  2. Run model extraction attacks using provided examples

    master

    PrivacyRaven provides several example scripts to demonstrate different model extraction attack scenarios. You can use these to understand how to apply attacks to MNIST models or how to integrate custom components like synthesizers and callbacks.

    Available examples include:

    • CPU-based extraction: extract_mnist_cpu.py uses the copycat synthesizer to attack an MNIST model using CPU resources.
    • GPU-based extraction: extract_mnist_gpu.py uses the copycat synthesizer to attack an MNIST model using GPU resources.
    • Custom Synthesizers: create_synthesizer.py demonstrates how to implement and apply a model extraction attack using a custom synthesizer.
    • PyTorch Lightning Callbacks: example_pytorch_callback.py demonstrates how to apply an attack using a callback from PyTorch Lightning Bolts.
  3. Run PrivacyRaven in a Docker container

    master

    You can run PrivacyRaven using a Docker container by executing the provided build script. Note that performance may be significantly impacted depending on the resources allocated to Docker.

    chmod +x build.sh
    ./build.sh
  4. Install PrivacyRaven using Poetry

    master

    To install PrivacyRaven locally, ensure you have Poetry installed, then follow these steps:

    1. Clone the repository.
    2. Update dependencies: poetry update
    3. Install the package: poetry install

    To use PrivacyRaven in a Jupyter Notebook environment, run poetry shell followed by jupyter notebook.

    git clone <repository_url>
    poetry update
    poetry install
    
    # For Jupyter Notebooks
    poetry shell
    # then run:
    # jupyter notebook
  5. Run a model extraction attack

    master

    PrivacyRaven allows you to perform model extraction attacks by providing a query function that wraps your target model. The ModelExtractionAttack class orchestrates the attack using a query function, query limits, input shapes, and seed data.

    Key components required:

    • Query Function: A function that takes input data and returns the target model's output. You can use privacyraven.utils.query.get_target to wrap a model.
    • Seed Data: Public or known data used during the extraction process.
    • Substitute Model: An architecture used to synthesize the extracted knowledge.
    import privacyraven as pr
    from privacyraven.utils.data import get_emnist_data
    from privacyraven.extraction.core import ModelExtractionAttack
    from privacyraven.utils.query import get_target
    from privacyraven.models.victim import train_four_layer_mnist_victim
    from privacyraven.models.four_layer import FourLayerClassifier
    
    # 1. Setup the target model
    model = train_four_layer_mnist_victim()
    
    # 2. Define the query function
    def query_mnist(input_data):
        return get_target(model, input_data, (1, 28, 28, 1))
    
    # 3. Obtain seed data
    emnist_train, emnist_test = get_emnist_data()
    
    # 4. Configure and run the attack
    attack = ModelExtractionAttack(
        query_mnist,             # query function
        200,                     # query limit
        (1, 28, 28, 1),          # victim input shape
        10,                      # number of targets
        (3, 1, 28, 28),          # substitute input shape
        "copycat",              # synthesizer name
        FourLayerClassifier,    # substitute model architecture
        784,                     # substitute input size
        emnist_train,            # seed train data
        emnist_test,             # seed test data
    )
  6. Generate hyperparameters with set_hparams

    master

    The set_hparams function creates a dictionary of hyperparameters used to configure PyTorch Lightning training.

    Required arguments:

    • input_size: The size of the input data.
    • targets: The number of target classes.

    Optional arguments:

    • transform: Data transformation function.
    • batch_size: Integer (default: 100).
    • num_workers: Integer (default: 4).
    • gpus: Number of GPUs to use (defaults to torch.cuda.device_count() if None).
    • max_epochs: Integer (default: 8).
    • learning_rate: Float (default: 1e-3).
    from privacyraven.utils.model_creation import set_hparams
    
    hparams = set_hparams(
        input_size=(28, 28),
        targets=10,
        batch_size=64,
        max_epochs=10,
        learning_rate=0.001
    )
  7. Register a custom synthesizer function

    master

    You can define and register your own data synthesis functions using the @register_synth decorator. Registered functions are added to the internal synths dictionary and can be invoked via the synthesize function by name.

    from privacyraven.extraction.synthesis import register_synth
    
    @register_synth
    def my_custom_synthesizer(data, query, query_limit, art_model, victim_input_shape, substitute_input_shape, victim_output_targets):
        # Implementation logic
        return x_synthetic, y_synthetic
  8. Load EMNIST datasets with get_emnist_data

    master

    Use get_emnist_data to obtain EMNIST train and test datasets. This function is typically used to obtain seed or public data for extraction tasks. It handles downloading the dataset to the current working directory and applies standard transforms by default.

    Parameters:

    • transform (torchvision.transforms): Custom transforms to apply. If None, a default composition of RGB conversion, ToTensor, and normalization is used.
    • RGB (bool): If True (default), images are converted to RGB. If False, images are treated as grayscale.
    from privacyraven.utils.data import get_emnist_data
    
    # Get EMNIST datasets with default RGB transforms
    train_set, test_set = get_emnist_data()
    
    # Get EMNIST datasets as grayscale
    train_set_gray, test_set_gray = get_emnist_data(RGB=False)
  9. Configure a ModelExtractionAttack

    master

    The ModelExtractionAttack class is the base for black-box, label-only model extraction attacks. It uses a synthesizer to create synthetic data from seed data, which is then used to train a substitute model.

    When initializing a subclass of ModelExtractionAttack, you can provide several configuration parameters to control the attack parameters, the substitute model architecture, and the training process. Note that certain attributes (like synth_train, substitute_model, etc.) are managed internally during the post-initialization phase and cannot be passed as arguments.

    from privacyraven.extraction.core import ModelExtractionAttack
    
    # Example of how one might configure a subclass of ModelExtractionAttack
    class MyAttack(ModelExtractionAttack):
        pass
    
    attack = MyAttack(
        query=my_query_function,             # Function that queries the victim model
        query_limit=500,                     # Max number of queries allowed
        victim_input_shape=(3, 224, 224),    # Shape of victim inputs
        victim_output_targets=1000,         # Number of labels in victim model
        substitute_model_arch=MyArch,        # PyTorch module for substitute architecture
        seed_data_train=my_train_tensors,    # Seed data for synthesis
        seed_data_test=my_test_tensors,     # Seed data for synthesis
        batch_size=32,
        learning_rate=1e-4,
        trainer_args=[("deterministic", True)] # List of tuples for PyTorch Lightning Trainer
    )
  10. Initialize the InversionModel for model inversion attacks

    master

    The InversionModel is a PyTorch Lightning module used to perform model inversion attacks. It consists of a decoder that attempts to reconstruct data from the classifier's outputs.

    To initialize the model, you must provide:

    • hparams: Hyperparameters for the Lightning module.
    • inversion_params: A dictionary containing the following keys:
      • nz: The size of the latent space (input channels for the decoder).
      • ngf: The number of generator filters.
      • affine_shift: The value c used for affine transformation of top-k values.
      • truncate: The value t representing the number of top-k entries to use.
    • classifier: The target PyTorch Lightning model (the classifier) that you are attacking. The InversionModel will automatically set the classifier to .eval() mode.
    from privacyraven.models.inversion_model import InversionModel
    
    inversion_params = {
        "nz": 10, 
        "ngf": 64, 
        "affine_shift": 0.5, 
        "truncate": 3
    }
    
    inversion_model = InversionModel(
        hparams=None, 
        inversion_params=inversion_params, 
        classifier=target_classifier
    )
  11. Train a 3-layer MNIST victim model with train_mnist_victim()

    master

    Use train_mnist_victim() to train a 3-layer fully connected neural network on MNIST data.

    Note: This function is deprecated. It is recommended to use train_four_layer_mnist_victim() instead, as the ThreeLayerClassifier will be deprecated.

    Parameters:

    • transform: A Torchvision.transforms object. Defaults to ToTensor and Normalize((0.1307,), (0.3081,)).
    • batch_size: Integer size of training/testing batches. Defaults to 100.
    • num_workers: Integer number of workers for data loading. Defaults to 4.
    • rand_split_val: An array describing how the val and train data are split. Defaults to [55000, 5000].
    • gpus: Integer number of GPUs. If None, it uses all available GPUs.
    • max_epochs: Maximum number of training epochs. Defaults to 8.
    • learning_rate: Float learning rate for the optimizer. Defaults to 1e-3.

    Returns: A trained ThreeLayerClassifier model ready for inference.

    # Deprecated: Use train_four_layer_mnist_victim instead
    victim_model = train_mnist_victim(batch_size=100)
  12. Get MNIST DataLoaders with get_mnist_loaders

    master

    Use get_mnist_loaders to return PyTorch DataLoader objects for MNIST training, validation, and testing. This is a convenience wrapper around get_mnist_data that handles the creation of the loaders.

    Parameters:

    • hparams (dict): A dictionary containing loader configuration.

    Required hparams keys:

    • batch_size (int): The number of samples per batch.
    • num_workers (int): Number of subprocesses to use for data loading.
    from privacyraven.utils.data import get_mnist_loaders
    
    hparams = {
        "batch_size": 64,
        "num_workers": 4,
        "rand_split_val": [55000, 5000],
        "transform": my_transform
    }
    
    train_loader, val_loader, test_loader = get_mnist_loaders(hparams)